Python Practice › Basic Programs › Program 30

Check for an anagram

MediumBasic Programs · 30 of 40

Write a Python program to check whether two words are anagrams: one is a rearrangement of all the letters of the other.

Advertisement
Input
"listen" and "silent", "apple" and "paple", "hello" and "world"
Output
True
True
False

Approach

  1. Ignore case and spaces.
  2. Two words are anagrams if their sorted letters are the same.

Solution 1: sorting

Python
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

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

More basic programs

← All 40 Basic Programs

Leave a Comment