开发者

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

This question already has answers here: 开发者_运维知识库 How can I generate a list of all possible permutations of several letters? [duplicate] (4 answers) Closed 9 years ago.

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!


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']


itertools.permutations does that.

>>> import itertools
>>> for s in itertools.permutations('banana'):
...     print ''.join(s)
... 
banana
banaan
bannaa
bannaa
# many, many more...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜