【问题标题】:All possible change combinations所有可能的变化组合
【发布时间】:2020-05-26 04:25:01
【问题描述】:

我正在尝试输出一个列表列表,其中包含给定数量和硬币的所有可能的变化组合。 例如 - 给定金额 6 和硬币 = [1,5,10] 我会得到:

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

我写了一些打印正确解决方案的东西,但我不知道如何让函数以列表格式输出解决方案

def possible_change(n,p=[],coins = [1,5,10]):
    if n == 0:
        print(p)
        return p
    else:
        for c in coins:
            if n - c >= 0:
                possible_change(n-c,p+[c],coins=coins)

possible_change(6,coins=[1,5,10])

如何让函数返回实际列表?

【问题讨论】:

  • 您可以创建一个全局列表并附加到它而不是打印。我认为创建一个将列表作为属性并将函数作为方法的类会更好。

标签: python recursion


【解决方案1】:

代替那些打印语句,只需填充一个全局列表。

sols = []
def possible_change(n,p=[],coins = [1,5,10]):
    if n == 0:
        global sols
        sols.append(p)
    else:
        for c in coins:
            if n - c >= 0:
                possible_change(n-c,p+[c],coins=coins)    

possible_change(6,coins=[1,5,10])
print(sols)

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

【讨论】:

    【解决方案2】:

    如果 n - c 小于 0 或 for loop for c in coins: 结束,您可以尝试向函数添加一个总列表并返回它

    def possible_change(n,p=[],coins = [1,5,10], total=[]):
        if n == 0:
            total.append(p)
        else:
            for c in coins:
                if n - c >= 0:
                    print("c {}".format(c))
                    possible_change(n-c,p+[c],coins=coins)
                else:
                    return total
        return total
    
    print(possible_change(6,coins=[1,5,10]))
    

    结果

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多