vijetha
vijetha

Reputation: 1

python Program to check whether two words are anagrams

I have written a small program to check whether two words are anagrams. If two words are anagrams it should return "true" otherwise it should return "False", but I am not getting the correct output. Kindly, tell me what is the mistake in the below program.

 def anagram(s1,s2):
     for x in s1:
         if (x in s2) and (s2.count(x)==s1.count(x)):
             pass
         return(True)
     else:
         return(False)

Upvotes: 0

Views: 545

Answers (4)

Hardik Patel
Hardik Patel

Reputation: 155

You may try this:

>>> def anagram(str1,str2):
    s1=str1.lower()
    s2=str2.lower()
    a=len(s1)
    b=len(s2)
    if a==b:
        for c in s1:
            if c in s2:
                for s in s2:
                    if s in s1:
                        return True
            else:
                return False
    else:
        return False

Upvotes: 0

Ma0
Ma0

Reputation: 15204

You were really close. Your indentation was bad but that is probably due to the text formatting here in SO.

The mistake in your code was that you were returning True too soon. What you have to do is to go through all letters and check for existance and count. Below you can find a corrected and somewhat optimised version of what you were trying to do.

def anagram(s1, s2):
    if set(s1) == set(s2) and all(s2.count(x) == s1.count(x) for x in set(s1)):
        return True
    return False

But then again @Tigerhawk's solution is way better.

Upvotes: -1

Steve TheGreat
Steve TheGreat

Reputation: 51

Please format this in a more readable way. However, it looks like you are calling return True inside the loop, meaning that if any character occurs the same amount of times in each string, your function will return True

Try this:

def anagram(s1,s2):
    for x in s1:
        if ( x in s2 ) and (s2.count(x) == s1.count(x) ):
            pass
        else:
            return False
    for x in s2:
        if ( x in s1 ) and (s1.count(x) == s2.count(x) ):
            pass
        else:
            return False
    return True

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49320

You are iterating over a word and then not doing anything (with pass, the empty statement). Then you return True unconditionally, leaving no chance to return False.

Instead, you can simply sort the two words and then see if they end up the same:

def anagram(s1, s2):
    return sorted(s1) == sorted(s2)

Upvotes: 4

Related Questions