Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Anagrams

Two strings are anagrams if you can make one from the other by rearranging the letters.

Write a function named is_anagram that takes two strings as its parameters. Your function should return True if the strings are anagrams, and False otherwise.

For example, the call is_anagram("typhoon", "opython") should return True while the call is_anagram("Alice", "Bob") should return False.

 

==== SOLUTION ====

You can implement the `is_anagram` function in Python by first sorting the characters of both strings and then comparing if the sorted strings are equal. If they are equal, the strings are anagrams; otherwise, they are not.

Here’s how you can do it:

“`python
def is_anagram(s1, s2):
        # Sort the characters of both strings and compare them
        return sorted(s1.lower()) == sorted(s2.lower())

# Test the function
print(is_anagram(“typhoon”, “opython”)) # Output: True
print(is_anagram(“Alice”, “Bob”)) # Output: False
“`

Explanation:

1. `def is_anagram(s1, s2):`: This line defines a function named `is_anagram` that takes two parameters `s1` and `s2`, which are strings to be checked for being anagrams.

2. `sorted(s1.lower())`: This part converts the string `s1` to lowercase and sorts its characters alphabetically using the `sorted()` function.

3. `sorted(s2.lower())`: Similarly, this part converts the string `s2` to lowercase and sorts its characters alphabetically.

4. `return sorted(s1.lower()) == sorted(s2.lower())`: This line compares the sorted versions of both strings. If they are equal, it returns `True`, indicating that the strings are anagrams. Otherwise, it returns `False`.

So, when you call `is_anagram(“typhoon”, “opython”)`, it returns `True` because you can rearrange the letters of “typhoon” to get “opython”. Similarly, for `is_anagram(“Alice”, “Bob”)`, it returns `False` because the letters in “Alice” cannot be rearranged to form “Bob”.

Join the conversation