Daniel Chepenko Daniel Chepenko - 5 months ago 21
Python Question

How to check whether two words are anagrams python

I'm dealing with simple problem, checking if two strings are anagram.
I write the simple code, that can check, whether two strings, such as
'abcd' and 'dcba' are anagrams, but I have mo idea what to do with more complex one, 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 is not working, if 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

Answer

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.lower()).strip()
    return sort(s1) == sort(s2)
Comments