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]

8th Jan 2020, 10:25 PM
Fabian Nwobi
Fabian Nwobi - avatar
4 Respuestas
+ 3
Use recursion. Think what happens when you choose 1/2.
8th Jan 2020, 10:36 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 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
8th Jan 2020, 10:42 PM
Jianmin Chen
Jianmin Chen - avatar
+ 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
9th Jan 2020, 2:15 AM
Jianmin Chen
Jianmin Chen - avatar
0
jianmin, the permutation of [1,2] returns [(1,2),(2,1)], hence it won't work
8th Jan 2020, 11:02 PM
Fabian Nwobi
Fabian Nwobi - avatar