m2skills

anagrams py

Jul 13th, 2017
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. # program to indentify if 2 string are anagrams
  2.  
  3. # method to check for anagrams
  4. def check_anagram(str1, str2):
  5.     # we create a boolean to denote if the strings are anagrams or not
  6.     is_anagram = True
  7.    
  8.     # making a copy of strings
  9.     s1 = str1
  10.     s2 = str2
  11.    
  12.     # removing all the white spaces and converting the string to lower case
  13.     str1 = str1.replace(" ", "")
  14.     str2 = str2.replace(" ", "")
  15.    
  16.     # checking if the lengths are equal if not then they are not anagrams
  17.     if len(str1) != len(str2):
  18.         is_anagram = False
  19.     else:
  20.    
  21.         # here I am ignoring upper and lower case differences if you want to keep them comment below lines
  22.         str1 = str1.lower()
  23.         str2 = str2.lower()
  24.        
  25.         # sorting the string characters and comparing if the resultant strings are the same
  26.         str1 = list(str1)
  27.         str2 = list(str2)
  28.         str1.sort()
  29.         str2.sort()
  30.        
  31.         str1 = "".join(str1)
  32.         str2 = "".join(str2)
  33.        
  34.         if str1 == str2:
  35.             is_anagram = True
  36.         else:
  37.             is_anagram = False
  38.    
  39.     # printing the results
  40.     if is_anagram:
  41.         print(s1 + " and " + s2 + " are Anagrams")
  42.     else:
  43.         print(s1 + " and " + s2 + " are not Anagrams")
  44.    
  45.  
  46. # main function
  47.  
  48. check_anagram("Mother In Law", "Hitler Woman");
  49. check_anagram("DORMITORY", "Dirty Room");
  50. check_anagram("ASTRONOMERS", "NO MORE STARS");
  51. check_anagram("Toss", "Shot");
  52. check_anagram("joy", "enjoy");
  53. check_anagram("HOST", "shot");
  54. check_anagram("repacks", "PaCkErs");
  55. check_anagram("LISTENED", "ENLISTED");
  56. check_anagram("NAMELESS", "salesmen");
Add Comment
Please, Sign In to add comment