I am trying to define a function that takes 2 strings, compare those two and returns True if they are anagram. I don't want to import collections.
So, if string1 is python
and string 2 is nohtyp
, it should return True
. Otherwise, obviously, return false
. Here's my code looks like so far:
def check_anagram(str1, str2):
if len(str1) != len(str2):
return False
else:
for i in range(0, len(str1), 1):
if i in range(0, len(str2), 1):
return True
else:
return False
It works well for most of cases, but when
str1 is aaaaaaaaaabbbbbbbbbb
and str2 is ababababbbababababab
, it returns true
and when str1 is xxxyyyxxx
and str2 is yyyxxxyyy
, it also returns True
.
It should retrun False
for these 2 cases, but I have no idea.
Can anybody help me with this?
I think the most trivial way to do the task is sorting your strings and comparing them like this example:
def check_anagram(a = '', b = ''):
return sorted(a) == sorted(b)
Test1:
a = "python"
b = "nohtyp"
print(check_anagram(a, b))
Output:
>>> True
Test2:
a = "aaaaaaaaaabbbbbbbbb"
b = "ababababbbababababab"
print(check_anagram(a, b))
Output:
>>> False
Test3:
a = "xxxyyyxxx"
b = "yyyxxxyyy"
print(check_anagram(a, b))
Output:
>>> False