Skip to content

Instantly share code, notes, and snippets.

@vnprc
Created December 28, 2014 00:44
Show Gist options
  • Select an option

  • Save vnprc/10df5885bc721f3a9b0a to your computer and use it in GitHub Desktop.

Select an option

Save vnprc/10df5885bc721f3a9b0a to your computer and use it in GitHub Desktop.
Programming exercise to print all permutations of an input strings. Contains two implementations, one with duplicates (in the case of repeated characters), and one without.
"""
Programming exercise to print all the permutations of an input string.
"""
import sys
def get_permutations(string):
permutations = []
if len(string) == 1:
return [string]
for i in string:
for permutation in get_permutations(string.replace(i, "", 1)):
permutations.append(i + permutation)
return permutations
for permutation in get_permutations(sys.argv[1]):
print permutation
"""
Programming exercise to print all permutations of an input strings without
any duplicates (in the case of repeated characters).
"""
import sys
def get_permutations(string):
permutations = []
completed_permutations = []
if len(string) == 1:
return [string]
for i in range(len(string)):
if string[i] in completed_permutations:
continue
else :
completed_permutations.append(string[i])
for permutation in get_permutations(string.replace(string[i], "", 1)):
permutations.append(string[i] + permutation)
return permutations
for permutation in get_permutations(''.join(sorted(sys.argv[1]))):
print permutation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment