【问题标题】:Python exercise Vigenère codePython 练习 Vigenère 代码
【发布时间】:2016-12-15 09:46:34
【问题描述】:

我对以下代码有疑问:

ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def main():
 encrypt_code = codeer('NOBODY EXPECTS THE SPANISH INQUISITION!', 'CIRCUS')
 print("{}".format(encrypt_code))
 print("{}".format(decrypt('CIRCUS', encrypt_code)))

def codeer(tekst, sleutel):
 pairs = zip(tekst, cycle(sleutel))
 code = ""

 for pair in pairs:
    total = reduce(lambda x, y: ALPHA.index(x) + ALPHA.index(y), pair)
    code += ALPHA[total % 26]

 return code;

此代码将崩溃,因为该消息包含一个空格和一个!符号。

total = reduce(lambda x, y: ALPHA.index(x) + ALPHA.index(y), pair) ValueError: 未找到子字符串

谁能帮我解决我的问题

以下是预期输出的示例:

codeer('NOBODY EXPECTS THE SPANISH INQUISITION!', 'CIRCUS')
'PWSQXQ MORYUVA VBW AGCHAUP KHIWQJKNAQV!'

decodeer('PWSQXQ MORYUVA VBW AGCHAUP KHIWQJKNAQV!', 'CIRCUS')
'NOBODY EXPECTS THE SPANISH INQUISITION!'

【问题讨论】:

  • 使用find() 来避免抛出错误? (虽然我猜这会给你错误的结果)
  • 您应该解释预期的输出和行为是什么 - 例如:空格和感叹号字符应该发生什么?
  • 您好,我目前正在使用 find 来查看字母表中存在的字符,但是,我收到以下异常:TypeError: not all arguments convert during string formatting

标签: python vigenere


【解决方案1】:

在我看来,您需要做的就是仅当相关字符为大写字母时才进行编码/解码。请参阅下面的示例,了解我的想法。

def codeer(tekst, sleutel):
    pairs = zip(tekst, cycle(sleutel))
    code = ""

    for pair in pairs:
        if pair[0].isupper():
            total = reduce(lambda x, y: ALPHA.index(x) + ALPHA.index(y), pair)
            code += ALPHA[total % 26]
        else:
            code += pair[1]
    return code

你可以观察它的执行here。它似乎产生了所需的输出。

【讨论】:

  • @Michael 他们是一样的。唯一的区别是前导单引号和尾随单引号,如果它们真的很重要,您可以将它们连接起来。我是否错过了其他不同的东西?
  • @Michael 您在问题中提供的代码不包含函数解码器,这就是为什么我在回复中包含的 ideone 链接在 main() 函数中没有对解码器的调用。如果您可以将解码器的代码添加到您的问题中,我可以修改我的答案以包括对解码器的修改,这与编码器非常相似。