Last active
October 23, 2021 04:08
-
-
Save OEUG99/bbb34c6ae0a6b4308f2e15d1d621c044 to your computer and use it in GitHub Desktop.
A recursive function that generates a list of all possible anagrams for a given string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def anagram_generator(string): | |
""" | |
A recursive function that generates a list of all possible anagrams for a given string. | |
""" | |
list = [] | |
# The last char in our string will be inserted at every index in order to generate sub-anagrams. | |
insert_char = string[len(string)-1] | |
# Base Case: if string is only 1 character. | |
if len(string) <= 1: | |
return [string[0]] | |
# Inductive Step: | |
for sub_anagram in anagram_generator(string[:-1]): # for a sub-anagram in of list of sub-anagrams. | |
for index in range(len(sub_anagram) + 1): # We loop one extra over so we can assign our insert letter at the first element | |
list.append(sub_anagram[:index] + insert_char + sub_anagram[index:]) | |
return list | |
print(anagram_generator("abcdefg")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment