From what I can tell, the code block you've provided appears to be a modification of an algorithm from an answer to a previous question which asked how to generate all combinations of a list
that sum to a given number. However, your modification appears to generate permutations as opposed to combinations.
If you want the permutations, consider that those permutations which are solutions to the sum(numbers) == target
condition are also permutations of the elements of those combinations which are solutions to the same. So what you may want to do instead is find the combinations which satisfy the relation and take the permutations of the elements of those solutions to get all permutations of the list
which are solutions of the condition. i.e.,
from itertools import combinations, permutations
def subset_sum(numbers, target):
for length in range(len(numbers)):
for combination in combinations(numbers, length):
if sum(combination) == target:
for permutation in permutations(combination, len(combination)):
print("sum({}) = {}".format(list(permutation), target))
s = [2, 4]
k = [22, 25, -11, 13, 58]
x = [100, 101, 23]
v = [77, 88, 99]
y = s + k + x + v
if __name__ == "__main__":
subset_sum(y, 47)
Note that calling subset_sum(k, 47)
still prints the same solutions:
sum([22, 25]) = 47
sum([25, 22]) = 47
sum([-11, 58]) = 47
sum([58, -11]) = 47
And calling subset_sum(y, 47)
prints:
sum([22, 25]) = 47
sum([25, 22]) = 47
sum([-11, 58]) = 47
sum([58, -11]) = 47
sum([2, 22, 23]) = 47
sum([2, 23, 22]) = 47
sum([22, 2, 23]) = 47
sum([22, 23, 2]) = 47
sum([23, 2, 22]) = 47
sum([23, 22, 2]) = 47
sum([22, -11, 13, 23]) = 47
sum([22, -11, 23, 13]) = 47
sum([22, 13, -11, 23]) = 47
sum([22, 13, 23, -11]) = 47
sum([22, 23, -11, 13]) = 47
sum([22, 23, 13, -11]) = 47
sum([-11, 22, 13, 23]) = 47
sum([-11, 22, 23, 13]) = 47
sum([-11, 13, 22, 23]) = 47
sum([-11, 13, 23, 22]) = 47
sum([-11, 23, 22, 13]) = 47
sum([-11, 23, 13, 22]) = 47
sum([13, 22, -11, 23]) = 47
sum([13, 22, 23, -11]) = 47
sum([13, -11, 22, 23]) = 47
sum([13, -11, 23, 22]) = 47
sum([13, 23, 22, -11]) = 47
sum([13, 23, -11, 22]) = 47
sum([23, 22, -11, 13]) = 47
sum([23, 22, 13, -11]) = 47
sum([23, -11, 22, 13]) = 47
sum([23, -11, 13, 22]) = 47
sum([23, 13, 22, -11]) = 47
sum([23, 13, -11, 22]) = 47
If, however, you only want the combinations, the code is simply:
from itertools import combinations, permutations
def subset_sum(numbers, target):
for length in range(len(numbers)):
for combination in combinations(numbers, length):
if sum(combination) == target:
print("sum({}) = {}".format(list(combination), target))
s = [2, 4]
k = [22, 25, -11, 13, 58]
x = [100, 101, 23]
v = [77, 88, 99]
y = s + k + x + v
if __name__ == "__main__":
subset_sum(y, 47)
Where calling subset_sum(k, 47)
prints:
sum([22, 25]) = 47
sum([-11, 58]) = 47
And calling subset_sum(y, 47)
prints:
sum([22, 25]) = 47
sum([-11, 58]) = 47
sum([2, 22, 23]) = 47
sum([22, -11, 13, 23]) = 47