3
3
# removed from both the string so that they become
4
4
# anagrams of each other
5
5
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
+
6
12
import string
7
13
14
+ # letters will be a string of the form "abc...xyz"
15
+ # CHARACTER_HASH looks like this {'a'0, 'b':0 ...., 'z':0}
8
16
letters = string .ascii_lowercase
9
17
CHARACTER_HASH = dict (zip (letters , [0 ] * len (letters )))
10
18
11
19
20
+ # This method will mark all the letters occuring in 'text_a'
12
21
def mapLettersToHash (text_a ):
13
22
for char in text_a :
14
23
if char in CHARACTER_HASH .keys ():
15
24
CHARACTER_HASH [char ] += 1
16
25
17
26
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
18
29
def computeCommonLetters (text_b ):
19
30
common_letters = 0
20
31
for char in text_b :
@@ -23,14 +34,17 @@ def computeCommonLetters(text_b):
23
34
return common_letters
24
35
25
36
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
26
40
def computeUncommonLetters (text_a , text_b , common_letters ):
27
41
return abs (len (text_a ) + len (text_b ) - (2 * common_letters ))
28
42
43
+ if __name__ == "__main__" :
44
+ text_1 = "hello"
45
+ text_2 = "billion"
29
46
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