[英]Python recursive list comprehension to iterative approach
I'm trying to understand how to think a recursive method iteratively.我试图了解如何迭代地思考递归方法。 For example, I have the following backtracking method:
例如,我有以下回溯方法:
def bitStr(n, s):
if n == 1:
return s
return [digit + bits for digit in bitStr(1, s) for bits in bitStr(n - 1, s)]
I'm practicing how to do accomplish a similar iteratively or explicitly using double for-loop.我正在练习如何使用双 for 循环以迭代方式或显式方式完成类似的操作。
I started something like this which I understand is incorrect;我开始了这样的事情,我知道这是不正确的; however, unable to fix it:
但是,无法修复它:
def bitStr2(n, s):
if n == 1:
return [c for c in s]
for bits in bitStr2(n - 1, s):
for digit in bitStr2(1, s):
return digit + bits
Thank You谢谢你
There are two issues in your code.您的代码中有两个问题。
First, as pointed out by @MisterMiyagi, you switched the loops.首先,正如@MisterMiyagi 所指出的,您切换了循环。 In a list comprehension, loops are read from left to right.
在列表理解中,循环是从左到右读取的。 You should write the regular loops like this:
您应该像这样编写常规循环:
for digit in bitStr2(1, s):
for bits in bitStr2(n - 1, s):
...
Second, a list comprehension produces... a list.其次,列表推导产生……一个列表。 You have to store the elements in a list:
您必须将元素存储在列表中:
...
result = []
for digit in bitStr2(1, s):
for bits in bitStr2(n - 1, s):
result.append(digit + bits)
return result
(Conversely: never use a list comprehension if you don't want to produce a list. ) And you don't have to handle differently the n = 1
case. (相反:如果您不想生成列表,则永远不要使用列表理解。 )并且您不必以不同方式处理
n = 1
的情况。 Full code:完整代码:
def bitStr2(n, s):
if n == 1:
return s
result = []
for digit in bitStr2(1, s):
for bits in bitStr2(n - 1, s):
result.append(digit + bits)
return result
Note that for digit in bitStr(1, s)
is equivalent to for digit in s
.请注意,
for digit in bitStr(1, s)
中的for digit in s
。 I don't see why you call the method bitStr
in this case, since you already know the result.我不明白为什么在这种情况下调用方法
bitStr
,因为您已经知道结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.