Python Recursion: Range

2020-05-04 08:49发布

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) rec_range(1) returns (0,)

This is what I have come up with so far.

def rec_range(n):
    """takes a natural number n and returns a tuple of numbers starting with 0     and ending before n

    Natural Number -> Tuple of Numbers"""
    if n == 0:
        return 0
    else:
        return (rec_range(n-1), )

This works for rec_range(1).

***Restrictions are: must be defined recursively, cannot use lists, loops or use the existing range() function

5条回答
趁早两清
2楼-- · 2020-05-04 08:59

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)
查看更多
孤傲高冷的网名
3楼-- · 2020-05-04 09:03

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 ()
查看更多
成全新的幸福
4楼-- · 2020-05-04 09:12

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.

查看更多
可以哭但决不认输i
5楼-- · 2020-05-04 09:14

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)
查看更多
迷人小祖宗
6楼-- · 2020-05-04 09:17

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 ()
查看更多
登录 后发表回答