每日codingame小游戏练习[2021.4.01](python3入门学习之凯撒密码)

题目描述

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:

InputOutput
aaaaaaabcdef

题目分析

题目有点长,直接看例子比较好。是一道有关凯撒密码变种,位移字母的算法。

解题代码

因为我的代码,没调试完成,直接分析俄罗斯老哥的代码:

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”的情况做处理

总结

  1. Python enumerate() 函数:用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
  2. Python3 islower()方法:用于检测字符串是否由小写字母组成。
  3. Python isalpha()方法:用于检测字符串是否只由字母组成。
  4. 看到题目是一道有关凯撒密码的算法题,身为ctfer的我一阵狂喜,但在写完代码的调试过程中又被泼了一阵冷水,俄罗斯人真的很厉害,学到了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值