I’ve seen some postings of code for permutations on here but I haven’t really been able to find a good step-by-step walk through of what is actually going on. If someone could just explain what is actually happening in each step of this code I would really appreciate it. I can’t quite seem to wrap my head around it. The code I’m looking at is in Python and is from http://snippets.dzone.com/posts/show/753.
def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm)+1):
yield perm[:i] + str[0:1] + perm[i:]
for p in all_perms(['a','b','c']):
print p
First of all, the name of the parameter
stris a bad choice. It’s probably due to the fact that it works for all kinds of sequence types in Phyton but it should beseqor something to make the intention clear.If the length of the list is <= 1 (empty or one element) return the list (there is just one solution for this case).
For all other cases:
a) Create all permutations of
str[1:](i.e. the list just without the head element).b) Insert the head element at each position in each permutation created in a) and return the result
yieldworks a bit likereturn; the main difference is that the current value is returned and, when the function is called again, it continues with the instruction after theyield.This way, it’s easy to assemble the result.
Example:
'a'gives'a'(trivial).'ab'first chops of the head ('a'), then creates all permutations ofb(there is just one:'b'itself). Now the head is inserted at every position, so we end up with'ab'(head+list) and'ba'(list+head).etc.