Your algorithm cannot possibly account for all the permutations.
Notice that the pair (i,j)
can be any index pair. However, for each of your permutations in your code, you start with the original string and apply one swap. This cannot possibly get you all the permutations.
Pretend you start with ABCD
. If you wanted the reverse permutation DCBA
, you would not be able to do this in a single swap. A single swap will at most change the positions of 2 characters, but all 4 characters need to be in a different place.
Note that the number of possible (i,j)
pairs for a list of size n
is n*n = n^2
, which is not the same as the expected number of permutations n!
. In almost all cases, n! > n^2
, which means there definitely will be missing permutations.
In addition, you have pairs like (1,1)
which results in a swap that does nothing (which is fine, except now (2,2)
, (3,3)
, etc. give duplicate permutations) [thanks Code-Apprentice for pointing that out]. You also have both (1,2)
which will result in ACBD
, as well as (2,1)
, which also results in ACBD
. This is why you have duplicate permutations in your final permutation list.
P.S. In Python, you can swap two elements by simply doing a,b = b,a
.
Heap's Algorithm
The correct implementation of this is to use something like Heap's algorithm, which is a proper, more sophisticated switching of elements to obtain all the permutations.
Instead of making a new copy of the list each time, you keep doing swaps on the same list and it will cycle through all of the permutations, provided you do them in the correct order specified by the algorithm.
I won't bother detailing the algorithm here since the resources do a great job explaining it. If you really need an explicit Python implementation example, that's also easy to find.