Python Recursion: Range

回眸只為那壹抹淺笑 提交于 2019-12-02 09:01:59

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.

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)

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 ()

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 ()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!