fluttersmith/py-snippetsGitHub ↗

Check if two strings are anagrams

Compare letter counts, ignoring case, spaces and punctuation.

Strings#text#validationO(n + m) time✓ 3 examples pass on 3.11–3.14

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)
  1. 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")False
Edit 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).

How it works

  • casefold() is a stronger lower() 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

Importfrom 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.