Skip to content

Instantly share code, notes, and snippets.

@rohit-jamuar
Created March 30, 2015 21:42
Show Gist options
  • Select an option

  • Save rohit-jamuar/0addac31cd02265ca4f8 to your computer and use it in GitHub Desktop.

Select an option

Save rohit-jamuar/0addac31cd02265ca4f8 to your computer and use it in GitHub Desktop.
Find all combinations / permutations of a string
def combine(s):
if len(s) <= 1:
return {'', s}
last_char = s[-1]
result = combine(s[:-1])
intermediate = {i for i in result}
for item in result:
intermediate.add(item + last_char)
return list(intermediate)
def permute(s):
if len(s) <= 1:
return {s}
last_char = s[-1]
result = set()
for item in permute(s[:-1]):
for index in range(len(item) + 1):
result.add(item[:index] + last_char + item[index:])
return list(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment