python recursive function that prints from 0 to n?

前端 未结 5 1131
陌清茗
陌清茗 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条回答
  •  天命终不由人
    2020-12-01 22:14

    You can replace the 0 and the n, and the + with a - to make your recursive countdown function to a recursive countup:

    def countup(N, n=0):
        print(n)
        if n == N:
            return
        return countup(N, n + 1)
    

    And call it as follows:

    countup(3)
    

    @JFSebastian points out this algorithm has the benefit of being O(1) rather than O(n), as discussed in this excellent article about the difference between a linear and iterative recursion, if used with the @tail_call_optimized decorator.

提交回复
热议问题