【问题标题】:Python - Combination of Numbers Summing to Greater than or Equal to a ValuePython - 总和大于或等于某个值的数字组合
【发布时间】:2017-08-31 02:20:54
【问题描述】:

我最近被提出了以下用 Python 回答的面试问题 - 给定一个数量-值对列表,找到总和尽可能接近且至少与, 一些提供的价值。

例如,给定:[(1, $5), (3, $10), (2, $15)],期望值为 $36,答案将是 [(2,$15), (1,$10 )] 或 [(1,$15), (2,$10), (1,$5)]。原因是 40 美元是可以达到的大于或等于 36 美元的最小金额,这是达到该金额的两种方法。

我被难住了。有人有解决办法吗?

【问题讨论】:

  • 你可以试试itertools.combinations
  • 找出给定量值对的所有组合,然后取最小元素[s]

标签: python permutation dynamic-programming number-theory


【解决方案1】:

数字太小了,你可以用暴力破解它:

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))

您可以将其扩展到所有组合,只需将 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)})

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 2015-09-19
    • 2014-12-20
    • 2014-07-19
    • 2018-09-01
    • 2020-11-22
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    相关资源
    最近更新 更多