I'm dealing with a simple problem:
I wrote the simple code that can check whether two strings, such as 'abcd' and 'dcba', are anagrams, but I have no idea what to do with more complex ones, like "Astronomer" and "Moon starter."
line1 = input('Enter the first word: ')
line2 = input('Enter the second word: ')
def deleteSpaces(s):
s_new = s.replace(" ","")
return s_new
def anagramSolution2(s1,s2):
alist1 = list(deleteSpaces(s1))
alist2 = list(deleteSpaces(s2))
print(alist1)
print(alist2)
alist1.sort()
alist2.sort()
pos = 0
matches = True
while pos < len(deleteSpaces(s1)) and matches:
if alist1[pos]==alist2[pos]:
pos = pos + 1
else:
matches = False
return matches
Firstly I thought that the problem lies in working with spaces, but then I understood that my algorithm doesn't work if the strings are not the same size.
I have no idea what to do in that case.
Here I found a beautiful solution, but it doesn't work either:
def anagrams(s1,s2):
return [False, True][sum([ord(x) for x in s1]) == sum([ord(x) for x in s2])]
If I run this function and test it on two strings, I'll get such output:
Examples:
First Word: apple
Second Word: pleap
output: True
First Word: Moon starter
Second Word: Astronomer
output: False //however it should should be True because this words are anagrams
Your algorithm is ok. Your problem is that you don't consider upper and lower case letters. Changing the two lines
alist1 = list(deleteSpaces(s1))
alist2 = list(deleteSpaces(s2))
to
alist1 = list(deleteSpaces(s1).lower())
alist2 = list(deleteSpaces(s2).lower())
will solve your issue. As an alternative you could simply use the following function:
def anagrams(s1, s2):
def sort(s):
return sorted(s.replace(" ", "").lower())
return sort(s1) == sort(s2)
If you want to have a faster solution with complexity of O(n), you should use a Counter instead of sorting the two words:
from collections import Counter
def anagrams(s1, s2):
def get_counter(s):
return Counter(s.replace(" ", "").lower())
return get_counter(s1) == get_counter(s2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With