Skip to content

Instantly share code, notes, and snippets.

@redspider
Created September 26, 2012 11:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redspider/3787386 to your computer and use it in GitHub Desktop.
Save redspider/3787386 to your computer and use it in GitHub Desktop.
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