一种方式做到这一点是通过递归过程跟踪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你介意解释一下你'重新说明? –