python - 递归,Python,计数,倒计时

标签 python recursion

我应该编写一个递归函数 counting(5) 来打印 5 4 3 2 1 0 1 2 3 4 5
我在下面制作了两个功能,每个功能各占一半,但我需要将它们放在一起。

def countdown(n):
    if n == 0:
        print 0
    else:
        print n,
        countdown(n-1)

def countup(n):
    if n >= 1:
        countup(n - 1)
        print n,

最佳答案

我想诀窍是理解递归点不会结束执行:

def count_down_up(n):
    if not n:
        print n  # prints 0 and terminates recursion
        return
    print n  # print down 5, 4, 3, 2, 1
    count_down_up(n-1)  # recursion point
    print n  # prints up 1, 2, 3, 4, 5

可以看到每一步打印n, <RECURSION>, n ,展开为:

5, <count_up_down 4>, 5
5, 4, <count_up_down 3>, 4, 5
# ...
5 ,4, 3, 2, 1, <count_up_down 0>, 1, 2, 3, 4, 5   # recursion stops ...
5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5

关于python - 递归,Python,计数,倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46201436/

相关文章:

Python:将数据批量插入 SQL Server

python - 绘制最近质心的 ROC 曲线

python - python 每 4 个选项卡写入一个新行文本文件

python - 如何将 Pandas DataFrame 转换为 RDF(资源描述框架)?

java - 我不知道我在这个java递归问题上做错了什么!我在下面发布了练习和我的代码

algorithm - 有人可以解释递归插入排序是如何工作的吗?

PHP 将变量传递给 array_walk_recursive

python - 为什么我收到 TypeError : 'module' object is not callable using tkinter Fonts

python - 使用匿名lambda实现阶乘函数的python代码的解释是什么

javascript - 递归展平一组数组的算法