IsAnagram? - Quick Hack

shyams1993

Shyam Salil

Posted on June 17, 2020

IsAnagram? - Quick Hack

Hello folks,

Just sharing a quick hack to find out if two words are anagrams of each other or not.

def isAnagram(word,word2):
    return sorted(word.lower().strip().replace(" ","")) == sorted(word2.lower().replace(" ",""))
print(isAnagram("Dormitory","Dirty room"))
print(isAnagram("School master", "The classroom"))

This function returns a boolean output based on whether they're anagrams or not.

Using sorted() to compare two words in an orderly manner to check their anagrammatic property & it just makes things a lot easier! :)

  • Added the ".lower()" to convert the uppercase to lowercase (if there's an upper case letter) and check since different letter cases impact the result.
  • Also, using ".replace(" ","")" to remove whitespaces.

Code on -- Cheers!

Thanks to the brilliant comments, made some edits to change the logic from set() to sorted() to rule out false positives

💖 💪 🙅 🚩
shyams1993
Shyam Salil

Posted on June 17, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

IsAnagram? - Quick Hack
python IsAnagram? - Quick Hack

June 17, 2020