I've been studying python at school and I decided to complete a task to make a decrypter but instead of inputting the amount the message is changed it will do every one and look for common words and pick the most likely decryption. If it is not what you are after then they can look at every one. However I have had a problem with getting the code to decrypt it with each amount. This is the error returned after an odd return from a part of the code: IndexError: string index out of range. I cannot understand why it doesn't function. This is the only programming language I know so it might be obvious and I just didn't get it. I have been unable to find an answer online so if anyone finds a solution I'd be very grateful. Thanks in advance.
import sys
import time
from time import sleep as s
import random
import collections
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'
LETTERS = LETTERS.lower()
global c1, message
c1=int(0)
message = input("Enter the thing you want to decrypt. ")
def decrypt():
global c1, LETTERS, message
decrypted = ''
for counter in range(1,27):
for chars in message:
if chars in LETTERS:
c1 = int(c1+counter)
num = LETTERS.find(chars)
num -= c1
decrypted += LETTERS[num]
s(1)
print(decrypted)
decrypt()
The full error:
Enter the thing you want to decrypt. ij
hh
hhed
hhedzx
hhedzxsp
hhedzxspjf
hhedzxspjfyt
hhedzxspjfytlf
Traceback (most recent call last):
File "C:\Users\TomHu\Documents\Documents\Tom\School\Homework\Year 8\Computing\Python\Encrypter.py", line 30, in <module>
decrypt()
File "C:\Users\TomHu\Documents\Documents\Tom\School\Homework\Year 8\Computing\Python\Encrypter.py", line 25, in decrypt
decrypted += LETTERS[num]
IndexError: string index out of range
LETTERS have a length of 52 in your example.
The indexes you can use with LETTERS (num) must be between -52 and 51. However with your exemple num is equal to -56 before the error.
You can see it by adding print(num)
before decrypted += LETTERS[num]
.
if you want to avoid this problem you can do a modulo len(LETTERS):
import sys
import time
from time import sleep as s
import random
import collections
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'
LETTERS = LETTERS.lower()
length=len(LETTERS)
global c1, message
c1=int(0)
message = input("Enter the thing you want to decrypt. ")
def decrypt():
global c1, LETTERS, message
decrypted = ''
for counter in range(1,27):
for chars in message:
if chars in LETTERS:
c1 = int(c1+counter)
num = LETTERS.find(chars)
num -= c1
num=num%length
decrypted += LETTERS[num]
s(1)
print(decrypted)
decrypt()
With this modification you are sure to give all the time a valid index. After that you are free to modify your algorithm to have the output you expect.