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.
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. 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. 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
. I don't see why you call the method bitStr
in this case, since you already know the result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.