Check Anagrams Program in Python

Check if Two Strings are Anagrams in Python

Introduction

This program checks if two strings are anagrams of each other. Two strings are considered anagrams if they contain the same characters with the same frequencies, but possibly in a different order.

Python Program


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

    :param str1: The first string.
    :param str2: The second string.
    :return: True if the strings are anagrams, False otherwise.
    """
    # Remove any spaces and convert strings to lowercase
    str1 = str1.replace(" ", "").lower()
    str2 = str2.replace(" ", "").lower()
    
    # Check if lengths of both strings are equal
    if len(str1) != len(str2):
        return False
    
    # Sort both strings and compare
    return sorted(str1) == sorted(str2)

def main():
    """
    Main function to test the are_anagrams function.
    """
    # Example strings
    string1 = "Listen"
    string2 = "Silent"
    
    # Check if the strings are anagrams
    if are_anagrams(string1, string2):
        print(f'"{string1}" and "{string2}" are anagrams.')
    else:
        print(f'"{string1}" and "{string2}" are not anagrams.')

if __name__ == "__main__":
    main()

    

Explanation

The program consists of two functions:

  • are_anagrams: This function takes two strings as input and returns a boolean indicating whether they are anagrams. It performs the following steps:
    • Removes any spaces and converts both strings to lowercase to ensure case-insensitive comparison.
    • Checks if the lengths of both strings are equal. If not, they cannot be anagrams.
    • Sorts both strings and compares them. If the sorted versions are identical, the strings are anagrams.
  • main: This function serves as the entry point of the program. It defines two example strings, calls the are_anagrams function to check if they are anagrams, and prints the result.

Key Points:

  • The program removes spaces and converts strings to lowercase to handle case and space insensitivity.
  • Sorting is used to compare the strings, as anagrams will have identical sorted character sequences.
  • The main function demonstrates the use of the are_anagrams function with example strings.


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 :)