久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

算法 - python 給定一個(gè)正整數(shù)a和一個(gè)包含任意個(gè)正整數(shù)的 列表 b,求所有<=a 的加法組合

瀏覽:163日期:2022-08-19 08:44:47

問題描述

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

輸出類似:1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 12 + 2 + 2 +2 + 23 + 3 + 3 + 23 + 2 + 2 + 2 + 1

注意:是小于等于,list 內(nèi)的正整數(shù)有可能并不能正好等于 a.

問題解答

回答1:

通過itertools.combinations_with_replacement我們寫短一點(diǎn)的代碼:

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)回答2:

假設(shè)該問題符合下列假設(shè):

列表內(nèi)元素可重複使用

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

以下是暴力法:

# code for python3from itertools import combinationsdef 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

標(biāo)簽: Python 編程
主站蜘蛛池模板: 浦城县| 灵山县| 玉树县| 江孜县| 穆棱市| 肥西县| 晴隆县| 百色市| 萍乡市| 宁武县| 泾川县| 仁寿县| 象山县| 泾源县| 全南县| 将乐县| 泾川县| 江华| 高密市| 普兰县| 林西县| 肥城市| 墨脱县| 聂荣县| 佛学| 兴城市| 庆云县| 盐城市| 怀化市| 登封市| 怀宁县| 梨树县| 天镇县| 油尖旺区| 恭城| 五莲县| 高邑县| 左贡县| 上饶市| 德令哈市| 滕州市|