Python problem 7 of 30

Is it an anagram?

  • Python
  • Easy

Write is_anagram(a, b) that returns True if the two strings use exactly the same letters the same number of times, ignoring spaces and case.

is_anagram("Listen", "Silent")          # True
is_anagram("Dormitory", "dirty room")   # True
is_anagram("abc", "abd")                # False
Show hint

Two anagrams look identical once you clean them up and sort their letters.

Show solution
def is_anagram(a, b):
    def letters(s):
        return sorted(s.replace(" ", "").lower())
    return letters(a) == letters(b)

Sorting puts the letters in a standard order, so anagrams become equal lists. That is O(n log n). Comparing collections.Counter objects instead is O(n), because it only counts letters.

Want a problem like this every day? See today's problem and keep a streak going.