2017-09-13 89 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