每日codingame小游戏练习[2021.4.01](python入门学习)
作者:互联网
题目描述
In Caesar Code you take every letter of the given text and move them forward by the integer k in the alphabet. (Attention: After z comes a)
Example:
Normal text: “hello”
k = 2
h -> j
e -> g
l -> n
l -> n
o -> q
Encrypted text: “jgnnq”
Caesar Code is easy to break. Let’s try something a little harder.
Your task is now to encrypt a given text t with a substitution, but now k increases for each character (not only letter) by 1. For the first character k = 0, for the second k = 1, for the third k = 2 …
Leave everything that is not a letter (number, punctuation mark…) as it is.
eg:
Input | Output |
---|---|
aaaaaa | abcdef |
题目分析
题目有点长,直接看例子比较好。是一道有关凯撒密码变种,位移字母的算法。
解题代码
因为我的代码,没调试完成,直接分析俄罗斯老哥的代码:
for i,c in enumerate(input()):x=65+32*c.islower();print(end=(c,chr((ord(c)-x+i)%26+x))[c.isalpha()])
把代码简化后:
for i,c in enumerate(input()): #提取下标
x=65+32*c.islower() #判断大小写
print((c, chr((ord(c)-x+i)%26+x)) [c.isalpha()],end= '')
#c.isalpha()用于根据凯撒密码的规律判断是否是英文,数字原样输出,英文按照凯撒规律后移
#chr((ord(c)-x+i)%26+x)对于出现“ZZZZZ”或者“zzzzz”的情况做处理
总结
- Python enumerate() 函数:用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
- Python3 islower()方法:用于检测字符串是否由小写字母组成。
- Python isalpha()方法:用于检测字符串是否只由字母组成。
- 看到题目是一道有关凯撒密码的算法题,身为ctfer的我一阵狂喜,但在写完代码的调试过程中又被泼了一阵冷水,俄罗斯人真的很厉害,学到了。
标签:26,01,2021.4,python,text,代码,isalpha,ord,凯撒 来源: https://blog.csdn.net/m0_50317371/article/details/115384387