Skip to content

Commit 6342cab

Browse files
author
Amogh Singhal
authored
Update check_anagrams.py
1 parent a731ee4 commit 6342cab

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

check_anagrams.py

+21-7
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,29 @@
33
# removed from both the string so that they become
44
# anagrams of each other
55

6+
# Anagrams: Words that are made from rearranging the letters of another word
7+
8+
# Algorithm: We will use dictionaries to keep track of characters.
9+
# The idea is to get the common occuring characters and derive
10+
# uncommon characters
11+
612
import string
713

14+
# letters will be a string of the form "abc...xyz"
15+
# CHARACTER_HASH looks like this {'a'0, 'b':0 ...., 'z':0}
816
letters = string.ascii_lowercase
917
CHARACTER_HASH = dict(zip(letters, [0] * len(letters)))
1018

1119

20+
# This method will mark all the letters occuring in 'text_a'
1221
def mapLettersToHash(text_a):
1322
for char in text_a:
1423
if char in CHARACTER_HASH.keys():
1524
CHARACTER_HASH[char] += 1
1625

1726

27+
# This method will count the letters present in 'text_b', also found in 'text_a'
28+
# These will be charcaters whose frequency in HASH is greater than zero
1829
def computeCommonLetters(text_b):
1930
common_letters = 0
2031
for char in text_b:
@@ -23,14 +34,17 @@ def computeCommonLetters(text_b):
2334
return common_letters
2435

2536

37+
# Now we derive how many uncommon letters are present,
38+
# This is done by subtracting twice the count of common letters
39+
# from the total length of both the strings
2640
def computeUncommonLetters(text_a, text_b, common_letters):
2741
return abs(len(text_a) + len(text_b) - (2 * common_letters))
2842

43+
if __name__ == "__main__":
44+
text_1 = "hello"
45+
text_2 = "billion"
2946

30-
text_1 = "hello"
31-
text_2 = "billion"
32-
33-
mapLettersToHash(text_1)
34-
common = computeCommonLetters(text_2)
35-
result = computeUncommonLetters(text_1, text_2, common)
36-
print(result)
47+
mapLettersToHash(text_1)
48+
common = computeCommonLetters(text_2)
49+
result = computeUncommonLetters(text_1, text_2, common)
50+
print(result)

0 commit comments

Comments
 (0)