我真的需要这个python代码说明

时间:2019-11-11 12:51:03

标签: python recursion

我在python中有一个代码,该代码使用金额和硬币更改数组作为参数,并基于可能用于提供货币或金额的硬币组合的数量(作为完整的深度信息)。但是这里的问题是我似乎不知道这种递归的工作原理

我已经找到了有效的代码,但是自从我的countChange(4, [1,2])代码得到了这之后,我需要一些关于如何工作的解释。 这里的问题是它是如何工作的,因为我注意到下面的代码, 数量开始减少,数组为零

def countChange(amount, coins):
    if (amount == 0):
        print("amount is 0", amount, coins)
        return 1
    elif (amount < 0 or coins == []):

        print("amount is less than 0 or empty coins array", amount, coins)
        return 0
    else:
        countChange(amount, coins[:-1])
        print("first called")
        countChange(amount - coins[-1], coins)
        print("second called")

countChange(4, [1,2])

我真的不知道这种正确结果是怎么发生的。

from python3 myprogram_name.py
amount is less than 0 or empty coins array 4 []
first called
amount is less than 0 or empty coins array 3 []
first called
amount is less than 0 or empty coins array 2 []
first called
amount is less than 0 or empty coins array 1 []
first called
amount is 0 0 [1]
second called
second called
second called
second called
first called
amount is less than 0 or empty coins array 2 []
first called
amount is less than 0 or empty coins array 1 []
first called
amount is 0 0 [1]
second called
second called
first called
amount is 0 0 [1, 2]
second called
second called

来回走动

1 个答案:

答案 0 :(得分:0)

第一次,

countChange(4, [1,2])

金额不为零,且coins数组不为空,否则语句生效。在else语句内部,有一个递归调用,

countChange(4, [1])-------->opened

然后再次进入else语句,并再次调用递归,

countChange(4, [])----->opened

现在进入elif语句,打印字符串并返回零,称为。因此最后的递归调用将结束。

countChange(4, [])------>ended..

在该else块上仍然有3条语句。

print("first called")
countChange(amount - coins[-1], coins)
print("second called")

因此,将打印出“第一个被调用”字符串。再次进行递归调用,现在我们用counts [-1]减去数量值,所以数量= 4-1 = 3。

countChange(3, [1])----->opened

再次类似于,else语句被激活,并再次进行递归调用,

countChange(3, [])----->opened

这样,如果您跟踪递归,则可以清除。 希望对您有帮助:)