Skip to content

Instantly share code, notes, and snippets.

@kkirsche
Created October 14, 2016 20:00
Show Gist options
  • Select an option

  • Save kkirsche/7fd294681c984eda6b5fe4931afc7338 to your computer and use it in GitHub Desktop.

Select an option

Save kkirsche/7fd294681c984eda6b5fe4931afc7338 to your computer and use it in GitHub Desktop.
# or use https://docs.python.org/3/library/itertools.html#itertools.permutations
def permutations(string, step = 0):
# if we've gotten to the end, print the permutation
if step == len(string):
print "".join(string)
# everything to the right of step has not been swapped yet
for i in range(step, len(string)):
# copy the string (store as array)
string_copy = [character for character in string]
# swap the current index with the step
string_copy[step], string_copy[i] = string_copy[i], string_copy[step]
# recurse on the portion of the string that has not been swapped yet (now it's index will begin with step + 1)
permutations(string_copy, step + 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment