Skip to content

Instantly share code, notes, and snippets.

@CS-savvy
Created March 16, 2019 11:22
Show Gist options
  • Save CS-savvy/e5c48e35c8e16943a61288843e0f0563 to your computer and use it in GitHub Desktop.
Save CS-savvy/e5c48e35c8e16943a61288843e0f0563 to your computer and use it in GitHub Desktop.
This python script generates all possible strings using provided string
print("This algorithm use backtrack to first find all possible sets using combination \n then uses permutation to get all possible arrangements \n\n\n")
class find_all_possiblities():
def __init__(self,source_str):
self.source_str = source_str
self.generated_str = list()
self.prepare_for_combination(self.source_str)
def prepare_for_permute(self,input):
count_map = {}
for ch in input:
if ch in count_map.keys():
count_map[ch] = count_map[ch] + 1
else:
count_map[ch] = 1
keys = sorted(count_map)
str = []
count = []
for key in keys:
str.append(key)
count.append(count_map[key])
result = [0 for x in range(len(input))]
self.permute_util(str, count, result, 0)
def permute_util(self,str, count, result, level):
if level == len(result):
self.generated_str.append("".join(result))
return
for i in range(len(str)):
if count[i] == 0:
continue;
result[level] = str[i]
count[i] -= 1
self.permute_util(str, count, result, level + 1)
count[i] += 1
def prepare_for_combination(self,input):
count_map = {}
for ch in input:
if ch in count_map.keys():
count_map[ch] = count_map[ch] + 1
else:
count_map[ch] = 1
keys = sorted(count_map)
str = []
count = []
for key in keys:
str.append(key)
count.append(count_map[key])
result = [0 for x in range(len(input))]
self.combination_util(str, count, result, 0 ,0)
def combination_util(self,str, count, result, level,search_from):
for i in range(search_from,len(str)):
if count[i] == 0:
continue;
result[level] = str[i]
self.prepare_for_permute(result[:level+1])
count[i] -= 1
self.combination_util(str, count, result, level + 1 , i)
count[i] += 1
def get_results(self):
return self.generated_str
your_string = "AABC" ## change this string to get generate results.
possible_strings = find_all_possiblities(your_string).get_results()
assert len(set(possible_strings)) == len(possible_strings), "Duplicate string found"
print( "No of string formed %d \n\n" % len(possible_strings))
print(possible_strings)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment