首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >了解Python堆栈中的递归

了解Python堆栈中的递归
EN

Stack Overflow用户
提问于 2018-07-15 03:27:21
回答 1查看 113关注 0票数 -1

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

代码语言:javascript
复制
x = 0
def recursion():
    global x
    x += 1
    print(x)
    while x < 5:
        recursion()
        recursion()
        print("example")
    print("test")
recursion()

输出:

代码语言:javascript
复制
1
2
3
4
5
test
6
test
example
test
7
test
example
test
8
test
example
test
9
test
example
test

如果有人能一步一步地解释一下,我将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2018-07-15 03:34:00

这是一步一步发生的事情。第一次呼叫时:

代码语言:javascript
复制
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

现在恢复所有处于保留状态的呼叫:

代码语言:javascript
复制
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

直到调用where x==4

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51342707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档