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
- Lowercases both strings and removes spaces.
sortedputs the letters of each in order.- Matching sorted letters means the strings are anagrams.
Keywords and builtins used here
defis_anagramlambdareturnsorted
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.
Step 8 of 9 in Strings, step 14 of 72 in Language basics.