递归函数和列表追加/扩展 [英] Recursive functions and lists appending/extending
问题描述
这是一个非常简单的代码,代替了一个更大的问题,但我希望我可以分块处理它。我将从我的第一个问题开始。
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]
我试过改变$ / b
I've tried changing
x=[] to x=[z]
$ b $然后我收到:
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.
推荐答案
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
。如果你想这样做,把第三行改为
Note that it does not include 1024
any more. If you want this, change the third line to
return [z]
当然,你通常不会递归地写这个,而是使用作为
循环或 itertools.takewhile()
。
Of course you wouldn't normally write this recursively, but rather use a for
loop or itertools.takewhile()
.
这篇关于递归函数和列表追加/扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!