So given an input of two strings I have the following linear time solution to check if one string is an anagram of the other. I wanted a more concise and pythonic linear time solution to this.
for i in range(len(str1)):
if l1 in d1:
if l2 in d2:
for letter in d1:
if letter not in d2:
if d1[letter] != d2[letter]:
You can use python
collections.Counter class to do this. Basically, in anagrams, the count of each character has to be same between the two strings, so all you need is a character count of each character in both the strings, and compare them. The
Counter class will create the dictionaries for you, which you can directly compare.
from collections import Counter def is_anagram(string1, string2): return Counter(string1) == Counter(string2)
>>> is_anagram("helper", "perhel") True >>> is_anagram("helper", "perhe") False >>> is_anagram("helper", "perhes") False