所以我在python中遇到了以下字符串编码方法。
def encode(the_string):
encoded_string = ''
rotations = ord(the_string[-1]) + 5
for i in range(0, len(the_string)):
value = ord(the_string[i])
for j in range(0, rotations):
value -= 1
if value < 65:
value = 25 + value
encoded_string += chr(value)
rotations += ord(the_string[i])-2
return encoded_string
它看起来像一个凯撒密码,其中字母的 ASCII 值决定了字母表的移位次数,但“Z”留在最后。初始旋转数是字符串最后一个字母的 ASCII 值加 5。
def encode(the_string):
ALPHABET='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encoded_string = ''
rotations = (ord(the_string[-1]) + 5) % 25
for i in range(0, len(the_string)):
alphabet_rotate = ALPHABET
print('Rots:',rotations)
for j in range(0, rotations):
alphabet_rotate = alphabet_rotate[1:-1] + alphabet_rotate[0] + alphabet_rotate[-1]
encoded_string += ALPHABET[alphabet_rotate.index(the_string[i])]
rotations += (ord(the_string[i]) - 2)
rotations %= 25
return encoded_string
我正在尝试编写一种解码方法,但是我正在努力为旋转找到正确的偏移量。我正在扭转转变的方向。解码字母的查找也反向工作。这是正确的方法吗?任何帮助将不胜感激。
def decode(the_string):
ALPHABET='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
decoded_string = ''
rotations = (ord(the_string[-1]) + 3) % 25 # <== 1. PROBLEM HERE
for i in range(0, len(the_string)):
alphabet_rotate = ALPHABET
for j in range(0, rotations):
alphabet_rotate = alphabet_rotate[-2] + alphabet_rotate[0:-2] + alphabet_rotate[-1]
decoded_string += alphabet_rotate[ALPHABET.index(the_string[i])]
rotations += (ord(the_string[i]) +20 ) # <== 2. PROBLEM HERE
rotations %= 25
return decoded_string