一種方式做到這一點是通過遞歸過程跟蹤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
你是什麼意思在一起,你的意思是一個功能? –
@ 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
@TusharAggarwal你介意解釋一下你'重新說明? –