Problem:define a recursive function to generate all Anagrams of a given stringTest Case 1:Enter a word: abcabcacbbacbcacabcbaTest Case 2:Enter a word: ababba
Question
Problem:
Define a recursive function to generate all Anagrams of a given string
Test Case 1:
Enter a word: abcabcacbbacbcacabcba
Test Case 2:
Enter a word: ababba
Solution
Sure, here is a Python solution for generating all anagrams of a given string using recursion:
def generate_anagrams(word):
if len(word) <= 1:
return [word]
# Get all permutations of length N-1
permutations = generate_anagrams(word[1:])
char = word[0]
result = []
# Iterate through all permutations of length N-1
for perm in permutations:
# Insert the character into every possible location
for i in range(len(perm)+1):
result.append(perm[:i] + char + perm[i:])
return result
You can test this function with your test cases like this:
print(generate_anagrams('abcabcacbbacbcacabcba'))
print(generate_anagrams('ababba'))
Please note that the number of anagrams for a string of length N is N factorial (N!). So, for long strings, this function may take a very long time to run and may consume a large amount of memory.
Similar Questions
Write a program that figures out whether one string is an anagram of another string. The program should ignore white space and punctuation
Read a string with words separated by space and return its length and count of consonants.Sample Inputwrite a programSample Output158
Given two strings A and B, find the minimum number of characters that need to be deleted from these 2 strings to make them anagrams of each other.
How many anagrams can be created from the word 'accommodate' if the new words do not need to be meaningful?
Write a java program to accept a String and the perform the following operations:a) Count the number of words with the first and the last letter being same.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.