python recursive function that prints from 0 to n?

前端 未结 5 1127
陌清茗
陌清茗 2020-12-01 21:36

I am trying to write a recursive function that prints from 0 to n, but I have no idea how to do it. I accidentally made one that prints from

5条回答
  •  -上瘾入骨i
    2020-12-01 22:11

    You almost got it! here's a fixed, simplified version:

    def countup(n):
        if n >= 0:
            countup(n - 1)
            print(n)
    

    Notice that:

    • You don't have to return anything from a recursive function that only prints values
    • For printing in ascending order, the print statement must be placed after the recursive call
    • The recursion exits when n < 0, given that we're only printing, there's nothing left to be done afterwards and it's ok to return None (Python's default return value)

    UPDATE

    It seems that writing a tail recursive solution is all the rage around here :) oh well, here's my shot at it, a simplified and tail-recursive version of @AndyHayden's idea - using the tail call optimization decorator recipe:

    @tail_call_optimized
    def countup(N, n=0):
        print(n)
        if n < N:
            countup(N, n + 1)
    

    Either way, it works as expected:

    countup(5)
    => 0
       1
       2
       3
       4
       5
    

提交回复
热议问题