Anagrams in Python

How To Work With Anagrams in Python: Step-By-Step Examples

Do you know how to check if two strings are anagrams of each other in Python? It’s a common problem and there are multiple ways to solve it.

Two strings are anagrams of each other if they both contain the same characters and each character is present in each string the same number of times. Two ways to check if two strings are anagrams in Python is by using the sorted() function or the collections.Counter() function.

Technically anagrams should have a meaning but in this scenario we will consider as anagrams also permutations of characters without meaning.

Let the anagrams begin!

What is an Anagram in Python?

The anagram is not a concept specific to Python, it’s a more generic concept. If two words contain the same letters and each letter is present the same number of times they are anagrams of each other.

For example, the following strings are anagrams of each other:

'elle' and 'leel'

Other examples of anagrams are:

'hello' and 'olleh'
'hello' and 'lleoh'

And the following strings are not anagrams…

'elle' and 'leele'

So, how can we verify anagrams in Python?

One way is by using the sorted built-in function.

Let’s see what output does the sorted function return…

>>> sorted('elle')
['e', 'e', 'l', 'l']
>>> sorted('leel')
['e', 'e', 'l', 'l'] 

The sorted function takes an iterable as argument and returns a sorted list that contains the items in the iterable.

In this specific case we have passed a string to the sorted function (yes, a string is an iterable) and we get back a list of characters.

Have a look at the output of the sorted function.

How do you think you can use this function to check if two strings are anagrams of each other?

We can simply compare the two lists returned by the sorted function. If the two lists are equal then the two strings are anagrams.

Here is the logic we can use:

>>> sorted('leel') == sorted('leel')
True
>>> sorted('leel') == sorted('leele')
False 

Example of Program to Check if Two Strings are Anagrams of Each Other

Let’s write a simple Python program that read two string from the user by calling the input function and checks if the two strings are anagrams.

first_string = input("Provide the first string: ")
second_string = input("Provide the second string: ") 

if sorted(first_string) == sorted(second_string):
    print("The two strings are anagrams of each other.")
else:
    print("The two strings are not anagrams of each other.") 

After reading the two strings from the user input we verify, using a Python if else statement, if the lists returned by the sorted function are the same.

Verify if the program does what it’s expected to do…

$ python anagrams.py
Provide the first string: hello
Provide the second string: olelh
The two strings are anagrams of each other.
 
$ python anagrams.py
Provide the first string: hello
Provide the second string: ollleh
The two strings are not anagrams of each other. 

Looks good!

We have created a simple program that performs an anagram test between two strings.

Perform Anagram Check in a Python Function

Before making our algorithm to check for anagrams more complex I want to refactor the previous code and move all the logic into a function.

The function takes the two strings as arguments and prints the messages we have seen before.

def anagram_checker(first_value, second_value):
    if sorted(first_string) == sorted(second_string):
        print("The two strings are anagrams of each other.")
    else:
        print("The two strings are not anagrams of each other.") 

And here is how we can call it from the main of our Python program.

first_string = input("Provide the first string: ")
second_string = input("Provide the second string: ")
anagram_checker(first_string, second_string) 

Before continuing with this tutorial verify that the new code works as expected.

In the next section we will see how to enhance our code.

How to Find Anagrams For a String in a List of Strings

It’s time to learn how to look for anagrams for a string in a list of strings.

Let’s assume we have the following list:

words = ['enif', 'ollhe', 'aivrre', 'gdo', 'atc', 'neif'] 

We want to take one string as user input and find any anagrams for it inside the list of words.

You already know how to get the user input so for now let’s focus on updating the anagram_checker function.

This function will now:

  • Take as arguments the string we are searching anagrams for and the list of words.
  • Return a list that contains any anagrams found.
  • If no anagrams are found the list returned is empty.
def anagram_checker(value, words):
    anagrams = []

    for word in words:
        if sorted(word) == sorted(value):
            anagrams.append(word)

    return anagrams 

We use a for loop to go through each word in the list to verify which one is an anagram for the first value passed to the function.

Let’s test this function to see if it returns the expected results…

words = ['enif', 'ollhe', 'aivrre', 'gdo', 'atc', 'neif']

# Test 1
print(anagram_checker('hello', words))

[output]
['ollhe']

# Test 2
print(anagram_checker('fine', words))

[output]
['enif', 'neif']

# Test 3
print(anagram_checker('python', words))

[output]
[] 

The three tests executed against our function return the correct results.

How to Generate Anagrams For a Word Using Python

Now we will solve a slightly different problem.

Given a string we want to generate all the words made of the possible permutations of the letters in the word.

So, for the word ‘cat’ we want the following output:

['cat', 'cta', 'atc', 'act', 'tac', 'tca']

The Python itertools module provides the permurations() function that can help us with this.

Let’s see what the permutations() function returns when we pass our string to it.

>>> from itertools import permutations
>>> permutations('cat')
<itertools.permutations object at 0x7fa2d8079d60> 

We get back an itertools.permutations object. Let’s see if we can cast it to a list…

>>> list(permutations('cat'))
[('c', 'a', 't'), ('c', 't', 'a'), ('a', 'c', 't'), ('a', 't', 'c'), ('t', 'c', 'a'), ('t', 'a', 'c')] 

This time we get back a list of tuples. The elements of each tuple are characters in the original string.

I would like to see a list of strings, how can we generate it?

We can use a list comprehension and the Python string join method:

>>> [''.join(element) for element in list(permutations('cat'))] 
['cat', 'cta', 'act', 'atc', 'tca', 'tac'] 

It looks better!

The join method transforms each tuple into a string.

How to Find Anagrams in a Python List Using a Dictionary

Now, let’s find out how we can use a Python dictionary to store all the anagrams starting from a list of strings.

['cat', 'hello', 'tiger', 'olleh', 'tac', 'atc', 'regit', 'elephant']

The algorithm to store anagrams will work as follows:

  • Go through each string in the list and firstly sort its characters.
  • Check if any anagram of this string is already a dictionary key.
  • If not add this word as dictionary key otherwise add this word to the value (of type list) mapped to the existing dictionary key.

For example, if we take the first string ‘cat’, we expect something like this:

{'cat': ['tac', 'atc'], .... }

So, ‘cat’ is encountered and it’s set as dictionary key. Then when ‘tac’ and ‘atc’ are processed they are added to the list mapped to the ‘cat’ key because they are anagrams of ‘cat’.

Makes sense?

Let’s write the code to do this…

Firstly we need a function that takes a word and a list of dictionary keys and checks if an anagram of the word is present in the dictionary keys.

If present it returns the key otherwise it returns None.

def get_anagram_from_dictionary_keys(word, keys):
    for key in keys:
        if sorted(word) == sorted(key):
            return key

    return None 

Test this function first…

Scenario in which an anagram for the word is one of the dictionary keys

keys = ['cat', 'hello', 'tiger']
print(get_anagram_from_dictionary_keys('tac', keys))

[output]
cat 

Scenario in which there is no anagram for the word in the list of dictionary keys

print(get_anagram_from_dictionary_keys('elephant', keys))

[output]
None 

Make sure you understand this function before continuing considering that we will call this function when generating our dictionary of anagrams.

Writing a Function That Creates a Dictionary of Anagrams

And now we will write the function that generates the dictionary of anagrams starting from a list of words.

The function does the following:

  • Go through each word in the list of words.
  • Convert the word to lowercase.
  • Call the previous function get_anagram_from_dictionary_keys().
  • If a key is returned by the previous function this word is simply added to the list mapped to the existing dictionary key. Otherwise this word becomes a new dictionary key.
def create_anagrams_dictionary(words):
    anagrams = {}

    for word in words:
        word = word.lower()
        dict_key_for_word = get_anagram_from_dictionary_keys(word, anagrams.keys())

        if dict_key_for_word:
            anagrams[dict_key_for_word].append(word)
        else:
            anagrams[word] = []

    return anagrams 

It’s time to test our code.

words = ['cat', 'hello', 'tiger', 'olleh', 'tac', 'atc', 'regit', 'elephant']
print(create_anagrams_dictionary(words)) 

And the output is…

{'cat': ['tac', 'atc'], 'hello': ['olleh'], 'tiger': ['regit'], 'elephant': []} 

It works as we expected!

Using collections.Counter() to Search for Anagrams

Another way to check if two strings are anagrams of each other is by using the Counter() function of the collections module.

Given a string the Counter() function returns a dictionary-like object in which the keys are the characters of the string and the values are the number of times each character appears in the string.

Here is an example:

>>> from collections import Counter
>>> Counter('cat')
Counter({'c': 1, 'a': 1, 't': 1}) 

Now, let’s apply the Counter function to the string ‘tac’.

>>> Counter('tac')
Counter({'t': 1, 'a': 1, 'c': 1}) 

We can simply compare the two objects returned to verify if the two strings are anagrams of each other.

>>> Counter('cat') == Counter('tac')
True
>>> Counter('cat') == Counter('hrt')
False  

Another trick you can use in your Python programs! 🙂

Conclusion

In this tutorial we went through multiple ways of verifying if two strings are anagrams of each others.

We have also seen how to find anagrams of a word in a list of words and how to generate words made of permutations of all the characters in a single word.

I know it’s quite a lot, I hope you have found it useful! 😉

Leave a Reply

Your email address will not be published. Required fields are marked *