简体   繁体   English

Python-总和大于或等于值的数字组合

[英]Python - Combination of Numbers Summing to Greater than or Equal to a Value

I was recently posed the following interview question to be answered in Python - given a list of quantity-value pairs, find the optimal combination(s) of sets of values whose sum is as close to, and at least as large as, some provided value. 最近,我提出了以下要在Python中回答的面试问题-给定数量-值对的列表,找到其总和与所提供的某些值接近且至少一样大的值集的最佳组合值。

For example, given: [(1, $5), (3, $10), (2, $15)], and a desired value of $36, the answer would be [(2,$15), (1,$10)] or [(1,$15), (2,$10), (1,$5)]. 例如,给定:[[(1,$ 5),(3,$ 10),(2,$ 15)],并且期望值为$ 36,则答案将为[(2,$ 15),(1,$ 10)]或[(1,$ 15),(2,$ 10),(1,$ 5)]。 The reason is that $40 is the least sum greater than or equal to $36 that can be achieved, and these are the two ways to achieve that sum. 原因是$ 40是可以达到或大于或等于$ 36的最小总和,这是实现该总和的两种方法。

I got stumped. 我很沮丧 Does anyone have a solution? 有没有人有办法解决吗?

The numbers are so small you can just brute force it: 数字太小了,您可以蛮力地对待它:

In []:
notes = [(1, 5), (3, 10), (2, 15)]
wallet = [n for a, b in notes for n in [b]*a]
combs = {sum(x): x for i in range(1, len(wallet)) for x in it.combinations(wallet, i)}

target = 36
for i in sorted(combs):
    if i >= target:
        break
i, combs[i]

Out[]:
(40, (5, 10, 10, 15))

You can extend this for all combinations, just replace the combs dictionary comprehension with: 您可以将其扩展到所有组合,只需将combs词典理解替换为:

combs = {}
for i in range(1, len(wallet)):
    for x in it.combinations(wallet, i):
        combs.setdefault(sum(x), set()).add(x)

...
i, combs[i]

Out[]:
(40, {(5, 10, 10, 15), (10, 15, 15)})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Python中的字典找到值总和等于或大于k的键的可能组合? - How to find possible combination of keys having sum of values equal or greater than k using dictionary in Python? 在 Python Selenium 中等待某个值大于等于某个数 - Waiting for a value to be greater than or equal to a certain number in Python Selenium python 中的“大于”或“等于”与“等于”或“大于” - “Greater than” or “equal” vs “equal” or “greater than” in python 如何在 python 中删除列表中大于或等于指定数字的数字 - How do you remove numbers greater than or equal to a specified number within a list, in python 在Python中具有加号,等于号和大于号的表达式 - Expression with plus, equal, and greater than symbols in python 如何使 python 大于/小于或等于? - How to make a greater/less than or equal to on python? Python-Pandas Dataframe:计数值大于或等于 dataframe 中的值 - Python-Pandas Dataframe: count values greater than or equal to a value in the dataframe 如何使用 Python 查找等于或大于给定总和的值组合? - How To Use Python to find combinations of value with equal or greater than given sum? Python Pandas:有效计算值大于或等于一组值的行数,按键列分组 - Python Pandas: Efficiently compute count of rows with value greater than or equal to a set of values, grouped by key columns 等于或大于 0 时对三个连续数求和 - Python - Summing three consecutive number when equal to or great than 0 - Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM