Python Recursion: Range

后端 未结 5 992
小鲜肉
小鲜肉 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:38

    This is nice and concise, I think:

    def rec_range(n):
        if not n <= 1: return rec_range(n-1) + (n-1,)
        return (0,)
    

    Basically you recurse downwards until you reach 1, and for each recursion add one less than the number that you just recursed on position wise to your tuple.

    Outputs:

    >>>rec_range(4)
    (0, 1, 2, 3)
    
    0 讨论(0)
  • 2021-01-26 05:38

    this is simple one:

    def getrange(a,b,c=1): 
         if a < b: 
            print(a)
            a+=c  
            getrange(a,b,c)
        else:
            return
    
    getrange(0,30,2)
    
    0 讨论(0)
  • 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 ()
    
    0 讨论(0)
  • 2021-01-26 05:52

    I would write it as follows:

    def rec_range(n):
        if n < 1:
            return ()
        else:
            return rec_range(n - 1) + (n - 1,)
    
    print(rec_range(4)) # prints (0, 1, 2, 3)
    

    This can also handle negative arguments.

    0 讨论(0)
  • 2021-01-26 05:54

    Just keep concatenating tuples for the number that is one less until one is reached:

    rec_range = lambda n: rec_range(n - 1) + (n - 1,) if n > 0 else ()
    
    0 讨论(0)
提交回复
热议问题