Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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")

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading