@@ -31,6 +31,23 @@ def letter_frequency(c):
3131 0.15 , 1.974 , 0.074 ]
3232 return frequencies [ord (c ) - ord ('a' )]
3333
34+ # This is what map() is all about.
35+ # 1. Take a list of letters, aka list(some_string)
36+ # 2. For each letter, compute the letter_frequency for that letter
37+ # In other words, "map" the letter to its letter frequency score
38+ # 3. The result of the mapping is a list of floats. Specifically, it
39+ # is a list of the letter frequency scores that correspond to the
40+ # characters in the original string. Sum up those floats to get
41+ # the frequency score for the entire string.
42+ #
43+ # sum of,
44+ # the mapping to scores of,
45+ # the list of letters
46+ #
47+ # It's just composite functions in algebra/calculus all over again :-)
48+ def frequency_score (some_list_of_characters ):
49+ return sum (map (letter_frequency , some_list_of_characters ))
50+
3451if mode == 'e' :
3552 message = input ('What message do you want to send? ' )
3653 shift = int (input ('How much do you want to shift the letters? ' ))
@@ -41,18 +58,23 @@ def letter_frequency(c):
4158elif mode == 'd' :
4259 message1 = input ('What is the message you want to decrypt? ' )
4360 listmessage1 = list (message1 )
44- freqall = []
45- for i in range (26 ):
46- shift = i
47- decrypt = new_message (listmessage1 , encription , shift )
48- frequency = []
49- (map (letter_frequency , decrypt ))
50- for i in range (len (decrypt )):
51- frequency .append (letter_frequency (decrypt [i ]))
52- freqall .append (sum (frequency ))
53- for x in freqall :
54- if x == max (freqall ):
55- print ('' .join (decrypt ))
61+
62+ decrypted_strings = []
63+ for shift in range (26 ):
64+ # Each entry in the decrypted_strings list is itself a list
65+ # of (decrypted) characters.
66+ decrypted_strings .append (new_message (listmessage1 , encription , shift ))
67+
68+ best_score = 0
69+ best_score_shift = 0
70+
71+ for shift in range (26 ):
72+ this_score = frequency_score (decrypted_strings [shift ])
73+ if this_score > best_score :
74+ best_score = this_score
75+ best_score_shift = shift
76+
77+ print ('' .join (decrypted_strings [best_score_shift ]))
5678
5779 brutethisbish = input ('This decryption may not be correct, would you like to see the list of all possible decryptions?(y/n) ' )
5880 for shift in range (26 ):
0 commit comments