3.23. Anagram ¶
Two words are anagrams if they consist of the same letters, but in a
different order. For example, “palm” and “lamp” are anagrams because
each contains one ‘p’, one ‘a’, one ‘l’, and one ‘m’. Write a function
named as anagram that takes two strings as arguments, and returns
True
if the strings are anagrams or returns False
otherwise.
Hint: You can use dictionaries to keep track of different characters in the input string and count them.
Sample I/O:
>>> anagram('palm', 'lamp')
True
>>> anagram('hello', 'olla')
False
def anagram(str1, str2):
count_1 = {}
for char in str1:
if char in count_1:
count_1[char] += 1
else:
count_1[char] = 1
count_2 = {}
for char in str2:
if char in count_2:
count_2[char] += 1
else:
count_2[char] = 1
if count_1 == count_2:
return True
else:
return False