I have a string. I want to generate all permutations from that string, by changing the order of characters in it. For example, say:
x='stack'
what I want is a list like this,
l=['stack','satck','sackt'.......]
Currently I am iterating on the list cast of the string, picking 2 letters randomly and transposing them to form a new string, and adding it to set cast of l. Based on the length of the string, I am calculating the number of permutations possible and continuing iterations till set size reaches the limit. There must be a better way to do this.
See
itertools.combinations
oritertools.permutations
.Here's a simple function to return unique permutations:
Here's a really simple generator version:
I think it's not so bad!
Here is another way of doing the permutation of string with minimal code. We basically create a loop and then we keep swapping two characters at a time, Inside the loop we'll have the recursion. Notice,we only print when indexers reaches the length of our string. Example: ABC i for our starting point and our recursion param j for our loop
here is a visual help how it works from left to right top to bottom (is the order of permutation)
the code :
Here is another approach different from what @Adriano and @illerucis posted. This has a better runtime, you can check that yourself by measuring the time:
For an arbitrary string "dadffddxcf" it took 1.1336 sec for the permutation library, 9.125 sec for this implementation and 16.357 secs for @Adriano's and @illerucis' version. Of course you can still optimize it.