[Tutor] recursion
noopy
ml1 at bitbert.com
Thu Feb 4 21:03:14 EST 2016
Hi,
I just cannot get my head around the following code, maybe someone could
explain it to me.
def permutations(items):
n = len(items)
if n==0: yield []
else:
for i in range(len(items)):
for cc in permutations(items[:i]+items[i+1:]):
yield [items[i]]+cc
for p in permutations(list("XYZ")):
print(''.join(p))
I did not figure out how this works in the deepest level of the
recursion. I mean, when I go down the recursion level
and do the part "for cc in permutations("Z")".
I have a problem with the following understanding:
when I am in the recursion and call "for cc in permutations("Z")", the
next level of the recursion will do "for cc in permutations([])", which
will yield an empty list.
But when "for cc in permutations([])" yields an empty list, why does
"for cc in permutations("Z")" then actually have an item so that "yield
[items[i]]+cc" will be executed?
So although "for cc in permutations("Z")" does have an item it does
"yield [items[i]]+cc" - thats the confusion for me. I hope I could
express myself clearly.
Maybe someone could enlighten me, I would be more than happy since I
have been thinking for quite some time about this and it does not let me
sleep, hehe.
thanks in advance,
noopy
More information about the Tutor
mailing list