patternpythonModerate
Determining if a word is an anagram of another
Viewed 0 times
wordanagramdetermininganother
Problem
The question was to see if a word is an anagram of another word.
How would you improve this? It returns True if an anagram, or False otherwise.
How would you improve this? It returns True if an anagram, or False otherwise.
# write the function is_anagram
def is_anagram(test, original):
if len(test) != len(original):
return False
for letter in test.lower():
if letter not in original.lower():
return False
for letter in original.lower():
if letter not in test.lower():
return False
return TrueSolution
You need to check if each letter occurs the name number of times in both strings.
One method would be to sort the letters and compare the lists of letters for equality.
Here is my approach:
This algorithm is far from optimal runtime O(n*logn), but I have chosen it because of its simplicity.
For an Efficient algorithm see the comment of @corsiKa for a quite simple O(n) algorithm.
One method would be to sort the letters and compare the lists of letters for equality.
Here is my approach:
def is_anagram(test, original):
return sorted(list(test.lower())) == sorted(list(original.lower()))This algorithm is far from optimal runtime O(n*logn), but I have chosen it because of its simplicity.
For an Efficient algorithm see the comment of @corsiKa for a quite simple O(n) algorithm.
Code Snippets
def is_anagram(test, original):
return sorted(list(test.lower())) == sorted(list(original.lower()))Context
StackExchange Code Review Q#96475, answer score: 13
Revisions (0)
No revisions yet.