pysnippets.strings.is_anagram
Check if two strings are anagrams
is_anagram(a: str, b: str) -> bool
Compare letter counts, ignoring case, spaces and punctuation.
Listen and Silent are anagrams. Sorting both strings works, but counting is linear.
is_anagram.py✓ ruff · mypy --strict
from collections import Counter
def is_anagram(a: str, b: str) -> bool:
"""Return ``True`` if ``a`` and ``b`` use the same letters and digits."""
def letters(s: str) -> Counter[str]:
return Counter(c for c in s.casefold() if c.isalnum())
return letters(a) == letters(b)- casefold handles cases lower() misses, like "ß" -> "ss"
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> is_anagram("#anagram", "Nag a ram!")Truepassed on Python 3.11 to 3.14: >>> is_anagram("Listen", "Silent")Truepassed on Python 3.11 to 3.14: >>> is_anagram("abc", "abcc")FalseEdit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
casefold()is a strongerlower()meant for comparisons.isalnum()drops spaces and punctuation.- Two
Counters are equal when every character occurs the same number of times.
Complexity: O(n + m) time, O(k) space
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.strings.is_anagram import is_anagramNo dependencies: copy is_anagram.py into your project, or clone the repo.Adapted from is-anagram in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: casefold instead of lower; typed. Suggest an edit.