Recursive functions and lists appending/extending

最后都变了- 提交于 2020-01-01 10:14:00

问题


This is a very simple code in place of a bigger problem, but I'm hoping I can tackle it in chunks. I'll start with my first problem.

def testrecurse(z,target):
    x=[]
    if z<target:
        z*=2
        x.append(z)
        x.extend(testrecurse(z,target))
    return x

This is a test function to help my brain out with recursion. It takes a number, then shows all the multiplications of two until it hits the target number. so if I enter:

testrecurse(1,1000)

I receive:

[2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]

which is great! Output looks good and clean. But here's my problem, I'm having a hard time appending or adding that very first value, in my output. Here's what I want the output to look like.

[1,2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]

I've tried changing

x=[] to x=[z]

but then I receive:

[1, 2, 2, 4, 4, 8, 8, 16, 16, 32, 32, 64, 64, 128, 128, 256, 256, 512, 512, 1024, 1024]

any help would be appreciated, I'm new to recursion and it makes my head hurt.


回答1:


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



来源:https://stackoverflow.com/questions/9896951/recursive-functions-and-lists-appending-extending

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