内存中的递归

时间:2014-04-10 22:57:08

标签: python recursion

def rec(x):
    if x < 2:
        return 1
    else:
        a = rec(x-1)
        b = rec(x-2)
        return a+b
rec(4)

我不明白这在记忆中有用,或者为什么它会返回5.有人可以帮助我吗?

4 个答案:

答案 0 :(得分:1)

使用print语句,它将使递归过程更加清晰: 基本上它会一遍又一遍地调用rec,直到它遇到x < 2时的“基本情况”。它必须递归调用,直到它击中基本情况,然后一直回来。

输入

def rec(x):
    if x < 2:
        return 1
    else:
        print "x = ", x
        a = rec(x-1)
        print "a = ", a
        b = rec(x-2)
        print "b = ", b
        return a+b
rec(4)

输出

x =  4
x =  3
x =  2
a =  1
b =  1
a =  2
b =  1
a =  3
x =  2
a =  1
b =  1
b =  2
5

答案 1 :(得分:1)

让我们映射出来的电话:

                                  rec(4)
                rec(3)              +              rec(2)
      rec(2)       +     rec(1)     +      rec(1)    +      rec(0)
rec(1)  +  rec(0)  +       1        +        1       +        1
  1     +    1     +       1        +        1       +        1

所以你可以看到那里(以及通过查看代码)每次调用rec(i) i >= 2,它会分成rec(i-1) + rec(i-2),当我们i < 2时在基本情况下,调用只返回1。因此,通过编写类似于我上面所做的内容,您可以跟踪调用,直到您剩下的只是基本情况。

答案 2 :(得分:0)

作为Cyber​​的答案的补充,这里的输出表明了递归的深度:

def rec(x, depth=0):
    print " "*(depth*3), "x =", x
    if x < 2:
        print " "*(depth*3), "=> 1"
        return 1
    else:
        a = rec(x-1, depth+1)
        print " "*(depth*3), "a =", a
        b = rec(x-2, depth+1)
        print " "*(depth*3), "b =", b
        print " "*(depth*3), "=>", a+b
        return a+b

rec(4)

输出:

 x = 4
    x = 3
       x = 2
          x = 1
          => 1
       a = 1
          x = 0
          => 1
       b = 1
       => 2
    a = 2
       x = 1
       => 1
    b = 1
    => 3
 a = 3
    x = 2
       x = 1
       => 1
    a = 1
       x = 0
       => 1
    b = 1
    => 2
 b = 2
 => 5

答案 3 :(得分:0)

假设每个缩进表示另一层递归(它在更深层次的函数调用中)。注意,当x < 2,我假设你理解为什么rec(x)= 1。

rec(4)
    a = rec(3)
        a = rec(2)
            a = rec(1) = 1
            b = rec(0) = 1
            return a + b
        #a = 1 + 1 = 2
        b = rec(1)
        return a + b
    #a = 2 + 1 = 3
    b = rec(2)
        a = rec(1) = 1
        b = rec(0) = 1
        return a + b
    #b = 1 + 1 = 2
    return a + b
#rec(4) = 5