Is Anagram
In this lesson, you will learn how to determine if a string is an anagram of another string or not.
We'll cover the following...
In this lesson, we will determine whether two strings are anagrams of each other.
Simply put, an anagram is when two strings can be written using the same letters.
Examples:
"rail safety" = "fairy tales"
"roast beef" = "eat for BSE"
It sometimes changes a proper noun or personal name into a sentence:
"William Shakespeare" = "I am a weakish speller"
"Madam Curie" = "Radium came"
We will write two solutions to this problem. The first one will be concise, while the second one will be more robust and efficient. Both of these approaches involve normalizing the input string, which means converting them into lowercase and removing all the characters which are not alphanumeric.
Let’s get started with the first approach.
Implementation
Solution 1
s1 = "fairy tales"s2 = "rail safety"s1 = s1.replace(" ", "").lower()s2 = s2.replace(" ", "").lower()# Requires n log n time (since any comparison# based sorting algorithm requires at least# n log n time to sort).print(sorted(s1) == sorted(s2))
On lines 4-5, s1
and s2
are normalized using replace()
and lower()
functions. replace(" ","")
replaces all the spaces with an empty string so that we are only left with alphabets or numbers. lower()
converts all the alphabets to lowercase. On line 10, the two strings are sorted after the normalization and then compared. If s1
and s2
are anagrams of each other, both the lists returned from sorted
will be the same ...