题解 | #HJ29 字符串加解密#

字符串加解密

http://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a

Python版本

Python 里无法直接对单个字符作差得到ASCII码(Unicode码),所以需要借助 ordchr,或者你能记住 aA0 的ASCII码也行……

def crypto(string):
    temp = []
    for c in string:
        if ord('a') <= ord(c) <= ord('z'):
            temp.append(chr((ord(c.upper())-ord('A')+1)%26 + ord('A')))
        elif ord('A') <= ord(c) <= ord('Z'):
            temp.append(chr((ord(c.lower())-ord('a')+1)%26 + ord('a')))
        elif ord('0') <= ord(c) <= ord('9'):
            temp.append(str((int(c)-0+1)%10+0))
        else:
            temp.append(c)
    return ''.join(temp)

def decrypt(string):
    temp = []
    for c in string:
        if ord('a') <= ord(c) <= ord('z'):
            temp.append(chr((ord(c.upper())-ord('A')+25)%26 + ord('A')))
        elif ord('A') <= ord(c) <= ord('Z'):
            temp.append(chr((ord(c.lower())-ord('a')+25)%26 + ord('a')))
        elif ord('0') <= ord(c) <= ord('9'):
            temp.append(str((int(c)-0+9)%10+0))
        else:
            temp.append(c)
    return ''.join(temp)

while True:
    try:
        string_raw = input()
        string_cpt = input()
        print(crypto(string_raw))
        print(decrypt(string_cpt))
    except Exception:
        break

全部评论

相关推荐

评论
点赞
5
分享
牛客网
牛客企业服务