在本体密码中的itertools循环导致空格python的问题 [英] itertools cycle in vigenere cipher causing problems with spaces python

查看:224
本文介绍了在本体密码中的itertools循环导致空格python的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代号为vigenere的密码中,我使用itertools循环遍历关键字。这样做很好,直到我在消息中使用空格,因为它加密了空间,从而使加密错误。这是代码。

In my code for vigenere cipher I use cycle from itertools to cycle through the key word. This works great until I use spaces in the message as it encrypts the space therefore making the encryption wrong. Here is the code.

    message = input('enter message: ')
    keyword = input('enter keyword: ')
    def chr_to_int(char):
        return 0 if char == 'z' else ord(char)-96
    def int_to_chr(integer):
        return 'z' if integer == 0 else chr(integer+96)
    def add_chars(a, b):
        return int_to_chr(( chr_to_int(a) + chr_to_int(b)) % 26 )
    def vigenere(message, keyword):
        keystream = cycle(keyword)
        new = ''
        for msg, key in zip(message, keystream):
            if msg == ' ':
                new += ' '
            else:
                new += add_chars(msg, key)
        return new

    new = vigenere(message, keyword)
    print('your encrypted message is: ',new)

我认为解决这个问题的方法是将消息的长度相同的循环遍历消息,这样它就可以继续下一个字母,好像空间不在那里。我不知道该怎么做。

I think a solution to this problem would be to cycle through the space the same length of the message so it will carry on to the next letter as if the space wasn't there. I do not know how to go about how to do this .

示例:

message:vignere cipher keyword :qwerty

message: vignere cipher keyword: qwerty

加密的mesasge(应该是什么):mflahdib hajgvo

encrypted mesasge (what it should be): mflahdib hajgvo

推荐答案

由于循环返回一个可迭代的,您可以使用下一个而不是zip,以便它只调用问:下一个字符:

since cycle returns an iterable, you could instead use next instead of zip so that it only calls for the next char when asked:

>>> def vigenere(message, keyword):
        keystream = cycle(keyword)
        new = ''
        for msg in message:
            if msg == ' ':
                new += ' '
            else:
                new += add_chars(msg, next(keystream))
        return new

>>> new = vigenere('computing is fun', 'gcse')
>>> new
'jrfubwbsn ll kbq'

编辑:每个OP请求,使用zip和偏移变量

per OP request, uses zip and offset variable

>>> def vigenere(message, keyword):
        keystream = cycle(keyword)
        new = ''
        offset = 0
        for msg, key in zip(message,keystream):
            if msg == ' ':
                new += ' '
                offset += 1
            else:
                new += add_chars(msg, keyword[keyword.index(key)-offset])
        return new
>>> new = vigenere('computing is fun', 'gcse')
>>> new
'jrfubwbsn ll kbq'

这篇关于在本体密码中的itertools循环导致空格python的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆