pythonanagram

Anagram function returns False for unknown reason in some words - Python


I've tried to create a function that returns True if two words are anagrams (have the same letters) to each other.

I realized that my counter counts to 13 but not sure what is the issue.

def is_anagram (worda: str , wordb: str) -> bool:
    count_same_letters = 0
    if len(worda) == len(wordb):
        for i in worda:
            for j in wordb:
                if i == j:
                    count_same_letters = count_same_letters+1
                    print(count_same_letters)
                    print(len(wordb))
        return count_same_letters == len(wordb)
    else:
        return False

print(is_anagram("anagram","nagaram"))

while trying the string 'abc' abd 'bca' the output was True as I expected, but the strings 'anagram' and 'nagaram'returns False


Solution

  • As mentioned, the problem here is that letters occurring more than once are counted again. Supposing you need to implement the algorithm yourself without Count, here's one approach to the problem:

    def is_anagram (worda: str , wordb: str) -> bool:
        if len(worda) == len(wordb):
            remaining_letters = wordb
            for letter in worda:
                letter_index = remaining_letters.find(letter)
                if letter_index == -1:
                    return False # no! not anagram
                
                remaining_letters = remaining_letters[:letter_index] + remaining_letters[letter_index+1:]
            
            if len(remaining_letters) == 0:
                return True
        else:
            return False
                    
    print(is_anagram("anagram", "gramnaa"))
    print(is_anagram("omg", "omggg"))
    print(is_anagram("abc", "cba"))
    print(is_anagram("aaaa", "aaaaaa"))  
    

    By "deleting" every letter we find from remaining_letters our code will have to search through a smaller string on each iteration, possibly making it perform faster then some other alternatives.