问题
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