我正在尝试创建一个分解仅具有给定数字的数字的函数:
例如分解的数字为5,分解的方式为1,2,5
0 1 2 3
0 star tshirt large red None
0 star tshirt large blue None
0 beautiful rainbow skirt small None None None
0 long maxwell logan jeans light blue 32L 28W
0 long maxwell logan jeans Dark blue 32L 28W
因此函数应返回:
beautiful rainbow skirt small
考虑到列表中的数字相加 所以[1 + 1 + 1 + 2]是5!
答案 0 :(得分:1)
尝试在列表理解中使用itertools.product
进行不同的重复,然后在列表理解之外进行检查:
import itertools
def func(n,l):
return [a for i in [itertools.product(l,repeat=x) for x in range(1,6)] for a in i if sum(a) == n]
print(func(5,[1,2,5]))
输出:
[(5,), (1, 2, 2), (2, 1, 2), (2, 2, 1), (1, 1, 1, 2), (1, 1, 2, 1), (1, 2, 1, 1), (2, 1, 1, 1), (1, 1, 1, 1, 1)]
如果需要列表列表:
print(list(map(list,func(5,[1,2,5]))))
输出:
[[5], [1, 2, 2], [2, 1, 2], [2, 2, 1], [1, 1, 1, 2], [1, 1, 2, 1], [1, 2, 1, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]
答案 1 :(得分:1)
这具有相当自然的递归公式:
from copy import copy
def recurse_find(decomposed,remaining,valid_numbers):
#base case
if remaining == 0:
return decomposed
#find all valid subtractions
else:
ans = []
for number in valid_numbers:
if remaining - number >= 0:
new_decomposed = copy(decomposed)
new_decomposed.append(number)
cand = recurse_find(new_decomposed,remaining-
number,valid_numbers)
if cand:
ans.append(cand)
if len(ans) > 0:
return ans
print(recurse_find([],5,[1,2,5]))->与您请求的输出匹配。