递归,Python,计数,倒计时

时间:2017-09-13 15:29:00

标签: 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,

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:2)

@Reut_Sharabani解决方案很好,但我认为这更容易阅读:

def countdown(N,n):
    if abs(n) > N:
        return
    else:
        print(abs(n))
        countdown(N,n-1)

这样打电话:

countdown(5,5)

答案 2 :(得分:0)

这样做的一种方法是在递归过程中跟踪2个列表,然后在最后返回时将它们拼接在一起。

def countdown_up(n, i=0, down=[], up=[] ):
    if n >i:
        return countdown_up(n-1, i, down+[n], [n]+up)
    else:
        # stich the 2 lists together with the low point [i]
        return down+[i]+up

# by default it counts down to 0. 
>>>countdown_up(5)
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5]
# you can run with any arbitrary high and low numbers. 
>>>countdown_up(10, 3)
[10, 9, 8, 7, 6, 5, 4, 3, 4, 5, 6, 7, 8, 9, 10]    

要让函数打印而不是返回列表,我们只需要更改1行。

def countdown_up(n, i=0, down=[], up=[] ):
    if n >i:
        return countdown_up(n-1, i, down+[n], [n]+up)
    else:
        print(" ".join("%s "%x for x in down+[i]+up))


>>>countdown_up(5)
5  4  3  2  1  0  1  2  3  4  5 
>>>countdown_up(10,3)
10  9  8  7  6  5  4  3  4  5  6  7  8  9  10