Skip to content

Instantly share code, notes, and snippets.

@macroxela
Created May 7, 2020 13:19
Show Gist options
  • Save macroxela/28faecf176ee8ffddafc6c33da4fdc0f to your computer and use it in GitHub Desktop.
Save macroxela/28faecf176ee8ffddafc6c33da4fdc0f to your computer and use it in GitHub Desktop.
Function to find all permutations of a given string
#########################################################################
# Finds all permutations of a given string by using a tree-structure #
# It sets two counters, i and j with 0 < i <= j < length(string) #
# While keeping i fixed, iterates j through the remaining characters, #
# swapping each one with the character at i and adding it to a list #
# if the new string isn't on the list. Example shown below for 'abc' #
# #
# (abc) #
# | | | #
# | | | #
# | | | #
# | | | #
# (abc) (bac) (cba) #
# | | | | | | #
# (abc) (acb) (bac) (bca) (cba) (cab) #
# #
#########################################################################
def search(list, platform): # Find out if given string/number is in list
for i in range(len(list)):
if list[i] == platform:
return True
return False
def swap(s, pos1, pos2): # Swap characters of a string
str_list = list(s)
d1 = str_list[pos1]
str_list[pos1] = str_list[pos2]
str_list[pos2] = d1
return "".join(str_list)
def permutations(string):
perms = [string] # List to store all permutations
for k in perms: # Iterate through current permutations
for i in range(0, len(string)): #Original char to swap
for j in range(i, len(string)): #Secondary char to swap
temp = swap(k, i, j)
if not search(perms, temp):
perms.append(temp)
return perms
s = "abcd"
x = permutations(s)
#x.sort()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment