Skip to content

Instantly share code, notes, and snippets.

@debetimi
Last active August 29, 2015 14:24
Show Gist options
  • Save debetimi/79b4111e46078e1ff6cd to your computer and use it in GitHub Desktop.
Save debetimi/79b4111e46078e1ff6cd to your computer and use it in GitHub Desktop.
Permutation
def memoize(func):
cache = {}
def memo(string):
if not string in cache:
cache[string] = func(string)
return cache[string]
return memo
@memoize
def permutations(string):
if not string:
return ['']
results = []
chars_used = []
for i, ch in enumerate(string):
if ch in chars_used:
continue
chars_used.append(ch)
for substr in permutations(string[:i]+string[i+1:]):
results.append(ch + substr)
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment