I know that the title I mentioned evokes many other topics already mentioned here (like library itertools) but none could give me a solution. 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. 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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.