In: Computer Science
PYTHON
Find anagrams of a word using recursion.
This a possible run of your program: Enter a word or empty string to finish: poster
The word poster has the following 6 anagrams:
presto
repost
respot
stoper
topers
tropes
Anagram: Anagram of a word is another word which is formed by rearranging the letters of same word.
So poster will have 6! anagrams including itself.
def getstring(lst):
return ''.join(lst)
def print_anagram(lst, left, right):
if left==right:
print(getstring(lst))
else:
for i in range(left,right+1):
lst[left],
lst[i] = lst[i], lst[left]
print_anagram(lst, left+1, right)
lst[left],
lst[i] = lst[i], lst[left]
input_string = str(input('Enter a word or empty string to
finish: '))
size = len(input_string)
lst = list(input_string)
print('The word ',input_string,' has the following
anagrams:')
print_anagram(lst, 0, size-1)