首页 > 解决方案 > 了解 Python 堆栈中的递归

问题描述

我试图了解递归,当我编写一小段代码时,我不知道它是如何达到特定输出的。

x = 0
def recursion():
    global x
    x += 1
    print(x)
    while x < 5:
        recursion()
        recursion()
        print("example")
    print("test")
recursion()

输出:

1
2
3
4
5
test
6
test
example
test
7
test
example
test
8
test
example
test
9
test
example
test

如果有人可以逐步解释,我将不胜感激。

标签: pythonrecursion

解决方案


这就是发生的事情,一步一步。第一次打电话:

def recursion():
      global x
      x += 1
      print(x)  # x ==1
      while x < 5:
        recursion() # on hold, executing recursion

def recursion():
      global x
      x += 1
      print(x)  # x ==2
      while x < 5:
        recursion() # on hold, executing recursion
.
.
.
.

def recursion():
      global x
      x += 1  
      print(x) # x == 5, skipping while loop
      while x < 5:
        recursion()
      print('test') # printing test

现在恢复所有保持的呼叫:

def recursion():
      global x
      x += 1
      print(x)
      while x < 5:
        recursion() # Called when x == 1
        recursion() # Resuming, this will put x to 6 and print it, won't enter the loop, so prints test directly
        print('example') # print example


def recursion():
      global x
      x += 1
      print(x)
      while x < 5:
        recursion() # Called when x == 2
        recursion() # Resuming, this will put x to 7 and print it, won't enter the loop, so prints test directly
        print('example') # print example

直到调用 x==4


推荐阅读