Anagram Checker in Python

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. For example, “listen” is an anagram of “silent”.

Python Program to Check if Two Strings are Anagrams


def are_anagrams(str1, str2):
    """
    Check if two strings are anagrams of each other.

    Args:
    str1 (str): The first string.
    str2 (str): The second string.

    Returns:
    bool: True if the strings are anagrams, False otherwise.
    """

    # Remove spaces and convert to lowercase for case-insensitive comparison
    str1 = str1.replace(" ", "").lower()
    str2 = str2.replace(" ", "").lower()

    # Anagrams must have the same length
    if len(str1) != len(str2):
        return False

    # Sort the characters in each string and compare
    return sorted(str1) == sorted(str2)

# Example usage
string1 = "Listen"
string2 = "Silent"

if are_anagrams(string1, string2):
    print(f'"{string1}" and "{string2}" are anagrams.')
else:
    print(f'"{string1}" and "{string2}" are not anagrams.')
    

Explanation

The provided Python program defines a function are_anagrams that checks whether two given strings are anagrams of each other. Here is a step-by-step explanation of the program:

  1. Function Definition: The are_anagrams function takes two string arguments, str1 and str2.
  2. Normalization: Both strings are normalized by removing spaces and converting all characters to lowercase to ensure the comparison is case-insensitive and ignores spaces.
  3. Length Check: If the lengths of the two strings differ, they cannot be anagrams, so the function returns False.
  4. Sorting and Comparison: Both strings are sorted alphabetically. If the sorted versions of both strings are equal, then the original strings are anagrams, and the function returns True. Otherwise, it returns False.
  5. Example Usage: An example usage of the are_anagrams function is provided where the strings “Listen” and “Silent” are checked. The result is printed based on whether the strings are anagrams or not.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)