typestar

Anagram check in Python

Sorting as a canonical form - a common comparison trick.

def is_anagram(a, b):
    normalize = lambda s: sorted(s.lower().replace(" ", ""))
    return normalize(a) == normalize(b)

How it works

  1. Lowercases both strings and removes spaces.
  2. sorted puts the letters of each in order.
  3. Matching sorted letters means the strings are anagrams.

Keywords and builtins used here

The run, in numbers

Lines
3
Characters to type
114
Tokens
40
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 25 seconds.

Type this snippet

Step 8 of 9 in Strings, step 14 of 72 in Language basics.

← Previous Next →