簡體   English   中英

Python-總和大於或等於值的數字組合

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

最近,我提出了以下要在Python中回答的面試問題-給定數量-值對的列表,找到其總和與所提供的某些值接近且至少一樣大的值集的最佳組合值。

例如,給定:[[(1,$ 5),(3,$ 10),(2,$ 15)],並且期望值為$ 36,則答案將為[(2,$ 15),(1,$ 10)]或[(1,$ 15),(2,$ 10),(1,$ 5)]。 原因是$ 40是可以達到或大於或等於$ 36的最小總和,這是實現該總和的兩種方法。

我很沮喪 有沒有人有辦法解決嗎?

數字太小了,您可以蠻力地對待它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM