算法 - python 给定一个正整数a和一个包含任意个正整数的 列表 b,求所有<=a 的加法组合
PHP中文网
PHP中文网 2017-04-18 10:28:42
[Python讨论组]

例如,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.

PHP中文网
PHP中文网

认证0级讲师

全部回复(2)
大家讲道理

通过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)
巴扎黑

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

  1. 列表內元素可重複使用

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

以下是暴力法:

# 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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号