How do I rearrange a deciphered text grammatically?

Viewed 21

Trying out a simple text cipher program by simply mapping each alphabet to a numerical value plus one. Here is the code.

import string

chars = [c for c in string.ascii_lowercase]
nums = [n for n in range(1, 27)]

plain_cipher = dict(zip(chars, nums))

prompt = input("Enter a word to decipher > ")

# Ciphering ... 
print('Ciphering ... ')
cipher = [str(plain_cipher[char]+1)for char in prompt]

print('-'.join(cipher))

# Deciphering ...
decipher = [int(num)-1 for num in cipher]
text = ''

for k in plain_cipher.keys():
    for n in decipher:
        if plain_cipher[k] == n:
            text += k

print('Deciphering ... ')
print(text)

. code execution output

Prints out the correct ciphered output but the wrong deciphered output. Output returned alphabetically. How do you correct this?

1 Answers

The problem is that when you look for a match you're iterating through the keys of the plain_cipher dictionary in the outer loop, then the ciphered message in the inner loop - so you'll see results in the order the dictionary iterator gives you (ie alphabetical).

for k in plain_cipher.keys():
    for n in decipher:
        if plain_cipher[k] == n:
            text += k

Switch the two loops and you'll search through the ciphertext decoding letters as you go:

for n in decipher:
    for k in plain_cipher.keys():
        if plain_cipher[k] == n:
            text += k
Related