[英]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.