[英]How to find all possible combinations of dictionary values that add up to a certain number in Python while still retaining the key names
[英]How to find all combinations of numbers summing up to a certain number?
给出一个总和,例如 25,并给出数字,例如 2、5、10 您需要找到所有组合来选择这个数量。 即程序应为 output 5 + 5 + 5 + 5 + 5、5 + 5 + 5 + 10、5 + 10 + 10、2 + 2 + 2 + 2 + 2 + 10 + 5 等等。
您推荐使用哪些算法/方法/库?
您可以使用itertools
获取所有组合,然后只保留总和为 25 的组合。我使用with_replacement
是因为相同的值可以出现两次。 此外,我使用了地板部门,因为没有一个数字比最小的数字更频繁。
from itertools import combinations_with_replacement
candidates = list()
for i in range(25//2): # floor division of largest by smallest
candidates.extend(list(combinations_with_replacement([2, 5, 10], i)))
positive_cases = [i for i in candidates if sum(i) == 25]
[(5, 10, 10), (5, 5, 5, 10),
(5, 5, 5, 5, 5), (2, 2, 2, 2, 2, 5, 10),
(2, 2, 2, 2, 2, 5, 5, 5),
(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.