Matthew Lee
Matthew Lee

Reputation: 69

Python anagram strings

I'm supposed to write a function to determine if two strings are anagrams or not.

The codes I've written now, doesn't really work well.

For example, one of sample input is

Tom Cruise
So I'm cuter

output should be True, but my code keep says False.

For another example, when the input is

the eyes
they see

My code actually says True which is the right answer.

So I have no idea why my code only works for certain input.

Can anyone help?

def anagram(a, b):

    if(sorted(a)==sorted(b)):
        return True
    else:
        return False

Upvotes: 1

Views: 426

Answers (4)

ComplicatedPhenomenon
ComplicatedPhenomenon

Reputation: 4189

def anagram(a, b):
    a = ''.join(e for e in a if e.isalpha()).lower()
    b = ''.join(e for e in b if e.isalpha()).lower()
    return sorted(a)==sorted(b)

a = "Tom Cruise"
b = "So I'm cuter"
anagram(a,b)

You got to remove the none alpha characters in the string and convert the two string into the consistent case.

Upvotes: 0

TEJAS SHAHA
TEJAS SHAHA

Reputation: 3

Check this one...

s1=input("Enter first string:")
s2=input("Enter second string:")
a=''.join(t for t in s1 if t.isalnum())
b=''.join(t for t in s2 if t.isalnum())
a=a.lower()
b=b.lower()
if(sorted(a)==sorted(b)):
      print("The strings are anagrams.")
else:
      print("The strings aren't anagrams.")

Upvotes: 0

Vasilis G.
Vasilis G.

Reputation: 7846

As I mentioned in the comment section above, you need to remove any symbol such as ' and convert each letter to either uppercase or lowercase to avoid case mismatches. So, your code should look like this:

def anagram(a, b):

    newA = ''.join(elem.lower() for elem in a if elem.isalpha())
    newB = ''.join(elem.lower() for elem in b if elem.isalpha())

    if(sorted(newA)==sorted(newB)):
        return True
    else:
        return False

a = "Tom Cruise"
b = "So I'm cuter"

print(anagram(a,b))

This will give you:

True

Upvotes: 2

Afik Friedberg
Afik Friedberg

Reputation: 342

You need to remove all the non alphabet characters and then convert all letters to lower case:

import re
regex = re.compile('[^a-zA-Z]')
return sorted(regex.sub('', a).lower()) == sorted(regex.sub('', b).lower())

Upvotes: 3

Related Questions