Python分解接收数字的函数和分解方法

2024-09-30 10:28:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个函数,用给定的数字分解一个数字:

例如分解的数字是5,分解的方式是1,2,5

def func(Number_to_decompose,list_with posible_ways_to_decompose)
func(5,[1,2,5])

因此函数应该返回:

^{pr2}$

考虑到名单上的数字正在增加 所以[1+1+1+2]是5!在


Tags: to函数numberdefwith方式数字list
2条回答

{1>尝试在CDS之外检查理解力:

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]))

输出:

^{pr2}$

如果需要名单:

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]]

一个非常自然的公式是:

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])gt;匹配您请求的输出。在

相关问题 更多 >

    热门问题