Python Practice › Basic Programs › Program 30
Check for an anagram
Write a Python program to check whether two words are anagrams: one is a rearrangement of all the letters of the other.
Input
"listen" and "silent", "apple" and "paple", "hello" and "world"
Output
True True False
Approach
- Ignore case and spaces.
- Two words are anagrams if their sorted letters are the same.
Solution 1: sorting
def is_anagram(a, b): clean_a = a.replace(" ", "").lower() clean_b = b.replace(" ", "").lower() return sorted(clean_a) == sorted(clean_b) print(is_anagram("listen", "silent"))print(is_anagram("Dormitory", "dirty room"))print(is_anagram("hello", "world"))Output
True True False
Line by line
Lines 2-3
Remove spaces and lower-case both words so “Dormitory” and “dirty room” compare fairly.
Line 4
sorted() turns each word into a sorted list of letters; equal lists mean the same letters.
Solution 2: Counter
from collections import Counterprint(Counter("apple") == Counter("paple"), Counter("abc") == Counter("abd"))Output
True False
Line by line
Line 2
Counter counts each letter; anagrams have identical counts.
Learn the concept
New to this topic? Read the lesson, then come back.