-1

我构建了一个简单的消息编码器和解码器。编码器将每个字母的值递减 3。例如:A 将被 D 替换,B 将变为 E。解码器则相反。有没有办法像我用编码器那样用更少的代码编写解码器?我试图这样做(我输入了代码),但它不起作用。有什么建议么?

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),
"""
4

1 回答 1

0

您可以使用列表推导或生成器表达式来使代码更短。

>>> message = 'HelloWorld'
>>> encoded = ''.join(chr(ord(letter) - 3) for letter in message)
>>> decoded = ''.join(chr(ord(letter) + 3) for letter in encoded)
于 2013-03-22T18:43:10.353 回答