没啥好说的,按照规则一个一个替换就好了,注意一下边界处理。
import sys
_ord_0 = ord("0")
_ord_9 = ord("9")
_ord_a = ord("a")
_ord_z = ord("z")
_ord_A = ord("A")
_ord_Z = ord("Z")
def encode(s):
result = []
for each in s:
t = 0
cn = ord(each)
# 特殊处理
if cn == _ord_9:
t = _ord_0
elif cn == _ord_z:
t = _ord_A
elif cn == _ord_Z:
t = _ord_a
# 通常处理
else:
# 如果是数字(非9)
if _ord_0 <= cn < _ord_9:
t = cn + 1
# 如果是小写字母(非z)
elif _ord_a <= cn < _ord_z:
t = cn - _ord_a + _ord_A + 1
# 如果是大写字母(非Z)
elif _ord_A <= cn < _ord_Z:
t = cn - _ord_A + _ord_a + 1
result.append(chr(t))
return "".join(result)
def decode(s):
result = []
for each in s:
t = 0
cn = ord(each)
# 特殊处理
if cn == _ord_0:
t = _ord_9
elif cn == _ord_A:
t = _ord_z
elif cn == _ord_a:
t = _ord_Z
# 通常处理
else:
# 如果是数字(非0)
if _ord_0 < cn <= _ord_9:
t = cn - 1
# 如果是小写字母(非a)
elif _ord_a < cn <= _ord_z:
t = cn - _ord_a + _ord_A - 1
# 如果是大写字母(非A)
elif _ord_A < cn <= _ord_Z:
t = cn - _ord_A + _ord_a - 1
result.append(chr(t))
return "".join(result)
for idx, line in enumerate(sys.stdin):
a = line.strip()
if idx == 0:
print(encode(a))
elif idx == 1:
print(decode(a))



京公网安备 11010502036488号