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.
Here's a slightly improved version of illerucis's code for returning a list of all permutations of a string
s
with distinct characters (not necessarily in lexicographic sort order), without using itertools:Here's a simple and straightforward recursive implementation;
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.You can get all N! permutations without much code
This program does not eliminate the duplicates, but I think it is one of the most efficient approaches:
itertools.permutations
is good, but it doesn't deal nicely with sequences that contain repeated elements. That's because internally it permutes the sequence indices and is oblivious to the sequence item values.Sure, it's possible to filter the output of
itertools.permutations
through a set to eliminate the duplicates, but it still wastes time generating those duplicates, and if there are several repeated elements in the base sequence there will be lots of duplicates. Also, using a collection to hold the results wastes RAM, negating the benefit of using an iterator in the first place.Fortunately, there are more efficient approaches. The code below uses the algorithm of the 14th century Indian mathematician Narayana Pandita, which can be found in the Wikipedia article on Permutation. This ancient algorithm is still one of the fastest known ways to generate permutations in order, and it is quite robust, in that it properly handles permutations that contain repeated elements.
output
Of course, if you want to collect the yielded strings into a list you can do
or in recent Python versions: