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.
The itertools module has a useful method called permutations(). The documentation says:
You’ll have to join your permuted letters as strings though.
If you find yourself troubled by duplicates, try fitting your data into a structure with no duplicates like a
set:Thanks to @pst for pointing out that this is not what we’d traditionally think of as a type cast, but more of a call to the
set()constructor.