简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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