-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfrequency_analysis
47 lines (38 loc) · 1.59 KB
/
frequency_analysis
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Crypto Analysis: Frequency Analysis
#
# To analyze encrypted messages, to find out information about the possible
# algorithm or even language of the clear text message, one could perform
# frequency analysis. This process could be described as simply counting
# the number of times a certain symbol occurs in the given text.
# For example:
# For the text "test" the frequency of 'e' is 1, 's' is 1 and 't' is 2.
#
# The input to the function will be an encrypted body of text that only contains
# the lowercase letters a-z.
# As output you should return a list of the normalized frequency
# for each of the letters a-z.
# The normalized frequency is simply the number of occurrences, i,
# divided by the total number of characters in the message, n.
def freq_analysis(message):
"""
Takes an input string and returns the frequency occurance
of each letter a-z in the string
"""
# define a message length and a pre-build list
length = len(message)
freq_list = [0 for i in range(26)]
# first count each occurance of each letter and store in list
for each in message:
freq_list[ord(each)-97] = freq_list[ord(each)-97] + 1
# then analyze the frequency by dividing through the message length
for each in freq_list:
if each != 0:
freq_list[freq_list.index(each)] = each * 1.0 / length
return freq_list
#Tests
print freq_analysis("abcd")
#>>> [0.25, 0.25, 0.25, 0.25, 0.0, ..., 0.0]
print freq_analysis("adca")
#>>> [0.5, 0.0, 0.25, 0.25, 0.0, ..., 0.0]
print freq_analysis('bewarethebunnies')
#>>> [0.0625, 0.125, 0.0, 0.0, ..., 0.0]