mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-18 01:00:15 +00:00
bc8df6de31
* [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.2.2 → v0.3.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.2.2...v0.3.2) - [github.com/pre-commit/mirrors-mypy: v1.8.0 → v1.9.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.8.0...v1.9.0) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
53 lines
1.5 KiB
Python
53 lines
1.5 KiB
Python
"""
|
|
wiki: https://en.wikipedia.org/wiki/Anagram
|
|
"""
|
|
|
|
from collections import defaultdict
|
|
|
|
|
|
def check_anagrams(first_str: str, second_str: str) -> bool:
|
|
"""
|
|
Two strings are anagrams if they are made up of the same letters but are
|
|
arranged differently (ignoring the case).
|
|
>>> check_anagrams('Silent', 'Listen')
|
|
True
|
|
>>> check_anagrams('This is a string', 'Is this a string')
|
|
True
|
|
>>> check_anagrams('This is a string', 'Is this a string')
|
|
True
|
|
>>> check_anagrams('There', 'Their')
|
|
False
|
|
"""
|
|
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
|
|
count: defaultdict[str, int] = defaultdict(int)
|
|
|
|
# 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
|
|
|
|
return all(_count == 0 for _count in count.values())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
from doctest import testmod
|
|
|
|
testmod()
|
|
input_a = input("Enter the first string ").strip()
|
|
input_b = input("Enter the second string ").strip()
|
|
|
|
status = check_anagrams(input_a, input_b)
|
|
print(f"{input_a} and {input_b} are {'' if status else 'not '}anagrams.")
|