Recursive functions and lists adding / expanding

This is very simple code instead of a more serious problem, but I hope I can handle it in pieces. I will start with the 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 that helps my brain with recursion. It takes a number and then shows all the multiplications of the two until it reaches the target number. so if I enter:

testrecurse(1,1000)

I get:

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

It's great! The output looks good and clean. But here is my problem, it's hard for me to add or add this very first value in my release. Here I want the result to look.

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

I tried changing

x=[] to x=[z]

but then I get:

[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 am new to recursion and my head hurts.

+5
source share
1 answer

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]

, 1024. ,

        return [z]

, , for itertools.takewhile().

+25

All Articles