简体   繁体   English

如何只打印一次递归调用中的语句? Python

[英]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)

I want the print statement to be printed only once.我希望打印语句只打印一次。 I don't want to use if y>4 print() that defect the purpose.如果 y>4 print() 有缺陷,我不想使用。

I want the output to be like this:我希望输出是这样的:

5
4
3
2
1
all the recursive calls are done, now printing the stack
1 
2
3
4
5

Put the message in the else: block so it's only printed when we don't recurse.将消息放在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)

when you reach the stop condition print the required text:当您达到停止条件时打印所需的文本:

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)

prints印刷

5
4
3
2
1
all the recursive calls are done, now printing the stack
1
2
3
4
5

because it only prints at the end of recursion, where y == 1. If you do recursion where 1 isn't the end, all you need to do to create a similar effect is to locate where the final recursion is and then put a print statement in that will only activate if you're in the final recursion.因为它只在递归结束时打印,其中 y == 1。如果在 1 不是结束的情况下进行递归,则要创建类似效果所需要做的就是找到最终递归的位置,然后放置一个仅当您处于最终递归中时才会激活其中的 print 语句。

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

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