Python结束后在这里做的递归是什么?

时间:2017-11-20 00:35:14

标签: python recursion

我是python编程的新手。我为递归写了一个小脚本,帮助我理解递归循环中发生了什么。但是在递归结束后,我不理解我的脚本的最后部分以及它正在做什么。这是我的剧本。

def test(n, m, p, k):
    print(n, m, p, k, 'This is the value coming in.')
    if n > 0:
        print(n, m, p, k, 'This is before recursion.')
        test(n-1, p, k, m)
        print(n, m, p, k, 'This is when n = 1.' )

这是我运行>>>时的结果测试(5,10,20,30)

5 10 20 30 This is the value coming in.
5 10 20 30 This is before recursion.
4 20 30 10 This is the value coming in.
4 20 30 10 This is before recursion.
3 30 10 20 This is the value coming in.
3 30 10 20 This is before recursion.
2 10 20 30 This is the value coming in.
2 10 20 30 This is before recursion.
1 20 30 10 This is the value coming in.
1 20 30 10 This is before recursion.
0 30 10 20 This is the value coming in.
1 20 30 10 This is when n = 1.
2 10 20 30 This is when n = 1.
3 30 10 20 This is when n = 1.
4 20 30 10 This is when n = 1.
5 10 20 30 This is when n = 1.

为什么最后5个打印功能从n = 1升到n = 5?

1 个答案:

答案 0 :(得分:1)

那是所有电话都打开的时候。 n正在下降,所以当它解包时,它将以相反的顺序(第一次调用是最后解决的)。您可以通过查看最后几行中的详细参数来看到这一点。