[英]Fill a list randomly with 2 digits of all possible combinations of them so that the sum of the elements of the list gives a given number
我知道我提到的标题唤起了这里已经提到的许多其他主题(如库 itertools),但没有一个可以给我一个解决方案。 我的问题并不难理解。 我有 2 个数字(比如 1 和 2),我想把它们放在一个列表中,这样列表中数字的总和给我一个数字(比如 5),我需要知道这个列表中所有可能的组合。 例如 :
a = 1
b = 2
L = [1, 2, 2] -> 5
L = [1, 1, 1, 1, 1] -> 5
L = [1, 1, 1, 2] -> 5
.
.
.
我希望能够描述我的问题,我感到失望已经超过 2 天了。
祝大家有个美好的一天
稍微修改一下我在提议的副本中展示的想法:
from collections import Counter
def subset_sum(vals, target):
counts = [[Counter()]] + [[] for _ in range(target)]
for val in vals:
for i in range(val, target + 1):
counts[i] += [c + Counter({val: 1}) for c in counts[i-val]]
return counts[target]
这给出了结果:
>>> for counts in subset_sum(vals=(1, 2), target=5):
... L = [*counts.elements()]
... print(L, "->", sum(L))
[1, 1, 1, 1, 1] -> 5
[1, 1, 1, 2] -> 5
[1, 2, 2] -> 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.