递归硬币更改功能打印正确答案但不返回它

时间:2017-02-04 19:55:45

标签: python algorithm recursion divide-and-conquer

使用下面的函数,它会在基本情况条件下打印问题的正确答案,但不会返回它。我的输出从第一行的函数中的基本案例打印,然后从第二行的函数打印返回的值。

如果我返回递归调用的值,则不会达到基本情况。

我看到这个输出:

[1,0,0,0,1]

但我希望这个输出:

[1,0,0,0,1]

[1,0,0,0,1]

def changeslow(amounts, goal, coins = [], highest = 0, sum = 0, results = []):
    # Base case
    if sum == goal:
        result = [] 
        if highest == amounts[(len(amounts)-1)]:
            result = []
            for amount in amounts:
                count = coins.count(amount)
                result.append(count)
                count = count + 1 
            print result
        return result

    # Recursive case
    for value in amounts:
        if value >= highest:
            copy = coins[:]
            copy.append(value)
            if sum + value <= goal:
                changeslow(amounts, goal, copy, value, sum + value, results)


amounts = [1, 5, 10, 25, 50]

print(changeslow(amounts, 51))

0 个答案:

没有答案