【问题标题】:Find the best combination of n element from a list that satisfies specific conditions从满足特定条件的列表中找到n个元素的最佳组合
【发布时间】:2023-02-04 23:48:43
【问题描述】:

我正在开发一个函数来解决任意列表中需要满足某些条件的任意组合。具体案例如下图: 给定一个包含 9 个元素的列表

[3,2,5,8,9,11,45,12,44],

找到元素的最佳组合,以便这些元素的总和 < 90 并且删除了最少数量的元素.

我正在考虑使用 itertools.combinations 甚至 Google ORTools,但还没有想出解决方案。请分享任何想法,谢谢!

【问题讨论】:

  • 那怎么不只是贪婪呢?该输入的正确结果是什么?
  • 您的具体情况可以通过排序数组上的窗口总和来解决(O(n log n) 进行排序,O(n) 进行查找)- 基本的贪心算法,因此您应该提供更通用的条件或解释为什么这不适合.. .

标签: python list combinations python-itertools or-tools


【解决方案1】:

您可以按降序对列表进行排序,然后遍历所有组合。

import itertools

def find_best_combination(lst, target_sum):
    lst.sort(reverse=True)
    for i in range(len(lst), 0, -1):
        for comb in itertools.combinations(lst, i):
            if sum(comb) < target_sum:
                return comb
    return lst

lst = [3, 2, 5, 8, 9, 11, 45, 12, 44]
print(lst)
result = find_best_combination(lst, 90)
print(result)

输出:

[3, 2, 5, 8, 9, 11, 45, 12, 44]
(45, 12, 11, 9, 5, 3, 2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    • 2018-08-23
    • 2014-05-22
    • 1970-01-01
    相关资源
    最近更新 更多