Python 中的凯撒密码
假设我们有一个小写字母字符串 s 和一个偏移数字 k。我们需要将 s 中的每个字母替换为字母表中后移 k 个位置的字母。我们需要记住,当字母超出 a 或 z 时,它会在另一侧换行。
因此,如果输入类似于“hello”,k = 3,则输出将为“khoor”
要解决此问题,我们将按照以下步骤进行 −
定义一个 shift() 函数。它将获取 c
i := ASCII (c) - ASCII('a')
i := i + k
i := i mod 26
返回 ASCII (ASCII('a') + i) 中的字符
在主方法中,执行以下操作 −
ret := 对于 s 中的每个字符 c,通过调用 shift(c) 生成一个元素列表
返回 ret
让我们看看下面的实现以更好地理解 −
示例
class Solution: def solve(self, s, k): def shift(c): i = ord(c) - ord('a') i += k i %= 26 return chr(ord('a') + i) return "".join(map(shift, s)) ob = Solution() print(ob.solve("hello", 3))
输入
"hello", 3
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
khoor
广告