首页 文章

这个简单的加密和解密程序有什么问题? [等候接听]

提问于
浏览
0
def enc(a):
    for i in range(len(a)):
        if (i%2==0):
            a[i]=chr(ord(a[i])+3)
        else:
            a[i]=chr(ord(a[i])+5)
    r1 = ''.join(a)
    return r1

def dec(m):
    for i in range(len(m)):
        if (i%2==0):
            m[i]=chr(ord(m[i])-3)
        else:
            m[i]=chr(ord(m[i]+5)
    r2 = ''.join(m)
    return r2
h=input()
print(enc(h))
print(dec(h))

请帮我解决这个可能是愚蠢的错误,我只想要一个输入并加密并解密它

1 回答

  • 1

    我读取你的代码非常有趣,因为前段时间我曾试图自己编写加密和解密 . 所以我想我知道你想要什么 .

    首先,Python字符串不喜欢assignements .

    So we convert the string to a list

    def enc(a):
       a = list(a)
    

    After that we look at your calls

    h=input()
    print(enc(h))
    print(dec(h))
    

    These calls will just produce some "random" strings, so I propose:

    h=input()
    h= enc(h)
    print(h)
    print(dec(h))
    

    这将加密字符串,而不是打印字符串 . 将其传递给dec方法,并在回滚enc中的更改后打印您输入的字符串 .

    At last but not least, we have to look at your dec method:

    else:
          m[i]=chr(ord(m[i]+5)
    

    如果你在enc中使用5,你将永远无法获得原始字符串,这应该是加密和解密中最重要的事情 .

    So you would have to change it to

    else:
          m[i]=chr(ord(m[i])-5)
    

    So if you change that all, the final code should look like that:

    def enc(a):
       a = list(a)
       for i in range(len(a)):
          if (i%2==0):
               a[i]=str(chr(ord(a[i])+3))
           else:
               a[i]=str(chr(ord(a[i])+5))
       r1 = ''.join(a)
       return r1
    
    def dec(m):
        m = list(m)
        for i in range(len(m)):
            if (i%2==0):
                m[i]=str(chr(ord(m[i])-3))
            else:
                m[i]=str(chr(ord(m[i])-5))
        string2 = "".join(m)
        return string2
    
    
    h = "Hallo"
    h = enc(h)
    print(h)
    print(dec(h))
    

    因此,对于字符串“Welcome to StackOverflow”,输出将为:

    after enc: Zjohrrh%wt#XwffpR{hwiqr|
    after dec: Welcome to StackOverflow
    

相关问题