递归,Python,倒计时,倒计时
我应该写一个递归函数递归,Python,倒计时,倒计时,python,recursion,Python,Recursion,我应该写一个递归函数counting(5),它打印542310345 我在下面做了两个函数,每个函数做一半,但我需要把它们放在一起 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, 我想诀窍在于理解递
counting(5)
,它打印542310345
我在下面做了两个函数,每个函数做一半,但我需要把它们放在一起
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,
我想诀窍在于理解递归点不会结束执行:
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,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
5,5
5, 4, 4, 5
# ...
5,4,3,2,1,1,2,3,4,5递归停止。。。
5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5
@Reut_Sharabani解决方案很好,但我认为这更简单:
def countdown(N,n):
if abs(n) > N:
return
else:
print(abs(n))
countdown(N,n-1)
这样称呼:
countdown(5,5)
一种方法是在递归过程中跟踪两个列表,然后在返回的最后将它们粘在一起
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
一起算是什么意思,是一个函数吗?@abdenaceurlicheb倒计时显示542310,倒计时显示123445,但我需要一个显示54231014的函数5@TusharAggarwal你能解释一下你在说什么吗?是的,你为什么不直接用另一个功能叫“超级圆滑的答案+1”。我认为
not n
也是最重要的一行,因为当n
达到0
时,not n
为真,然后反转开始。