Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: shuffle characters in string to get all possible string combinations [duplicate]

just looking for a script in Python which receives some string and returns all possible strings made up of all the possible combinations of the chars in the original string...

I've found scripts to shuffle randomly the chars in a string, but they only return one randome combination, and what I'm looking for is all the possible combinations...

Say, for example:

script.py "abc"
abc
acb
bac
bca
cab
cba

Thanks!

like image 918
Javier Novoa C. Avatar asked Dec 16 '10 15:12

Javier Novoa C.


People also ask

How do you get all the possible combinations of a string in Python?

To find all possible permutations of a given string, you can use the itertools module which has a useful method called permutations(iterable[, r]). This method return successive r length permutations of elements in the iterable as tuples.

How do you shuffle characters in a string in Python?

We have to use L = ['a', 'b', 'c'] then random. shuffle(L) and print L instead.

Does random shuffle work on strings?

Because a string is an immutable type, and You can't modify the immutable objects in Python. The random. shuffle() doesn't' work with String.

What is random shuffle in Python?

Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.


2 Answers

itertools.permutations

>>> import itertools
>>> import pprint
>>> pprint.pprint(list(itertools.permutations("spam")))
[('s', 'p', 'a', 'm'),
 ('s', 'p', 'm', 'a'),
 ('s', 'a', 'p', 'm'),
 ('s', 'a', 'm', 'p'),
 ('s', 'm', 'p', 'a'),
 ('s', 'm', 'a', 'p'),
 ('p', 's', 'a', 'm'),
 ('p', 's', 'm', 'a'),
 ('p', 'a', 's', 'm'),
 ('p', 'a', 'm', 's'),
 ('p', 'm', 's', 'a'),
 ('p', 'm', 'a', 's'),
 ('a', 's', 'p', 'm'),
 ('a', 's', 'm', 'p'),
 ('a', 'p', 's', 'm'),
 ('a', 'p', 'm', 's'),
 ('a', 'm', 's', 'p'),
 ('a', 'm', 'p', 's'),
 ('m', 's', 'p', 'a'),
 ('m', 's', 'a', 'p'),
 ('m', 'p', 's', 'a'),
 ('m', 'p', 'a', 's'),
 ('m', 'a', 's', 'p'),
 ('m', 'a', 'p', 's')]

(The pprint is just there to make the output look neater.) Or, if you prefer,

>>> list(map("".join, itertools.permutations("spam")))
['spam', 'spma', 'sapm', 'samp', 'smpa', 'smap', 'psam', 'psma', 'pasm', 'pams', 'pmsa', 'pmas', 'aspm', 'asmp', 'apsm', 'apms', 'amsp', 'amps', 'mspa', 'msap', 'mpsa', 'mpas', 'masp', 'maps']
like image 170
Katriel Avatar answered Oct 13 '22 13:10

Katriel


itertools.permutations does that.

>>> import itertools
>>> for s in itertools.permutations('banana'):
...     print ''.join(s)
... 
banana
banaan
bannaa
bannaa
# many, many more...
like image 24
bgporter Avatar answered Oct 13 '22 13:10

bgporter