# 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): alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m', 'n','o','p','q','r','s','t','u','v','w','x','y','z'] # builds empty count_list ([0,0,0...0,0]) count_list = [] i = 0 while i < 26: count_list.append(0) i += 1 # converts message string to array array = [] for i in message: array.append(i) n = len(array) + 0.0 # counts occurences of each letter for x in array: i = 0 while i < 26: if x == alphabet[i]: count_list[i] += 1 i += 1 # normalizes frequencies freq_list = [] for x in count_list: freq_list.append(x/n) 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]
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question