Skip to content

Instantly share code, notes, and snippets.

@redspider

redspider/permute.py

Created Sep 26, 2012
Embed
What would you like to do?
Simple string permutation
def permute(items):
"""
Return the permutations of the provided set
:param items: Set of items to permute
:type items: set
:return: list of permutations
:rtype: list
"""
# If there's only one item (or no items), only one permutation and we already have it
if len(items) <= 1:
yield list(items)
return
# For every item, we return a list starting with that item, followed by all the permutations of the
# remaining items.
result = []
for item in items:
# Loop through all the sub-permutations by calling permute with the same set we have now, except with our
# current item removed
for sub_permutation in permute(items - {item}):
# Append the permutation to the result set, prefixed by our current item
yield [item] + sub_permutation
def permute_string(s):
"""
Return the permutations of the given string, as a list of strings.
:param s: String to permute
:type s: str
:return: list of permutations
:rtype: list
"""
# Return a generator that converts the lists into strings for each permutation
return (''.join(permutation) for permutation in permute(set(s)))
for permutation in permute_string("123"):
print permutation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment