Search code examples
pythonfunctionif-statementconditional-statementsanagram

Creating an anagram checker


So I have been able to create the following program which compares two strings to see if they are anagrams of each other.

def anagrams( string1, string2 ):
    if sorted(string1.lower()) == sorted(string2.lower()):
        return True
    else:
        return False

However, my issue is that I wish to not return a True value should both input strings be the exact same. For example:

anagrams('silent','silent')

This outputs True but I do not want it to do that, what changes should I make to implement this?


Solution

  • Just check if the strings are different:

    def anagrams(string1, string2):
        if sorted(string1.lower()) == sorted(string2.lower()) and string1.lower() != string2.lower():
            return True
        else:
            return False
    
    result = anagrams('silent', 'silent')
    print(result)
    

    Output

    False
    

    You could use Counter instead of sorted:

    from collections import Counter
    
    
    def anagrams(string1, string2):
        if string1.lower() != string2.lower() and Counter(string1.lower()) == Counter(string2.lower()):
            return True
        else:
            return False
    
    print(anagrams('silent', 'silent'))
    print(anagrams('silent', 'sitlen'))
    

    Output

    False
    True
    

    UPDATE

    As suggested by @RoadRunner, you could do:

    from collections import Counter
    
    
    def anagrams(string1, string2):
        ls1, ls2 = string1.lower(), string2.lower()
        return ls1 != ls2 and Counter(ls1) == Counter(ls2)
    
    print(anagrams('silent', 'silent'))
    print(anagrams('silent', 'sitlen'))