python - Loop in recursive function -
for algorithm found convenient define recursive function looks this:
def f(l): in range(2): if len(l)>=1: print(l+[i]) else: return f(l+[i]) f([0])
but behavior different expect. print
[0, 0] [0, 1]
but expect print
[0,0] [0,1] [1,0] [1,1]
somehow nested function has access variable i, , instead of starting new loop different variable, continues on counting variable i. don't understand why python this.
my (vague) question therefore why python this, , there obvious modification code give output expected?
your code never recurses.
for in range(2): if len([0])>=1: print([0]+[i]) else: return f([0]+[i]) # de-functified
first time through for
loop, len([0]) >= 1
true
, prints [0] + [0]
. second time through for
loop, len([0]) >= 1
still true
, prints [0] + [1]
. loop ends , control passes outside function. never reach recursive case (len(l) < 1
)
note intended result just:
import itertools result = itertools.product(range(2), repeat=2) # cast list if necessary
Comments
Post a Comment