I have the following error when running encode() in my code.
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
encode()
File "/home/kian/dummyphone-app/python/encode.py", line 31, in encode
varb.insert(pl + 1, number2letter[randint(0, 26)])
KeyError: 0
The code is:
from collections import defaultdict
from random import randint
def encode():
number2letter = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e', 6 : 'f', 7 : 'g',
8 : 'h', 9 : 'i', 10 : 'j', 11 : 'k', 12 : 'l', 13 : 'm', 14 : 'n', 15 : 'o', 16 : 'p', 17 : 'q',
18 : 'r', 19 : 's', 20 : 't', 21 : 'u', 22 : 'v', 23 : 'w', 24 : 'x', 25 : 'y', 26 : 'z'}
encode = {"a": "y", "b": "z", "c": "a", "d": "b", "e": "c", "f": "d", "g": "e",
"h": "f", "i": "g", "j": "h", "k": "i", "l": "j", "m": "k", "n": "l", "o": "m",
"p": "n", "q": "o", "r": "p", "s": "q", "t": "r", "u": "s", "v": "t", "w": "u",
"x": "v", "y": "w", "z": "x"}
print("This is a work in progress.")
var = input("Please input the phrase to be encoded, and then press Enter. ")
vara = list(var.lower())
i = 0
while i < len(var):
if (vara[i] in encode) :
vara[i] = encode[vara[i]]
i += 1
else:
vara[i] = vara[i]
i += 1
pl = 0
dummyx = 0
dummyx2 = 0
varb = vara
for i in vara:
pl = pl + 1
if (dummyx == 1):
varb.insert(pl + 1, number2letter[randint(0, 26)])
pl = pl + 1
if (dummyx2 == 0):
dummyx2 = 1
if (dummyx2 == 1):
varb.insert(pl + 1, number2letter[randint(0, 26)])
dummyx2 = 0
pl = pl + 1
dummyx = 0
else:
dummyx = 1
print(''.join(varb))
I am trying to make it add random letters in specific spots, in the pattern:
normal letter, random letter, normal letter, random letter, random letter,
repeating every 5 letters. The rest of the code should encode letters into a code, in the "encode" dictionary. Numbers and symbols are ignored. I have a decoder for it as well, if you would like to see it I can post it here too.
randint(0, 26)
can return 0
, and there is no key 0
in number2letter
.
Change it to randint(1, 26)
.
Another way to generate a random lowercase letter in Python 3 is random.choice(string.ascii_lowercase)
(don't forget to import string
).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments