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
|
|
|
|
|
2023-03-01 16:23:33 +00:00
|
|
|
return all(_count == 0 for _count in count.values())
|
2020-08-19 16:24:02 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2020-09-25 13:20:09 +00:00
|
|
|
from doctest import testmod
|
|
|
|
|
|
|
|
testmod()
|
2022-10-12 22:54:20 +00:00
|
|
|
input_a = input("Enter the first string ").strip()
|
|
|
|
input_b = input("Enter the second string ").strip()
|
2020-08-19 16:24:02 +00:00
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
status = check_anagrams(input_a, input_b)
|
|
|
|
print(f"{input_a} and {input_b} are {'' if status else 'not '}anagrams.")
|