2017-09-13 73 views
2

我应该写一个递归函数counting(5)打印5 4 3 2 1 0 1 2 3 4 5
我已经做了两个函数,每个函数下半部分,但我需要把它们放在一起。递归,Python,countup,倒计时

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, 
+0

你是什么意思在一起,你的意思是一个功能? –

+0

@ AbdenaceurLichiheb那么倒计时打印5 4 3 2 1 0和countup打印1 2 3 4 5,但我需要一个功能,打印5 4 3 2 1 0 1 2 3 4 5 – Therapist

+0

@TusharAggarwal你介意解释一下你'重新说明? –

回答

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 
+0

超圆滑的答案+1。我认为'not n'也是最重要的行之一,因为当'n'达到'0'时,'not n'为TRUE,然后反转开始。 –

2

@Reut_Sharabani解决方案是好的,但我认为这是更简单的阅读:

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

这样调用:

countdown(5,5) 
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