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 :
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()