Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # program to indentify if 2 string are anagrams
- # method to check for anagrams
- def check_anagram(str1, str2):
- # we create a boolean to denote if the strings are anagrams or not
- is_anagram = True
- # making a copy of strings
- s1 = str1
- s2 = str2
- # removing all the white spaces and converting the string to lower case
- str1 = str1.replace(" ", "")
- str2 = str2.replace(" ", "")
- # checking if the lengths are equal if not then they are not anagrams
- if len(str1) != len(str2):
- is_anagram = False
- else:
- # here I am ignoring upper and lower case differences if you want to keep them comment below lines
- str1 = str1.lower()
- str2 = str2.lower()
- # sorting the string characters and comparing if the resultant strings are the same
- str1 = list(str1)
- str2 = list(str2)
- str1.sort()
- str2.sort()
- str1 = "".join(str1)
- str2 = "".join(str2)
- if str1 == str2:
- is_anagram = True
- else:
- is_anagram = False
- # printing the results
- if is_anagram:
- print(s1 + " and " + s2 + " are Anagrams")
- else:
- print(s1 + " and " + s2 + " are not Anagrams")
- # main function
- check_anagram("Mother In Law", "Hitler Woman");
- check_anagram("DORMITORY", "Dirty Room");
- check_anagram("ASTRONOMERS", "NO MORE STARS");
- check_anagram("Toss", "Shot");
- check_anagram("joy", "enjoy");
- check_anagram("HOST", "shot");
- check_anagram("repacks", "PaCkErs");
- check_anagram("LISTENED", "ENLISTED");
- check_anagram("NAMELESS", "salesmen");
Add Comment
Please, Sign In to add comment