sorted("elvis") == sorted("lives")
A popular question in programming interviews is about anagrams. The interviewer wants to test your knowledge about the basic terminology in computer science, and how good you are at developing your own simple algorithms to solve the problems you are facing. In this article, you’ll learn about a simple algorithm to find anagrams in Python.
Most students who have pursued an academic education in computer science, know exactly what to do here. When posed in a coding interview, this question serves as a test that immediately reveals whether you are part of this community. So let’s prepare!
What are anagrams? Two words are anagrams if they consist of the same characters.
“An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.”
Here are a few examples:
- “listen” → “silent”
- “funeral” → “real fun”
- “elvis” → “lives”
Figure 8-1: The word “elvis” is an anagram of the word “lives”.
Ok, now you know exactly what to do, right? So, let’s start coding.
Given are two strings x1 and x2. Write a function is_anagram which returns True if string x2 an anagram of string x1!
## One-Liner is_anagram = lambda x1, x2: sorted(x1) == sorted(x2) ## Results print(is_anagram("elvis", "lives")) print(is_anagram("elvise", "livees")) print(is_anagram("elvis", "dead"))
Listing 8-1: One-liner solution to check whether to strings are anagrams.
Before you read on: What’s the output of this code snippet?
How It Works
The one-liner solves the problem efficiently and correctly. Two strings are anagrams if they have the same sorted character sequence. It’s that easy. There is no need for external dependencies – we simply create a function is_anagram in a single line of code by using the lambda function definition with two arguments x1 and x2. The function simply returns the result of the expression sorted(x1) == sorted(x2) which is True if the sorted character sequences consist of the same characters. Here’s the output of the two sorted character sequences:
print(sorted("elvis")) # ['e', 'i', 'l', 's', 'v'] print(sorted("lives")) # ['e', 'i', 'l', 's', 'v']
Both strings “
## Results print(is_anagram("elvis", "lives")) # True print(is_anagram("elvise", "livees")) # True print(is_anagram("elvis", "dead")) # False
Where to go from here?
This article gave you the simplest way of finding anagrams in Python. There is no easier way — guaranteed.
If you feel like you need to become better in Python but you don’t know how and have little time, check out my daily “Coffee Break Python” email series with free Python cheat sheets. It’s fun!