-2

I built a simple message encoder and decoder. The encoder decrements each letter's value by 3. For example: A would be replaced by D, and B would become E. The decoder does the opposite. Is there a way to write the decoder with less code like I did it with the encoder? I tried to do it (I put in the code), but it doesn't work. Any suggestions?

import string

shift = 3 # a shift of 3 letters. for example: A would become D, B would become E...

# encoding message
encode = raw_input("Enter message to encode: ")
print "The encoded message is:",
for i in encode:
    print int(ord(i))-shift, # convert characters to numbers

print
print

#decoding message
decode = raw_input("Enter message to decode: ")
message = ""
for numStr in string.split(decode):
    asciiNum = eval(numStr) # convert digits to a number
    message = message + chr(asciiNum+shift) # append character to message and add shift

print "The decoded message is:", message

"""
#decoding message
decode = raw_input("Enter message to decode: ")
decode = int(decode)

print chr(decode+shift) # only works for one number

# doesn't work
for i in range(decode):
    print chr(decode+shift),
"""
  • aka "Caesar cipher": http://en.wikipedia.org/wiki/Caesar_cipher. Easy to crack. – duffymo Mar 22 '13 at 18:28
  • 1
    Yeah, I know. Just started Python. –  Mar 22 '13 at 18:30
  • FWIW, I find the encoder poor style because it does *too much* in one line. It encodes the data, and it prints the result. I'd prefer to see `cipher=[] ; for i in encode: cipher.append(int(ord(i))-shift)` followed by (after the loop is finished) `print cipher`. – Robᵩ Mar 22 '13 at 18:40
  • 1
    You say that your encoding method turns "A" into "D", but that's not true. It turns it into 62. If you meant, it turns "A" into the ordinal value of "D", that's _still_ not true. the ordinal value of "D" is 68. You turn "A" into the ordinal value of ">". – Kevin Mar 22 '13 at 18:43
  • 1
    You might find this [question](http://stackoverflow.com/questions/3269686/short-rot13-function) useful. – John Mar 22 '13 at 18:59
  • Rob - thanks for the advice. Kevin - you're right, it doesn't do what I described, but it still works. –  Mar 22 '13 at 19:37

1 Answers1

0

You could use list comprehensions or generator expressions to make the code much shorter.

>>> message = 'HelloWorld'
>>> encoded = ''.join(chr(ord(letter) - 3) for letter in message)
>>> decoded = ''.join(chr(ord(letter) + 3) for letter in encoded)
Ryan O'Neill
  • 3,727
  • 22
  • 27