Generate all possible lists of length N that sum to S in Python
Using a generator saves on memory (usexrange
instead of range
if using Python 2). This is what I came up with. It is very similar to your nToSum
without the need for compress
.
def sums(length, total_sum):
if length == 1:
yield (total_sum,)
else:
for value in range(total_sum + 1):
for permutation in sums(length - 1, total_sum - value):
yield (value,) + permutation
L = list(sums(5,100))
print('total permutations:',len(L))
# First and last 10 of list
for i in L[:10] + L[-10:]:
print(i)
Output
total permutations: 4598126
(0, 0, 0, 0, 100)
(0, 0, 0, 1, 99)
(0, 0, 0, 2, 98)
(0, 0, 0, 3, 97)
(0, 0, 0, 4, 96)
(0, 0, 0, 5, 95)
(0, 0, 0, 6, 94)
(0, 0, 0, 7, 93)
(0, 0, 0, 8, 92)
(0, 0, 0, 9, 91)
(98, 0, 2, 0, 0)
(98, 1, 0, 0, 1)
(98, 1, 0, 1, 0)
(98, 1, 1, 0, 0)
(98, 2, 0, 0, 0)
(99, 0, 0, 0, 1)
(99, 0, 0, 1, 0)
(99, 0, 1, 0, 0)
(99, 1, 0, 0, 0)
(100, 0, 0, 0, 0)