python - 我的 Python Caeser Cipher 程序在 30 后停止移动
问题描述
我创建了一个函数,将输入的字符串拆分为单词列表,然后将每个单词中的字母替换为其移位的对应字符,但是当我将移位设置为超过 30 时,它的打印结果不变。
def ceaser_cipher_encoder(string , num):
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
new_string = ""
string_list = string.split(" ")
new_list = []
for word in string_list:
word1 = ""
for charecter in word:
letter_position = alphabet.index(charecter)
letter_position_with_shift = letter_position + num
if letter_position_with_shift > 25:
letter_position_with_shift = 0 + ((letter_position - 25) - 1)
word1 += charecter.replace(charecter, alphabet[letter_position_with_shift])
new_list.append(word1)
end_string = " ".join(new_list)
return end_string
message = ceaser_cipher_encoder("hello dad", 35)
print(message)
解决方案
这里一个有用的技巧是使用模运算符 ( %
)。它将为您处理转变。
这是我会怎么做:
def ceaser_cipher_encoder(string , num):
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
new_string = ""
for c in string:
new_string += alphabet[(alphabet.index(c) + num) % len(alphabet)]
return new_string
假设c
是“y”并且num
是 10。然后您将alphabet.index(c)
等于 24,因此移位将返回 34。由于 34 模 26 为 8,因此它将alphabet[8]
(“i”) 附加到new_string
.
我使用len(alphabet)
而不是硬编码 26,以便您可以更改字母表并且代码仍然可以使用。
推荐阅读
- c# - 如何在 xaml 和 wpf 中将菜单项与 observableCollection 绑定?
- c++ - C++ 使用参数返回指针 - 不同指针类型之间的比较缺少强制转换
- graphql - 将 graphql 发送到 Restsharp 自动化中的 Post 正文
- powershell - Powershell 构建损坏的路径
- c# - Blazor 获取对单击元素的引用
- firebase - Unity Firebase Crashlytics 未发送任何崩溃报告,在 logcat 上出现“无法检索设置”错误
- jfreechart - 如何在 JFreeChart 中显示价格下跌的交叉线和红色?
- javascript - 如何在单击按钮时删除特定数量的 DOM 元素?
- java - 按顺序遍历两棵二叉树以比较哪一棵更大
- ios - 在 Objective-C 中找不到带有 Swift 类参数的方法