2 ms·
Compute all permutations of a string in Python
- dalke 13y ago(As a side note, that posting is from 2010.) As an alternative to writing the code yourself, there's itertools.permutations(). The Python itertools module documentation also gives a pure Python implementation of that function. itertools.permutations() does not give the same output as in the linked-to page because it returns tuples rather than strings. That is: >>> list(itertools.permutations("abc")) [('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')] instead of "abc", "acb", "bac", etc. It can also work on any indexable data type instead of just on strings. As for timings, I tested permutations("a" * 10) 0.53 seconds for itertools.permutations (in C) 17. seconds for the version on jeremy-boyd.com (in Python) 25. seconds for the itertools documentation version #1 (Python) ??? seconds for the itertools documentation version #2 (Python) I actually gave up on the last one. It computed "a" * 7 in 0.5 seconds, "a" * 8 in 12 seconds and "a" * 9 in 320.