我写了一个带有 2 个参数 m 和 n 的凯撒密码,其中字符的移位如下:
它在编码方面工作正常,但在解码方面却不行。
下面是我的代码。
def encode_cipher(n, m,message):
result = ""
p = m # Initialize p with the additional step shift 'm'
for char in message:
if char.islower():
# Determine the shift value for the current lowercase character
shift = n + p
# Adjust the shift to keep it within the range [0, 25]
shift = shift % 26
new_char = chr(((ord(char) - ord('a') + shift) % 26) + ord('a'))
result += new_char
# Update the value of p for the next character
p = ((ord(new_char) - ord('a')) % 26)
else:
# If the character is not a lowercase letter, leave it unchanged
result += char
return result
# Example usage for encoding
message = "aaaaaa"
n = 2
m = 2
encode_cipher( n, m,message)
#输出是:“egikmo”,如预期。
现在要解密,我写了以下内容:
def decode_cipher(n, m,message):
result = ""
p = m # Initialize p
for char in message:
if char.islower():
shift = n + p
shift = shift % 26
new_char = chr(((ord(char) - ord('a') - shift) % 26) + ord('a'))
result += new_char
# Update the value of p for the next character
p = ((ord(new_char) - ord('a')) % 26)
else:
result += char
return result
# Example
message = "egikmo" # Using output from encode function above.
n = 2
m = 2
decode_cipher( n, m,message)
输出不是“aaaaaa”,即编码前的原始消息。 所以显然减去班次是行不通的,我想知道我错过了什么。
首先,您打算使用 n + m 的移位来加密第一个字符,并且您做得正确。对于所有其他字符,您希望使用 n + 前一个字符的索引的移位进行加密,但您失败了。
我会解释一下,错误很小,位于这一行:
p = ((ord(new_char) - ord('a')) % 26)
相反,您应该只分配当前字符的索引。 为此,您需要获取字符的索引以及字符,而一种方法是迭代消息长度的范围,并使用方括号
[index]
获取字符。
更新
encode
函数后,它看起来像这样:
def encode_cipher(n, m,message):
result = ""
p = m
for i in range(len(message)):
char = message[i]
if char.islower():
shift = n + p
shift = shift % 26
new_char = chr(((ord(char) - ord('a') + shift) % 26) + ord('a'))
result += new_char
p = i
else:
result += char
return result
为了完成这个答案,我们也简单地更新
decode
函数:
def decode_cipher(n, m,message):
result = ""
p = m
for i in range(len(message)):
char = message[i]
if char.islower():
shift = n + p
shift = shift % 26
new_char = chr(((ord(char) - ord('a') - shift) % 26) + ord('a'))
result += new_char
p = i
else:
result += char
return result
还有一件事: 因为函数之间的差异很小,所以我们可以使用相同的函数,稍微调整一下,它看起来像这样:
def my_cipher(n, m, message, decode=False):
result = ""
p = m
for i in range(len(message)):
char = message[i]
if char.islower():
shift = n + p
shift = shift % 26
if not decode:
new_char = chr(((ord(char) - ord('a') + shift) % 26) + ord('a'))
else:
new_char = chr(((ord(char) - ord('a') - shift) % 26) + ord('a'))
result += new_char
p = i
else:
result += char
return result
致以最诚挚的问候,祝您的项目顺利!