As an exercise, I tested various ways of generating all list permutations in Python - recursive, non-recursive ... - and comparing performance with itertools.permutations(). But I'm having problems with the generator version of the recursive method, which does not end purely with an exception StopIteration, but instead calls IndexError:
def spawnperms(alist):
"""same algorithm as recursive option, but a generator"""
if (alist == []):
yield []
for perm in spawnperms(alist[:-1]):
for i in range(len(perm)+1):
yield perm[:i] + [alist[-1]] + perm[i:]
Calling this from the Python interpreter:
>>> for i in spawnperms(range(3)):
... print i
...
[2, 1, 0]
[1, 2, 0]
[1, 0, 2]
[2, 0, 1]
[0, 2, 1]
[0, 1, 2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in spawnperms
File "<stdin>", line 5, in spawnperms
File "<stdin>", line 5, in spawnperms
File "<stdin>", line 7, in spawnperms
IndexError: list index out of range
Uch. I tried to go through it with the help pdbthat almost created a stack overflow in my brain, but I realized that recursion "gets" to an empty list, and then the external (I think) loop forfrom the indices is executed .
How can I fix my code?
: , . else if, , , , . !