I am trying to get my head around how this permutation algorithm works:
def perm(n, i):
if i == len(n) - 1:
print n
else:
for j in range(i, len(n)):
n[i], n[j] = n[j], n[i]
perm(n, i + 1)
n[i], n[j] = n[j], n[i] # swap back, for the next loop
perm([1, 2, 3], 0)
Output:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
Question
How is it that the original list is the first line printed?
In this example, the length of n is 3. Initially, i is 0. The code should skip the if statement, and then first iteration mutates the list. How do we get [1, 2, 3] as the first line of output?
else?