bw61293
bw61293

Reputation: 91

Decrypting, How to find the key

I have to decrypt a phrase for an assignment of mine and try to find the key by shifting the phrase from -1 to -25 by using the letter frequencies of the letters E, T, O, I, A, N. I have the formulas correct, but I do not know how to shift the letter frequencies from -1 to -25. I am assuming I would use a range from (-1 to -26) somehow. This is my code:

phrase=input('What would you like decrypted?')
        e=0
        t=0
        o=0
        a=0
        i=0
        n=0
        for letter in phrase:
            if letter== 'e':
                e+=1
                e_freq= .1119-e/10
                e_ans= e_freq*e_freq
            if letter== 't':
                t+=1
                t_freq= .0928-t/10
                t_ans= t_freq*t_freq
            if letter== 'o':
                o+=1
                o_freq= .0819-o/10
                o_ans= o_freq*o_freq
            if letter== 'a':
                a+=1
                a_freq= .0754-a/10
                a_ans= a_freq*a_freq
            if letter== 'i':
                i+=1
                i_freq= .0710-i/10
                i_ans= i_freq*i_freq
            if letter== 'n':
                n+=1
                n_freq= .0643-n/10
                n_ans= n_freq*n_freq
        square_sum= e_ans+t_ans+o_ans+a_ans+i_ans+n_ans
        print(square_sum)

Upvotes: 0

Views: 93

Answers (2)

TessellatingHeckler
TessellatingHeckler

Reputation: 29048

You're going to have to run the code you've written 25 times, but where you have this line:

for letter in phrase:
    if letter == 'e':

find "what letter would this be, shifted by -1?' for each letter.

Then on the next run 'what letter would this be shifted by -2?'.

You can do that by making a string of all the letters in the alphabet and then using .index() to go letter -> number position, and [] indexing to go number position -> letter:

>>> alphabet = 'abcdefghijklmnopqrstuvwxyz'
>>> print alphabet.index('m')
12

>>> print alphabet[11]
l

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 122143

To use a range of the values you want, try:

for i in range(-1, -26, -1):

Using a negative step will count backwards.

More generally, you could tidy up the code a bit:

expected = {"e": 0.1119, ...}
counts = {letter: phrase.count(letter) for letter in expected}
match = sum((expected[letter]-(counts[letter]/10))**2 for letter in expected)

Upvotes: 1

Related Questions