Two words are anagrams when they use the same letters the same number of times, in a different order: "listen" and "silent". If you sort the letters of both, you get the same result.
The program
def is_anagram(first, second): first = first.lower().replace(" ", "") second = second.lower().replace(" ", "") return sorted(first) == sorted(second) a = input("First word or phrase: ") b = input("Second word or phrase: ") if is_anagram(a, b): print("They are anagrams.") else: print("They are not anagrams.")
Typed in this example: Dormitory, Dirty room. Press Run to type your own.
First word or phrase: Dormitory Second word or phrase: Dirty room They are anagrams.
How it works
.lower()and.replace(" ", "")remove the differences you do not care about: capital letters and spaces.sorted()takes the letters of a string and gives back a list in alphabetical order. Both phrases give the same list:
print(sorted("dormitory")) print(sorted("dirtyroom"))
['d', 'i', 'm', 'o', 'o', 'r', 'r', 't', 'y'] ['d', 'i', 'm', 'o', 'o', 'r', 'r', 't', 'y']
Another way: Counter
Counter from the collections module counts how many times each letter appears. Two strings are anagrams when their counts are equal:
from collections import Counter print(Counter("listen") == Counter("silent")) print(Counter("apple") == Counter("paple")) print(Counter("apple") == Counter("pale"))
True True False
"pale" has the right letters but only one "p", so it is not an anagram of "apple". For short words both ways are fast. For very long texts, Counter is faster, because it does not need to sort.