[英]How to print the statement only once which is inside recursion call? Python
def recur(y):
if y>0:
print(y)
recur(y-1)
print("all the recursive calls are done, now printing the stack") # I want this statement printed only once
print(y)
recur(5)
我希望打印語句只打印一次。 如果 y>4 print() 有缺陷,我不想使用。
我希望輸出是這樣的:
5
4
3
2
1
all the recursive calls are done, now printing the stack
1
2
3
4
5
將消息放在else:
塊中,以便僅在我們不遞歸時才打印它。
def recur(y):
if y>0:
print(y)
recur(y-1)
print(y)
else:
print("all the recursive calls are done, now printing the stack")
recur(5)
當您達到停止條件時打印所需的文本:
def recur(y):
if y>0:
print(y)
recur(y-1)
print(y)
else:
print("all the recursive calls are done, now printing the stack")
def recur(y):
if y > 0:
print(y)
recur(y - 1)
if y == 1:
print("all the recursive calls are done, now printing the stack") # I want this statement printed only once
print(y)
recur(5)
印刷
5
4
3
2
1
all the recursive calls are done, now printing the stack
1
2
3
4
5
因為它只在遞歸結束時打印,其中 y == 1。如果在 1 不是結束的情況下進行遞歸,則要創建類似效果所需要做的就是找到最終遞歸的位置,然后放置一個僅當您處於最終遞歸中時才會激活其中的 print 語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.