Last active
March 12, 2021 06:22
-
-
Save victor-iyi/23fb1f8f90ff91054a448311905873f0 to your computer and use it in GitHub Desktop.
Check if two words are anagram
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Classic interview question to check if two words are anagram.""" | |
import collections | |
import itertools | |
import pytest | |
def is_anagram(first: str, second: str) -> bool: | |
"""Implementation of anagram checker with 3 different methods. | |
Note: | |
Method 1 - Uses brute force. | |
Method 2 - Uses the built in `sorted` function. | |
Method 3 - Uses `itertools`' Counter method. | |
Method 3 is the fasted while Method 1 is the slowest at O(n!*n!) | |
Args: | |
first (str) - First word. | |
second (str) - Second word. | |
Return: | |
(bool) - Whether `first` and `second` are anagrams. | |
""" | |
# Method 1 (Brute force): | |
# for permutation1 in itertools.permutation(first): | |
# for permutation2 in itertools.permutation(second): | |
# if permutation1 == permutation2: | |
# return True | |
# return False | |
# Method 2 (Sort): | |
# return sorted(first) == sorted(second) | |
# Method 3 (Counter): | |
return collections.Counter(first) == collections.Counter(second) | |
@pytest.mark.parametrize( | |
('first', 'second') | |
( | |
('', ''), # An emtpy string is a valid anagram. | |
('a', 'a'), # Same 1 char string is a valid anagram. | |
('of', 'fo'), # Same counts of same char is a valid anagram. | |
('oof', 'foo'), # Same counts of same char is a valid anagram. | |
) | |
) | |
def test_matches(first, second): | |
"""Test to show the first and second word is a valid anagram.""" | |
assert is_anagram(first, second) is True | |
@pytest.mark.parametrize( | |
('first', 'second'), | |
( | |
('a', 'b'), # Different 1 char isn't a valid anagram. | |
('of', 'off'), # Different sized string isn't a valid anagram. | |
('oof', 'ffo'), # Different counts of same char isn't an anagram. | |
) | |
) | |
def test_not_matches(first, second): | |
"""Test to show the first and second word isn't a valid anagram.""" | |
assert is_anagram(first, second) is False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Classic interview question to check if two words are anagram.
Install PyTest to run tests:
You can run the test like so: