|
| 1 | +""" |
| 2 | +======================================================> Anagram Checker <===================================================== |
| 3 | +
|
| 4 | +Given two strings, determine if they are anagrams of each other (contain the same characters in any order). |
| 5 | +
|
| 6 | +Ignore casing and white space. |
| 7 | +
|
| 8 | +=========================================================================================================================== |
| 9 | +O/P : =====> |
| 10 | +
|
| 11 | +1. are_anagrams("listen", "silent") should return true. |
| 12 | +2. are_anagrams("School master", "The classroom") should return true. |
| 13 | +3. are_anagrams("A gentleman", "Elegant man") should return true. |
| 14 | +
|
| 15 | +""" |
| 16 | +from collections import Counter |
| 17 | +def are_anagrams(str1,str2): |
| 18 | + |
| 19 | + # return sorted(str1.lower()) == sorted(str2.lower()) # Solution 1 |
| 20 | + # return Counter(str1.lower()) == Counter(str2.lower()) # Solution 2 |
| 21 | + |
| 22 | + # As the problem says to ignore whitespace, but this code still counts the spaces as characters. so need to |
| 23 | + # remove the whitespaces. |
| 24 | + |
| 25 | + # are_anagrams("listen", "silent") # ✅ True |
| 26 | + # are_anagrams("conversation", "voices rant on") |
| 27 | + if len(str1) != len(str2): |
| 28 | + return False |
| 29 | + clean1 = str1.replace(" ","").lower() |
| 30 | + clean2 = str2.replace(" ","").lower() |
| 31 | + return Counter(clean1) == Counter(clean2) |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | +if __name__ == "__main__": |
| 36 | + print(are_anagrams("listen", "silent")) |
| 37 | + print(are_anagrams("Hello", "World")) |
| 38 | + print(are_anagrams("School master", "The classroom")) |
| 39 | + |
| 40 | + |
| 41 | + |
0 commit comments