您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中生成所有长度为N的总和为S的所有可能列表

在Python中生成所有长度为N的总和为S的所有可能列表

使用生成器可以节省内存(如果不使用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)
python 2022/1/1 18:45:50 有326人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶