我知道有很多方法可以编写 ROT(n) 函数。但我不想有一些带有字符的表格。
所以,我尝试用解码器编写一个简单的 ROT(n) 作为练习项目。编码功能工作正常。但是解码器不断将“a”更改为“z”。
有人可以向我解释我做错了什么吗?
下面的(Python3)代码将所有内容更改为小写,忽略任何特殊字符。
import random
import string
shift = random.randint(1, 20)
# Encoder:
def encode(string):
coded_string = []
string = string.lower()
for c in string:
if ord(c) >= 97 and ord(c) <= 122:
c = (ord(c) + shift) % 122
if c <= 97:
c += 97
coded_string.append(chr(c))
continue
coded_string.append(c)
return ''.join(coded_string)
# Decoder:
def decode(string):
decoded_string = []
for c in string:
if ord(c) >= 97 and ord(c) <= 122:
if ord(c) - shift <= 97:
c = (ord(c) % 97) + (122 - shift)
decoded_string.append(chr(c))
continue
c = ord(c) - shift
decoded_string.append(chr(c))
continue
decoded_string.append(c)
return ''.join(decoded_string)
# Test Function:
def tryout(text):
test = decode(encode(text))
try:
assert test == text, 'Iznogoedh!'
except AssertionError as AE:
print(AE, '\t', test)
else:
print('Yes, good:', '\t', test)
# Random text generator:
def genRandomWord(n):
random_word = ''
for i in range(n):
random_word += random.choice(string.ascii_lowercase)
return random_word
# Some tests:
print(f'Shift: {shift}')
tryout('pokemon')
tryout("chip 'n dale rescue rangers")
tryout('Ziggy the Vulture or Zurg')
tryout('Fine # (*day%, to* code@ in Pyth0n3!')
tryout(genRandomWord(10))
tryout(genRandomWord(20))
示例输出:
Shift: 7
Yes, good: pokemon
Iznogoedh! chip 'n dzle rescue rzngers
Iznogoedh! ziggy the vulture or zurg
Iznogoedh! fine # (*dzy%, to* code@ in pyth0n3!
Yes, good: qrwmfyogjg
Yes, good: ihrcuvzyznlvghrtnuno
但是,忽略随机字符串测试,我期望:
Shift: 7
Yes, good: pokemon
Yes, good: chip 'n dale rescue rangers
Yes, good: ziggy the vulture or zurg
Yes, good: fine # (*day%, to* code@ in pyth0n3!