Python Recursion: Range

后端 未结 5 991
小鲜肉
小鲜肉 2021-01-26 05:14

I need to define a function called rec_range(n) which takes a natural number and returns a TUPLE of numbers up to the number n.

i.e. rec_range(5) returns (0,1,2,3,4)

5条回答
  •  礼貌的吻别
    2021-01-26 05:50

    How about a one-liner:

    def rec_range(n):
        return rec_range(n-1) + (n-1,) if n > 0 else ()
    

    Or with lambdas:

    rec_range = lambda n: rec_range(n-1) + (n-1,) if n > 0 else ()
    

提交回复
热议问题