Python 分解数字函数,接收数字以及分解方法

标签 python

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

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

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

所以函数应该返回:

[[1,1,1,1,1],[2,1,1,1],[1,2,1,1],[1,1,2,1],[1,1,1,2],[5]]

考虑到列表中的数字正在相加 所以 [1+1+1+2] 是 5!

最佳答案

这有一个非常自然的递归公式:

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

关于Python 分解数字函数,接收数字以及分解方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52267124/

相关文章:

python - 比较 Pyspark 中的列

python - 为什么这个问题发生在Python函数作用域中?

python - 连接失效时重新运行 SQLAlchemy 查询

python - Eventhub 在 python 中以列表形式读取数据

python - Python中将json转换为coo稀疏矩阵

python - django 如何获取 manytomany 字段的计数

Python 3 : How to search for a list created from a user's input?

python - 替换整个单词 Python(仅变量)

python - msys2 中的 Spidermonkey 构建失败 "OSError: [Errno 2] No such file or directory"

python - Pandas 枢轴给了我很多 'none' 值