簡體   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