繁体   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)

我希望打印语句只打印一次。 如果 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.

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