0
How to make a list of matching combinations with a given list
I've thought of some ways to accomplish this, but my ideas just don't work, so I decided to ask. I want to create a function that takes two args x and y, (Where 'x' is an integer and 'y' is a list of integers) and then return list of combinations of 'y' that sum up to 'x'. Ex: x=4, y=[1,2] Output [1,1,1,1], [1,1,2], [1,2,1], [2,1,1], [2,2]
4 Antworten
+ 3
Use recursion. Think what happens when you choose 1/2.
+ 1
I think I may have an idea. You can use itertools's permutations() function, which allows you to iterate through a list and create a permutations class containing tuples with the permutations; you can use this with y. You can then loop through each tuple, and check if the items add up to x.
To use permutations, all you have to do is:
from itertools import permutations
y = [1, 2]
perm = permutations(y) #get the possible combinations of the items in list
for item in perm:
print(item) #print each tuple in our collection of permutations
+ 1
Fabian Nwobi, sorry, my bad. I attempted to create this algorithm, but it can still be improved. It works though, I believe.
https://code.sololearn.com/c8wz88RgMCO8/?ref=app
0
jianmin, the permutation of [1,2] returns [(1,2),(2,1)], hence it won't work