[英]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
I know that the title I mentioned evokes many other topics already mentioned here (like library itertools) but none could give me a solution.我知道我提到的标题唤起了这里已经提到的许多其他主题(如库 itertools),但没有一个可以给我一个解决方案。 My problem is not complicated to understand.
我的问题并不难理解。 I have 2 digits (say 1 and 2) and I want to put them in a list so that the sum of the numbers in the list gives me a number (say 5) and I need to know all possible combinations from this list there.
我有 2 个数字(比如 1 和 2),我想把它们放在一个列表中,这样列表中数字的总和给我一个数字(比如 5),我需要知道这个列表中所有可能的组合。 For example :
例如 :
a = 1
b = 2
L = [1, 2, 2] -> 5
L = [1, 1, 1, 1, 1] -> 5
L = [1, 1, 1, 2] -> 5
.
.
.
I hope to have been able to describe my problem, it's been more than 2 days that I ream disappointed.我希望能够描述我的问题,我感到失望已经超过 2 天了。
Good day to all祝大家有个美好的一天
With a slight modification of the idea I showed in the proposed duplicate:稍微修改一下我在提议的副本中展示的想法:
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]
This gives the result:这给出了结果:
>>> 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.