算法 - python 给定一个正整数a和一个包含任意个正整数的 列表 b,求所有<=a 的加法组合
本文介绍了算法 - 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)
这篇关于算法 - python 给定一个正整数a和一个包含任意个正整数的 列表 b,求所有<=a 的加法组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文