Skip to content
CodeItRaw
Strings

Lesson 3/3

Whether two texts are made of the same letters (an anagram) is a question about counts, not order. You keep how many of each letter there are in a dictionary; if the two texts' dictionaries are equal, one is a rearrangement of the other.

def letters(text):
count = {}
for ch in text:
count[ch] = count.get(ch, 0) + 1
return count
same = letters(first) == letters(second)
The very counting pattern of the Hashing topic. Two dictionaries can be compared with ==: they are equal when the same keys hold the same values, whatever order they were added in.

Another way is to sort both texts and compare: sorted(first) == sorted(second). It is short and pays the price of sorting (n log n); counting is one pass (n). That is the difference a duel measures.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Anagram?

    Code reading · Bug Hunt

  2. 02

    Anagram Halves

    Function

  3. 03

    Repeated Letter

    Code reading · Read the Big-O

If you would rather not wait for the order, every problem is open without locks: Problem list