How to Find all Permutations of a String in Python

Python comes with a very useful module called itertools, which allows us to calculate permutations directly.

from itertools import permutations perms = [''.join(p) for p in set(permutations('hello'))] print(perms) print(len(perms))
Code language: Python (python)

This will result in 60 permutations:

#['helol', 'heoll', 'ehlol', 'eholl', 'ollhe', 'lheol', 'lhoel', 'lehol', 'leohl', 'hoell', 'holel', 'eohll', 'eolhl', 'olhel', 'olehl', 'lhelo', 'lhleo', 'lehlo', 'lelho', 'hlelo', 'hlleo', 'elhlo', 'ellho', 'lhloe', 'lhole', 'leloh', 'leolh', 'hlloe', 'hlole', 'elloh', 'elolh', 'lohel', 'loehl', 'oelhl', 'elhol', 'ohlel', 'olleh', 'holle', 'eollh', 'olhle', 'olelh', 'ehllo', 'hello', 'ohlle', 'oellh', 'llheo', 'lleho', 'llhoe', 'lleoh', 'llohe', 'lloeh', 'oehll', 'elohl', 'lohle', 'loelh', 'lolhe', 'loleh', 'hleol', 'hloel', 'ohell'] #60
Code language: Python (python)

How to Find all Permutations without Itertools

def permutations(string): if len(string) == 1: return string recursive_perms = [] for c in string: for perm in permutations(string.replace(c,'',1)): recursive_perms.append(c+perm) return set(recursive_perms) perms = permutations('hello') print(perms) print(len(perms))
Code language: Python (python)

This will give us 60 items:

#{'elohl', 'lhleo', 'hoell', 'hlleo', 'elhol', 'eholl', 'hlole', 'eolhl', 'hello', 'olehl', 'holle', 'oelhl', 'ehllo', 'leolh', 'leloh', 'lheol', 'elolh', 'loleh', 'lhelo', 'lehol', 'olhel', 'leohl', 'hlelo', 'elhlo', 'lolhe', 'llohe', 'loelh', 'hleol', 'lhole', 'ohell', 'oehll', 'lohle', 'lhoel', 'ehlol', 'eollh', 'loehl', 'lehlo', 'lhloe', 'lloeh', 'ollhe', 'ohlel', 'ohlle', 'olelh', 'oellh', 'llheo', 'olleh', 'lleoh', 'lohel', 'hloel', 'lleho', 'hlloe', 'ellho', 'holel', 'olhle', 'lelho', 'llhoe', 'elloh', 'heoll', 'eohll', 'helol'} #60
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments