如何在单词开头重新开始?
要应用Vigenere编码,我们必须将字母移动,但不是全部以相同的数字来移动。关键是这次的关键字,每个字母都会让我们进行轮班(以a换档为0,b以换档1 ...)。
让我们以一个例子来解释方法:让我们想象关键字是“数学”,而通往代码的单词是“ python”。 对于代码P,我将对应于m的数字移动,即12(因为我们从0开始,从a开始),这使我b作为编码P。 让我们继续前进:我将其转移到对应于a,ie 0的数字,所以y是在这里编码y的。 让我们去t转移到t的数字,即19 等等。
import string
def vigenere_cipher(msg, shift):
encrypted = ''
for i,j in zip(msg,shift):
new_index = ( string.ascii_uppercase.index(i) + string.ascii_uppercase.index(j) ) % 26
encrypted += string.ascii_uppercase[new_index]
return encrypted
print(vigenere_cipher('PYTHON', 'MATH'))
如果我们的关键字太短,我们会从单词的开头重新开始,IE n将被与M相对应的数字移动,而
我的问题实际上是最后一部分,我可以简单地说,如果关键字也是如此简而言之,我们从单词的开头重新开始?
因为只有“ pyth”部分以数学为钥匙加密为“ bymo”,而不是“ on”
To apply a Vigenere coding, we have to shift the letters but not all by the same number. The key is this time a keyword which each letter gives us the shift to be done (taking A for a shift of 0, B for a shift of 1 ...).
Let's take an example to explain the method: Let's imagine that the keyword is "MATHS" and the word to code is "PYTHON".
To code P, I shift the number corresponding to M, i.e. 12 (because we start at 0 with A) which gives me B as coding for P.
Let's move on to Y: I shift it by the number corresponding to A, i.e. 0, so Y is the coding for Y here.
Let's go to T which is shifted by the number corresponding to T, i.e. 19, so T becomes M once shifted
And so on.
import string
def vigenere_cipher(msg, shift):
encrypted = ''
for i,j in zip(msg,shift):
new_index = ( string.ascii_uppercase.index(i) + string.ascii_uppercase.index(j) ) % 26
encrypted += string.ascii_uppercase[new_index]
return encrypted
print(vigenere_cipher('PYTHON', 'MATH'))
If our keyword is too short we start again at the beginning of the word, i.e. N will be shifted by the number corresponding to M.
My problem right here is actually with the last part, How I can simply say that if the keyword is too short we start again at the beginning of the word ?
Because only "PYTH" part is encrypted to "BYMO" with MATH as a key but not the "ON"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需添加行
shift = shift *(len(msg)// len(shift) + 1)
在函数开始时,请重复shift
,直到比它更长msg
(例如,这一行转动数学
到MATHMATH
)输出:
bymoan
Just add the line
shift = shift * (len(msg) // len(shift) + 1)
at the start of the function soshift
is repeated until it's longer thanmsg
(e.g. this line turnsMATH
intoMATHMATH
)Output:
BYMOAN
我认为这里的主要问题是,当您实际上不需要这样做时,您同时将
msg
和shift> shift
在一起。您已经了解了使用%
保证您保持在最大数字小的数字的概念,因此我将修改您的功能,还可以使用%
选择哪个您想使用的转移角色I think the main issue here is that you're zipping both
msg
andshift
together, when you don't actually need to do so. You already understand the concept of using%
to guarantee that you stay on a number smaller than your max number, so I'll modify your function to also use%
to select which character from shift you want to use