Skip to content

Commit f2866ba

Browse files
committed
refactor(strings, anagram): is anagram improvements
1 parent 560526f commit f2866ba

File tree

2 files changed

+19
-10
lines changed

2 files changed

+19
-10
lines changed

pystrings/anagram/__init__.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
from typing import Dict
1+
from typing import DefaultDict
22
from functools import reduce
3+
from collections import defaultdict
34
from string import ascii_letters
45

56
from pymath.primes.is_prime import is_prime_with_re
@@ -27,25 +28,19 @@ def is_anagram(s1: str, s2: str) -> bool:
2728
# This dictionary is used to keep track of the character count in the strings to check if the strings are anagrams
2829
# of each other, the character count must be equal in both strings. This enables the algorithm to keep track of this
2930
# count.
30-
ht: Dict[str, int] = dict()
31+
ht: DefaultDict[str, int] = defaultdict(int)
3132

3233
# Loop through each character in the first string to count the number of characters and store them in the dictionary
3334
# this is linear, so, O(n) where n is the number of characters in the string as the loop has to iterate over each
3435
# character
3536
for char in s1:
36-
if char in ht:
37-
ht[char] += 1
38-
else:
39-
ht[char] = 1
37+
ht[char] += 1
4038

4139
# Loops through each character in the second string checking for the existence of that character in the already
4240
# populated dictionary. If a character, exists, the count is decremented, if not, the count is incremented. This
4341
# will be used to show the discrepancy in character count between the two strings
4442
for char in s2:
45-
if char in ht:
46-
ht[char] -= 1
47-
else:
48-
ht[char] = 1
43+
ht[char] -= 1
4944

5045
# Finally, check each key in the dictionary. If a given key's count is not equal to 0, then the algorithm exits
5146
# early as it's not possible to have a character count of more than 0 for strings that are anagrams, since the above

pystrings/anagram/test_anagram.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,20 @@ def test_madam_curie_and_radium_came(self):
2525
actual = is_anagram(s1, s2)
2626
self.assertTrue(actual)
2727

28+
def test_super_and_upper(self):
29+
"""should return false for s1='super' and s2='upper'"""
30+
s1 = "super"
31+
s2 = "upper"
32+
actual = is_anagram(s1, s2)
33+
self.assertFalse(actual)
34+
35+
def test_spare_and_pears(self):
36+
"""should return true for s1='spare' and s2='pears'"""
37+
s1 = "spare"
38+
s2 = "pears"
39+
actual = is_anagram(s1, s2)
40+
self.assertTrue(actual)
41+
2842

2943
class AnagramTests(unittest.TestCase):
3044
def setUp(self):

0 commit comments

Comments
 (0)