hershey10
hershey10

Reputation: 77

How do i fix my code to check if two words are anagrams

I am writing code to check if two words are anagrams of each other. But when I run this program, it is telling me that "tacocat" and "tacocatt" are anagrams of each other and they are not. I cant find whats wrong. Please help I am new

#How do you check if two strings are anagrams of each other?

def is_anagram(string1, string2):
    my_list = []

    for i in string1:
        my_list.append(i)

    for i in string2:
        if i in my_list:
            my_list.remove(i)

    if (not my_list):
        print("It is an anagram")
    else:
        print("No it is not an anagram")

is_anagram("tacocat", "tacocatt")

Upvotes: 1

Views: 110

Answers (2)

William
William

Reputation: 344

Your code only checks if string1 is a subset of string2. You need string2 a subset of string1 as well

def is_anagram(string1, string2):
    my_list = []
    my_list2= [] 

    for i in string1:
        my_list.append(i)

    for i in string2;
        my_list2.append(i)

    for i in string2:
        if i in my_list:
            my_list.remove(i)
            
    for i in string1:
        if i in my_list2:
           my_list2.remove(i)

    if (not (my_list and my_list2)):
        print("It is an anagram")
    else:
        print("No it is not an anagram")



is_anagram("tacocat", "tacocatt")

A simpler method is

def is_anagram(str1,str2):
    a=list(str1)
    b=list(str2)
    a.sort()
    b.sort()
    return a == b

Upvotes: 1

Nikhil VJ
Nikhil VJ

Reputation: 6112

you have to catch the flip side of if i in my_list: - if i is not present, then we know its not an anagram and we can get out of the function there itself.

    for i in string2:
        if i in my_list:
            my_list.remove(i)
        else:
            print("No it is not an anagram")
            return

Also, I think you need to get rid of spaces if any in either string at the start of the function before getting into comparing, as I believe those don't count (ex: "nag a ram" is an anagram of "anagram" - in your script the extra spaces will get flagged). Might also be a good idea to make it case insensitive while at it.

string1 = string1.replace(' ','').lower()

Upvotes: 2

Related Questions