Recursive functions and lists appending/extending

对着背影说爱祢 提交于 2019-12-04 07:28:05

How about this?

def testrecurse(z, target):
    if z >= target:
        return []
    return [z] + testrecurse(2 * z, target)

Example:

>>> testrecurse(1, 1000)
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

Note that it does not include 1024 any more. If you want this, change the third line to

        return [z]

Of course you wouldn't normally write this recursively, but rather use a for loop or itertools.takewhile().

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