Skip to content

Instantly share code, notes, and snippets.

@OEUG99
Last active October 23, 2021 04:08
Show Gist options
  • Save OEUG99/bbb34c6ae0a6b4308f2e15d1d621c044 to your computer and use it in GitHub Desktop.
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.
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