题解 | 凯撒加密
凯撒加密
https://www.nowcoder.com/practice/006b7917d3784371a43cfbae01a9313d
n = int(input())
s = input()
# 先创建正向和反向映射(不用推导式)
letter_to_num = {
'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10,
'k':11, 'l':12, 'm':13, 'n':14, 'o':15, 'p':16, 'q':17, 'r':18, 's':19,
't':20, 'u':21, 'v':22, 'w':23, 'x':24, 'y':25, 'z':26
}
# 创建反向映射
num_to_letter = {value:key for key,value in letter_to_num.items()}
# 计算密码
password = []
for ch in s:
# 获取字母对应的数字
num = letter_to_num[ch]
# 加上偏移量
new_num = num + n
# 处理循环(z后面是a)
if new_num > 26:
new_num = new_num % 26
if new_num == 0: # 处理整除的情况
new_num = 26
# 找到对应的字母
new_letter = num_to_letter[new_num]
password.append(new_letter)
print("".join(password))
好几个崭新知识点和用法:
① rules.items() 返回:[('a',1), ('b',2), ('c',3)](键值对元组的列表);for char,num in rules.items() 可以正确解包为两个变量
- 直接遍历字典:得到键
- 遍历 .items():得到键值对(元组)
- 遍历 .values():得到值
② ASCII 版本说明:
- ord(ch) - ord('a'):将字母转换为 0-25 的数字。
- + n 后 % 26:实现循环移位。
- + ord('a'):将数字转回字母的 ASCII 码。
- chr(...):将 ASCII 码转为字符。
n = int(input())
s = input()
res = []
for ch in s:
shifted = chr((ord(ch) - ord('a') + n) % 26 + ord('a'))
res.append(shifted)
print("".join(res))