繁体   English   中英

了解 python 递归函数

[英]Understanding python recursive functions

我是编码新手,正在尝试学习 Python 和递归函数。 我有一个小程序如下:

def hi_recursive(remaining):
 # The base case
 print(remaining)
 if remaining == 0:
     return
 print('hi')

 # Call to function, with a reduced remaining count
 hi_recursive(remaining - 1)
 print(remaining)
 print('bye')

hi_recursive(3)

这导致 output:

3
hi
2
hi
1
hi
0
1
bye
2
bye
3
bye

我不明白remaining变量的值在它为 0 后如何增加,为什么bye打印 3 次? 最后不应该只打印一次吗?

如果您能帮助我理解这一点,我将不胜感激。 谢谢你。

递归 function 是通过自引用表达式根据自身定义的 function。 这意味着 function 将继续调用自身并重复其行为,直到满足某些条件以返回结果。

The reason your bye print multiple time is because when you recursing function inside your function ends, the original function that call the function inside still needs to finish. 如果您希望在最后打印再见,则需要在返回之前将其放入 function 中。 此外,您还有一个额外的“打印(剩余)”打印您的号码三次,因为您的 go 超过了您的 function hi_recursive(剩余)三次。

def hi_recursive(remaining):
 # The base case
 print(remaining)
 if remaining == 0:
     print('bye')
     return
 print('hi')


 # Call to function, with a reduced remaining count
 hi_recursive(remaining - 1)
 
hi_recursive(3)

查看此链接以获取更多信息https://realpython.com/python-thinking-recursively/#recursive-functions-in-python

在您的代码中:

def hi_recursive (remaining):

  print (remaining)
  if remaining == 0: ##### target #####
      return
  print ('hi')

  # Call to function, with a reduced remaining count
  hi_recursive (remaining - 1)
  print (remaining)
  print ('bye')

hi_recursive (3)

您的最小打印数字在target line中确定。 换句话说,如果你写remaining == 0 ,你最小的打印数字是0

您可以使用VScode 调试器PyCharm调试查看逐行运行代码

因为你先打印,然后你得到它这个代码是你的

def hi_recursive (remaining):
  # The base case
  print (remaining) # This line
  if remaining == 0: # and this line
      return
  print ('hi')

  # Call to function, with a reduced remaining count
  hi_recursive (remaining - 1)
  print (remaining)
  print ('bye')

hi_recursive (3)

使用这些代码之一。

def hi_recursive (remaining):
  # The base case
  if remaining == 0:
      return
  print (remaining)
  print ('hi')

  # Call to function, with a reduced remaining count
  hi_recursive (remaining - 1)
  print (remaining)
  print ('bye')

hi_recursive (3)

或者

def hi_recursive (remaining):
  # The base case
  if remaining == 1:
      return
  print (remaining)
  print ('hi')

  # Call to function, with a reduced remaining count
  hi_recursive (remaining - 1)
  print (remaining)
  print ('bye')

hi_recursive (3)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM