DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Shyam Salil
Shyam Salil

Posted on

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

Top comments (4)

Collapse
kgb33 profile image
Kelton

I'm curious as to why you used sets rather than a sorted list.

You said you're using sets because they "use an orderly arrangement of alphabets", I thought python sets are unordered.

Also, a set cannot have duplicate elements, so wouldn't "apple" and "leap" return True despite not being anagrams?

Collapse
shyams1993 profile image
Shyam Salil Author

That’s a brilliant catch! Thank you. I will change this post to reflect that :)

Collapse
hammertoe profile image
Matt Hamilton

Using a set operator though you will remove duplicate letters. Which will give you some false positives.

Collapse
shyams1993 profile image
Shyam Salil Author

Yup, made the edits :) Thank you! Might have never noticed the loop if it weren't for these comments.

DEV runs on 100% open source code known as Forem.

Β 
Contribute to the codebase or host your own.
Β 
Check these out! πŸ‘‡