Anagram Program in Python with Code – A Fun Journey into Word Twisting

Imagine this kind of scenario: you're solving a complex puzzle, and then the word called“listen” suddenly transforms into just a “silent voice.” Is it a Coincidence? Not at all definitely! These are just anagrams that keep on fascinating the whole world, rearrangements that have often intrigued puzzle solvers and also at the same time linguists for many years. But there's more to them than just this kind of meets the eye. In this blog, we’re going on a best practical hands-on Python journey to understand, build great, and also explore anagram programs ranging from the basics to some interesting cool tweaks.

Blogging Illustration

Anagram Program in Python with Code – A Fun Journey into Word Twisting

image

Whether you’re a beginner learning Python or even the one having a coding ninja looking for a complex side of challenge, this article is particularly useful and also your one-stop guide to building all kinds of anagram checker programs in Python with ease, understanding the logic, optimizing the solution, and even creating a mini-game at the end!

What is an Anagram?

An anagram is a word or even a phrase that is often formed by just rearranging all the required letters of another word. All these letters must be used later exactly once, and then the comparison is usually done, which is case-insensitive.

Examples of Anagrams are mentioned below :

Listen and silent are one such type of anagram

Evil and vile are another type

a gentleman and elegant man most famous type

Funeral and real fun are other such examples.

Sounds fun, right? Let’s dive into the code!

1. The Basic Anagram Checker in Python is available

Let’s start with something simple. We'll just build a Python function that will help in all checks if two words are often anagrams.

Method 1: Using Sorted Strings with a Program

Program source code :
                        def is_anagram(str1, str2):
                    # Remove spaces and convert to lowercase
                    . str1 = str1.replace(" ", "").lower()
                    str2 = str2.replace(" ", "").lower()

                    # Compare sorted characters
                    return sorted(str1) == sorted(str2)

                # Test it out here
                print(is_anagram("Listen", "Silent"))  # Output: True
                print(is_anagram("Hello", "Olelh"))    # Output: True
                print(is_anagram("Apple", "Plead"))    # Output: False
                        
How It Just Works:

We just normalize all the strings (remove all unnecessary spaces, convert them to lowercase).

We sort both of these strings alphabetically in the right order.

If they just match, they are also anagrams.

Sorting just transforms all the strings into a right-predictable order. If two strings do not contain the same letters, then their sorted versions will also appear to be the same.

2. A More Efficient Approach: Using a Frequency Counter

Sorting has a best time complexity of O(n log n). Let’s just improve that with a frequency kind of counter (dictionary or even a collections.Counter).

Method 2: Using Collections Counter

Program source code :

From collections import Counter

                        def is_anagram_counter(str1, str2):
                        # Normalize input
                        str1 = str1.replace(" ", "").lower()
                        str2 = str2.replace(" ", "").lower()

                        # Use Counter to count character frequencies
                        return Counter(str1) == Counter(str2)

                    # Test it
                    print(is_anagram_counter("Dormitory", "Dirty Room"))  # Output: True
                    print(is_anagram_counter("School Master", "The Classroom"))  # Output: True
                        
Why This Is Better:

Time complexity: O(n) is an area where n is often the length of the string.

Counter automatically will help you in counting the number of occurrences of each type of character.

Real-World Uses of Anagram Checkers are mentioned below.

Whether you believe it or not, anagram kind of programs aren’t just for fun. They’re often used in:

Spell checkers and other grammar tools

Word games like Scrabble or crosswords

Plagiarism text detectors (rearranged text patterns)

Natural Language Processing (NLP) related tasks

Interview questions to test some of the string manipulation logic.

3. Testing Your Anagram Program

Program source code :

Let’s create some of the best engaging kinds of functions to test multiple cases at once.

                        def run_tests():
                    test_cases = [
                        ("Listen", "Silent", True),
                        ("Triangle", "Integral", True),
                        ("Apple", "Plead", False),
                        ("Clint Eastwood", "Old West Action", True),
                        ("Astronomer", "Moon starer", True),
                        ("Hello", "Helloo", False),
                    ]

                    for word1, word2, expected in test_cases:
                        result = is_anagram_counter(word1, word2)
                        print(f"'{word1}' & '{word2}' -> {result} | Expected: {expected} | {'✅' if result == expected else '❌'}")

                run_tests()
                        

It’s often always a great type of habit to test these edge cases like empty strings, spaces, or even some other type of different casing.

4. Build a Mini Anagram Finder version from a List of Words

Let’s take all of this one level higher. Suppose you just have a list of all the words and you now want to find all their anagram pairs in it. Here’s how you can easily do it.

Idea:

Group all these words that are anagrams of each other in one part.

You can take help of the below code for performing this kind of function.

from collections import defaultdict

                        def group_anagrams(word_list):
                    anagram_dict = defaultdict(list)

                    For word in word_list:
                        key = ''.join(sorted(word.lower()))
                        anagram_dict[key].append(word)

                    return list(anagram_dict.values())
                        

# Example usage is mentioned here for your reference

                    words = ["listen", "silent", "enlist", "hello", "below", "elbow", "stone", "tones", "notes"]
                    grouped = group_anagrams(words)

                    For group in grouped:
                        if len(group) > 1:
                            print("Anagram Group:", group)

                        
Output for above program is as follows:
                    Anagram Group: ['listen', 'silent', 'enlist']
                    Anagram Group: ['hello']
                    Anagram Group: ['below', 'elbow']
                    Anagram Group: ['stone', 'tones', 'notes'] 
                        

Now you have seen your typesanagramsm that are observed as a clustering tool!

5. Let’s just Gamify It – Anagram Guessing type of Game in Python

What if we have just built a tiny kind of terminal game where you’re shown a jumbled word and also need to guess the original?

Program source code :

                import random

                def anagram_game():
                    word_list = ["python", "listen", "silent", "elbow", "below", "heart", "earth"]
                    word = random.choice(word_list)
                    jumbled = ''.join(random.sample(word, len(word)))

                    print(" Unscramble the word:", jumbled)

                    guess = input("Your Guess: ").lower()

                    if sorted(guess) == sorted(word):
                        print(" Correct! It's an anagram.")
                    Else:
                        print(f" Oops! The correct word was '{word}'.")

                anagram_game()
                        

You can easily expand all of it into a full-fledged game by often adding score, levels, hints, or a timer!

6. Handling all types of Edge Cases

To make your particular code quite robust and also interview-friendly, think about below points :

Start to Normalize everything:

Remove punctuation that is not necessary.

Ignore all types of spaces.

Convert all sets of letters to other lowercase ones.

Here’s a more defensive category of function:

Program source code :

                    import re
                    def clean_string(s):
                        return ''.join(re.findall(r'\w', s.lower()))

                    def is_anagram_clean(str1, str2):
                        return sorted(clean_string(str1)) == sorted(clean_string(str2))

                        

7. Create a Python Module for Reuse type of work

Want to use your particular anagram checker in multiple projects? Turn it into a reusable one by using this module!

# File: anagram_utils.py

Program source code :

                    from collections import Counter
                    import re

                    def clean_string(s):
                        return ''.join(re.findall(r'\w', s.lower()))

                    def is_anagram(str1, str2):
                        return Counter(clean_string(str1)) == Counter(clean_string(str2))
                        

Now use it in your other Python scripts:

from anagram_utils import is_anagram

print(is_anagram("Debit card", "Bad credit")) # Output: True

Practice Questions for Your Better Understanding

Before we just wrap up, here are some of the coolest exercises that you can't ever forget :

1. Write a function that takes a sentence and finds all anagrams within it.

Program source code :

from collections import defaultdict import re

                        def find_anagrams_in_sentence(sentence):
                    # Extract words (alphanumeric only), ignoring case
                    words = re.findall(r'\w+', sentence.lower())

                    # Group words by their sorted character sequence
                    anagram_groups = defaultdict(list)
                    for word in words:
                        key = ''.join(sorted(word))
                        anagram_groups[key].append(word)

                    # Filter out groups that have more than one word
                    . Result = [group for group in anagram_groups.values() if len(group) > 1]
                    return result

                # Example usage
                sentence = "Listen to the silent tone in stone and enlist"
                print(find_anagrams_in_sentence(sentence))

                Output : 

                [['listen', 'silent', 'enlist'], ['tone', 'note'], ['stone', 'tones']]
                        

2. Modify the anagram checker to support multi-language Unicode.

Program source code :

                    import unicodedata
                    from collections import Counter

                    def normalize_unicode(s):
                        # Normalize accents (e.g., é → e)
                        normalized = unicodedata.normalize('NFKD', s)
                        return ''.join(c for c in normalized if c.isalnum()).casefold()

                    def is_unicode_anagram(str1, str2):
                        return Counter(normalize_unicode(str1)) == Counter(normalize_unicode(str2))

                    # Example
                    print(is_unicode_anagram("résumé", "sérumé"))  # Output: True
                    print(is_unicode_anagram("niño", "niñó"))      # Output: False
                        

Here we have seen that the casefold () is better than lower (), which is used for multilingual case-insensitive comparison.

3. Build a GUI (with Tkinter or Streamlit) for the anagram game.

Tkinter GUI

                    import tkinter as tk
                    from tkinter import messagebox
                    import random

                    words = ["listen", "silent", "enlist", "python", "below", "elbow"]
                    word = random.choice(words)
                    jumbled = ''.join(random.sample(word, len(word)))

                    def check_answer():
                        guess = entry.get().lower()
                        if sorted(guess) == sorted(word):
                            messagebox.showinfo("Correct!", "🎉 You got it!")
                        Else:
                            messagebox.showerror("Oops!", f"Wrong! The correct word was: {word}")

                    # GUI Setup
                    root = tk.Tk()
                    root.title("Anagram Game")

                    label = tk.Label(root, text=f"Unscramble: {jumbled}", font=("Arial", 20))
                    label.pack(pady=10)

                    entry = tk.Entry(root, font=("Arial", 16))
                    entry.pack(pady=10)

                    btn = tk.Button(root, text="Check", command=check_answer, font=("Arial", 16))
                    btn.pack()

                    root.mainloop()
                        

4. Optimize anagram grouping for millions of words using hashing.

Source code for optimizing grouping

                    from collections import defaultdict

                    def group_anagrams_optimized(words):
                        anagram_map = defaultdict(list)
                        
                        For word in words:
                            key = tuple(sorted(word))  # Tuples are faster and hashable
                            anagram_map[key].append(word)
                            
                        return [group for group in anagram_map.values() if len(group) > 1]

                    # Test with large input
                    words = ["listen", "silent", "enlist", "rat", "tar", "art", "elbow", "below", "stone", "tones"]
                    print(group_anagrams_optimized(words))
                        
Conclusion

Anagrams are not just used for fun puzzles, but they’re also a brilliant way to sharpen your Python string manipulation skills and later dive deeper into this algorithmic thinking. We have now started from scratch, explored some of the most interesting multiple methods, optimized them according to our needs, built the best version of mini-game, and later even grouped words together like we do with pros.

By understanding all this, like how to manipulate strings, handle some edge cases, and optimize all your performance, you're not just writing a perfect anagram checker, but you're learning is also learning quite essential Python concepts that will help you in all these real-world applications like text analytics, NLP, and beyond.

Placed Students

Our Clients

Partners

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses