使用生成器可以节省内存(如果不使用Python 2,请使用xrange
代替range
)。这就是我想出的。它非常类似于您,nToSum
而无需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)