Posted By

eazyigz on 09/23/11


Tagged

python anagram


Versions (?)

Anagram checker in Python


 / Published in: Python
 

  1. one = raw_input('Enter first word/phrase: ')
  2. two = raw_input('Enter second word/phrase: ')
  3.  
  4. # Check if one phrase has exactly the same letter set as the other.
  5. def isAnagram(one, two):
  6. # First divide each phrase into a list of words, then join the words into
  7. # a string. Then compare the alphabetically-sorted strings for equality.
  8. # Apostrophes are stripped from the words.
  9. list1 = one.split()
  10. list2 = two.split()
  11. word1 = ""; word2 = ""
  12. sorted_joined_str1 = ""; sorted_joined_str2 = ""
  13. for word in list1:
  14. word1 += word
  15. sorted_joined_str1 += ''.join(sorted(word1, key=str.lower)).lower().replace("'","")
  16.  
  17. for word in list2:
  18. word2 += word
  19. sorted_joined_str2 += ''.join(sorted(word2, key=str.lower)).lower().replace("'","")
  20.  
  21. if sorted_joined_str1 == sorted_joined_str2: return True
  22. else: return False
  23.  
  24.  
  25. if isAnagram(one, two):
  26. print one + " and " + two + " are anagrams of each other"
  27. else: print one + " and " + two + " are NOT anagrams of each other"

Report this snippet  

You need to login to post a comment.