如何解码编码的句子?

时间:2015-10-11 18:49:30

标签: python

我不太确定为什么StackOverflow不允许我在下面发布我的代码,所以我附上一些链接来展示我尝试过的内容。输入我的句子后,它将从1-25移动任何数量的字符,这很好。但是,我需要添加一个将反转编码的函数,并将原始句子打印出来。我不太确定为什么Python会在解码的句子中吐出,就像在第二个链接中那样。它应该有原始句子。谢谢你的帮助!

def encode( ch, shift):
    lower = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWZ'
    if ch not in lower:
        return ch
    newch = chr( ord(ch) + shift )
    if newch not in lower:
        newshift = ( ord(newch) - ord('z') - 1)
        nwech = chr ( ord('a') + newshift )
    return newch

def decoded(ch, shift):
    lower = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWZ'
    if ch not in lower:
        return ch
    newch = chr( ord(ch) + shift )
    if newch not in lower:
        newshift = ( ord(newch) - ord('z') - 1)
        newch = chr ( ord('a') + newshift)
    return newch

def main():
    shift = int(input("Enter a number between 1 and 25:"))
    sentence = input("Please enter a sentence:")
    code = ''
    decode = ''
    for char in sentence:
        code = code + encode (char, shift)
    for char in code:
        decode = decode + encode (char, shift)
    print("Uncoded sentence: " + sentence)
    print("Encoded sentence: " + code)
    print("Decoded sentence: " + decode)

main()
Enter a number between 1 and 25:3
Please enter a sentence:i need help
Uncoded sentence: i need help
Encoded sentence: l qhhg khos
Decoded sentence: o tkkj nkrv

2 个答案:

答案 0 :(得分:0)

您不能调用解码方法。你调用编码方法两次......

答案 1 :(得分:0)

您的decoded函数似乎与您的encode函数相同(并且在任何情况下都不会调用它)。更贴近您的需求是:

newch = chr( ord(ch) - shift )

在您的decoded函数中,您应该在此处代替encode调用:

for char in code:
    decode = decode + decoded(char, shift)

但现在你还有另外一个问题。如果您的班次让您离开角色ord范围的末尾,会发生什么?