I'm trying to get a list of all possible unique combinations from a provided list of values which sum result in an also provided target value. I'm a beginner and have seen some content about the coin change problem, however, this is somewhat different, since I'm not trying to get the minimum number of elements. I've tried many approaches, because recursion is very new and difficult to me, I've come up with this code, that stopped giving me a recursion error after I increased the recursion limit, but it only gives one combination every time
from random import choice as pick
import sys
sys.setrecursionlimit(5000)
def find_combinations(elements, target, partial=None, results=None):
if results is None:
results = []
if partial is None:
partial = []
if len(results) == 2:
return results
else:
rand_num = pick(elements)
if partial.count(rand_num) < elements.count(rand_num):
partial.append(rand_num)
total = sum(partial)
if total == target:
if partial not in results:
results.append(partial)
print(results)
partial.clear()
find_combinations(elements, target, partial, results)
elif total > target:
partial.clear()
find_combinations(elements, target, partial, results)
elif total < target:
find_combinations(elements, target, partial, results)
as you can see, the len is arbitrary. I can't seem to be able to break out of the recursion.Any solution would be apreciated :)
import itertools
stuff = [1, 2, 3]
Target = 3
for L in range(0, len(stuff)+1):
for subset in itertools.combinations(stuff, L):
if sum(subset) == Target:
print(subset)
You can loop through each combination using itertools
and if the sum of this subset is equal to the target you do whatever you want here i printed it, the output:
(3,)
(1, 2)