返回1到n的所有组合python,在Python中找到所有n个正数加起来等于k个的所有组合?...

How would I efficiently find all the possible combinations of n positive integers adding up to a given number k in Python?

I know I could solve this by filtering all the possible combinations:

import itertools

def to_sum_k(n, k):

for i in itertools.product(range(1, k - n + 2), repeat=n):

if sum(i) == k:

yield i

print(list(to_sum_k(3, 5)))

# [(1, 1, 3), (1, 2, 2), (1, 3, 1), (2, 1, 2), (2, 2, 1), (3, 1, 1)]

I have seen something similar has been discussed in abstract way here, but I do not see a simple way of translating this into code.

Also, I would prefer an iterative solution over a recursive one.

解决方案

A recursive solution based on this:

def to_sum_k_rec(n, k):

if n == 1:

yield (k,)

else:

for x in range(1, k):

for i in to_sum_k_rec(n - 1, k - x):

yield (x,) + i

print(list(to_sum_k_rec(3, 5)))

# [(1, 1, 3), (1, 2, 2), (1, 3, 1), (2, 1, 2), (2, 2, 1), (3, 1, 1)]

And an iterative one:

import itertools

def to_sum_k_iter(n, k):

index = [0] * (n + 1)

index[-1] = k

for j in itertools.combinations(range(1, k), n - 1):

index[1:-1] = j

yield tuple(index[i + 1] - index[i] for i in range(n))

print(list(to_sum_k_iter(3, 5)))

# [(1, 1, 3), (1, 2, 2), (1, 3, 1), (2, 1, 2), (2, 2, 1), (3, 1, 1)]

Time-wise, the recursive solution seems to be fastest:

%timeit list(to_sum_k_OP(4, 100))

# 1 loop, best of 3: 13.9 s per loop

%timeit list(to_sum_k_rec(4, 100))

# 10 loops, best of 3: 101 ms per loop

%timeit list(to_sum_k_iter(4, 100))

# 1 loop, best of 3: 201 ms per loop

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值