There's a lot going on here, but you're definitely having issues with your encode
and decode
functions. If I understand what you're trying to do, you could rewrite them as follows:
def encode(string):
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
key = 'XPMGTDHLYONZBWEARKJUFSCIQV'
encoded = []
for character in string:
character_index = alpha.index(character)
encoded.append(key[character_index])
return ''.join(encoded)
def decode(string):
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
key = 'XPMGTDHLYONZBWEARKJUFSCIQV'
decoded = []
for character in string:
character_index = key.index(character)
decoded.append(alpha[character_index])
return ''.join(decoded)
Each function is doing essentially the same thing (here's what encode
is doing:
- Creating an empty list called encoded. I'll use this to store each character, translated, in order.
- Loop through the characters of the string passed in.
- At each iteration, find its index in the string
alpha
.
- Find the character in
key
at that same index and append that character to the list encoded
- Once all the characters have been translated, join them into a string and return that string.
Note: This will fail if a character in the string
argument is not found in the alpha
string. You could add some error checking.
You could make this even more general if you wanted to allow for different keys. You could write a translate
function like this:
def translate(string, from_language_string, to_language_string):
translated = []
for character in string:
character_index = from_language_string.index(character)
translated.append(to_language_string[character_index])
return ''.join(translated)
And then your encode
and decode
functions could be written like this:
def encode(string):
return translate(string, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'XPMGTDHLYONZBWEARKJUFSCIQV')
def decode(string):
return translate(string, 'XPMGTDHLYONZBWEARKJUFSCIQV', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
To address what's going on in the rest of your code, for the conditionals in your main
function, you'll just want to make sure to pass the strings read in from raw_input
to the encode
and decode
functions as needed. Something like this:
if response == '1':
plain = raw_input('text to be encoded: ')
print encode(plain)
# and so on
Good luck.