2020-09-25 13:20:09 +00:00
|
|
|
"""
|
|
|
|
wiki: https://en.wikipedia.org/wiki/Anagram
|
|
|
|
"""
|
2021-10-31 10:41:39 +00:00
|
|
|
from collections import defaultdict
|
2021-10-31 21:56:33 +00:00
|
|
|
from typing import DefaultDict
|
2020-09-25 13:20:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
def check_anagrams(first_str: str, second_str: str) -> bool:
|
2020-08-19 16:24:02 +00:00
|
|
|
"""
|
2021-10-22 14:07:57 +00:00
|
|
|
Two strings are anagrams if they are made up of the same letters but are
|
2020-08-19 16:24:02 +00:00
|
|
|
arranged differently (ignoring the case).
|
|
|
|
>>> check_anagrams('Silent', 'Listen')
|
|
|
|
True
|
|
|
|
>>> check_anagrams('This is a string', 'Is this a string')
|
|
|
|
True
|
2020-09-25 13:20:09 +00:00
|
|
|
>>> check_anagrams('This is a string', 'Is this a string')
|
|
|
|
True
|
2020-08-19 16:24:02 +00:00
|
|
|
>>> check_anagrams('There', 'Their')
|
|
|
|
False
|
|
|
|
"""
|
2021-10-31 10:41:39 +00:00
|
|
|
first_str = first_str.lower().strip()
|
|
|
|
second_str = second_str.lower().strip()
|
|
|
|
|
|
|
|
# Remove whitespace
|
|
|
|
first_str = first_str.replace(" ", "")
|
|
|
|
second_str = second_str.replace(" ", "")
|
|
|
|
|
|
|
|
# Strings of different lengths are not anagrams
|
|
|
|
if len(first_str) != len(second_str):
|
|
|
|
return False
|
|
|
|
|
|
|
|
# Default values for count should be 0
|
2021-10-31 21:56:33 +00:00
|
|
|
count: DefaultDict[str, int] = defaultdict(int)
|
2021-10-31 10:41:39 +00:00
|
|
|
|
|
|
|
# For each character in input strings,
|
|
|
|
# increment count in the corresponding
|
|
|
|
for i in range(len(first_str)):
|
|
|
|
count[first_str[i]] += 1
|
|
|
|
count[second_str[i]] -= 1
|
|
|
|
|
|
|
|
for _count in count.values():
|
|
|
|
if _count != 0:
|
|
|
|
return False
|
|
|
|
return True
|
2020-08-19 16:24:02 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2020-09-25 13:20:09 +00:00
|
|
|
from doctest import testmod
|
|
|
|
|
|
|
|
testmod()
|
2020-08-19 16:24:02 +00:00
|
|
|
input_A = input("Enter the first string ").strip()
|
|
|
|
input_B = input("Enter the second string ").strip()
|
|
|
|
|
|
|
|
status = check_anagrams(input_A, input_B)
|
2020-08-21 06:39:03 +00:00
|
|
|
print(f"{input_A} and {input_B} are {'' if status else 'not '}anagrams.")
|