python求任意个连续整数的和_python 给定一个正整数a和一个包含任意个正整数的 列表 b,求所有<=a 的加法组合...

例如,10,[1,2,3]

输出类似:

1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1

2 + 2 + 2 +2 + 2

3 + 3 + 3 + 2

3 + 2 + 2 + 2 + 1

注意:是小于等于,list 内的正整数有可能并不能正好等于 a.

通过itertools.combinations_with_replacement我们写短一点的代码:

def solve2(lst, bound):

max_length = bound // min(lst)

for n in range(1, max_length+1):

for c in itertools.combinations_with_replacement(lst,n):

if sum(c) <= bound:

print('+'.join(map(str, c)))

solve2([1,2,3], 10)

假設該問題符合下列假設:

列表內元素可重複使用

只要是能滿足小於等於上限值的組合都可接受, 就算遠小於上限值甚至是零也可以

以下是暴力法:

# code for python3

from itertools import combinations

def solve(lst, upperbound):

candidates = []

for n in lst:

for count in range(upperbound//n):

candidates.append(n)

allcomb = set()

for l in range(1, len(candidates)+1):

for comb in combinations(candidates, l):

if not comb in allcomb:

allcomb.add(comb)

if sum(comb) <= upperbound:

print('+'.join([str(n)for n in comb]))

solve([1,2,3], 10)

我回答過的問題: Python-QA

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值