Python Anagram Checker
Check if two strings are anagrams by comparing their character compositions in Python.
How it Works
Two strings are anagrams if they contain the same characters in identical frequencies, though arranged in a different order (e.g., "listen" and "silent").
An elegant way to check for anagrams is to clean the strings (strip whitespace and lower casing), sort their characters, and verify if the sorted lists are identical.
This sorting approach executes in O(k log k) time where k is the string length, which is optimal for short text checks.
Source Code
Checking word pairings for anagram status by letter sorting.
def is_anagram(str1, str2):
s1 = sorted(str1.lower().replace(" ", ""))
s2 = sorted(str2.lower().replace(" ", ""))
return s1 == s2
word1, word2 = "listen", "silent"
print(f"Are '{word1}' and '{word2}' anagrams? {is_anagram(word1, word2)}")
word3, word4 = "hello", "world"
print(f"Are '{word3}' and '{word4}' anagrams? {is_anagram(word3, word4)}")Are 'listen' and 'silent' anagrams? True
Are 'hello' and 'world' anagrams? FalseReal-world Applications
- Text analysis and linguistic comparison engines
- String puzzle design and validator systems
- Technical interview coding tasks
Frequently Asked Questions
Is there a way to solve this in O(n) linear time?
Yes! Instead of sorting, you can count letter frequencies using a hash map or Python's `collections.Counter` and compare the resulting frequency maps.
More Examples
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.