In: Computer Science
Write the following Python code:
A string X is an anagram of string Y if X can be obtained by arranging all characters of Y in some order, without removing any characters and without adding new characters. For example, each of the strings "baba", "abab", "aabb" and "abba" is an anagram of "aabb", and strings "aaab", "aab" and "aabc" are not anagrams of "aabb".
A set of strings is anagram-free if it contains no pair of strings which are anagrams of each other. Given a set of strings words, return the size of its largest anagram-free subset. Note that the entire set is considered a subset of itself.
Examples:
words = ["abcd","abdc","dabc","bacd"] Returns: 1All of the strings in words are anagrams of each other, so no two of them can simultaneously belong to an anagram-free set.
words = ["abcd","abac","aabc","bacd"] Returns: 2One of the maximum anagram-free subsets is ["abcd","abac"].
words = ["aa","aaaaa","aaa","a","bbaaaa","aaababaa"] Returns: 6Note that strings of different length cannot be anagrams of each other.
words = ["creation","sentence","reaction","sneak","star","rats","snake"] Returns: 4
CODE: Python Programming Language
def anagram(S):
def sort(word):
chars = list(word)
chars.sort()
return
''.join(chars)
subset = set()
for word in S:
for i in [i for i in S
if i != word]:
str = sort(word)
if str not in subset or str != sort(i):
subset.add(str)
return len(subset)
#Test Case1
words = ["abcd","abdc","dabc","bacd"]
print(words)
result = anagram(words)
print(result)
#Test case 2
words = ["abcd","abac","aabc","bacd"]
print(words)
result = anagram(words)
print(result)
#Test Case 3
words = ["aa","aaaaa","aaa","a","bbaaaa","aaababaa"]
print(words)
result = anagram(words)
print(result)
#Test Case 4
words =
["creation","sentence","reaction","sneak","star","rats","snake"]
print(words)
result = anagram(words)
print(result)
============================================================================
SCREENSHOT OF THE CODE:
============================================================================
OUTPUT:
Thank you.