from itertools import product, compress def sub_sum(L, goal): return [ tuple(compress(L,f)) for f in product([0, 1], repeat=len(L)) if sum(compress(L,f)) == goal ] L = [ 25, 30, 15, 20, 30, 40, 35, 10 ] R = sub_sum(L, 120) for item in R: print(item)
Standard input is empty
(15, 30, 40, 35) (15, 20, 40, 35, 10) (30, 20, 30, 40) (30, 15, 40, 35) (30, 15, 30, 35, 10) (25, 20, 40, 35) (25, 20, 30, 35, 10) (25, 15, 30, 40, 10) (25, 30, 30, 35) (25, 30, 20, 35, 10) (25, 30, 15, 40, 10) (25, 30, 15, 20, 30)