在Python中简化Vigenere密码程序

时间:2016-05-12 20:16:12

标签: python python-2.7 lambda vigenere

我有下面的程序,它被传递给另一个函数,它只打印出原始和加密的消息。我想知道如何简化这个程序,特别是" match = zip"和"改变=(减少(lambda"行。如果可能的话,不使用lambda这样做,我该怎么办?

from itertools import cycle

alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

def vigenereencrypt(message,keyword):
    output = ""    
    match = zip(message.lower(),cycle(keyword.lower()))
    for i in match:
        change = (reduce(lambda x, y: alphabet.index(x) + alphabet.index(y), i)) % 26
        output = output + alphabet[change]
    return output.lower()

3 个答案:

答案 0 :(得分:2)

两件事:

  1. 您不需要拥有本地变量.Last.value %>% select(Interval) %>% unique Interval 1 2015-01-08 UTC--2015-01-09 UTC 3 2015-01-13 UTC--2015-01-15 UTC 4 2015-01-07 UTC--2015-01-17 UTC 6 2015-01-08 UTC--2015-01-16 UTC ,只需循环match
  2. 您可以在for循环定义中拆分两个索引zipx,而不是使用y; reduce通常用于较大的iterables,并且由于reduce中只有2个项目,因此会增加不必要的复杂性。
  3. 即,您可以将for循环定义更改为:

    i

    以及您对for x, y in zip(...): 的定义:

    change

答案 1 :(得分:1)

从R Nar所说的开始:

def vigenereencrypt(message,keyword):
    output = ""
    for x, y in zip(message.lower(), cycle(keyword.lower())):
        change = (alphabet.index(x) + alphabet.index(y)) % 26
        output = output + alphabet[change]
    return output.lower()

通过使用列表然后加入它,而不是添加到字符串,并注意到输出已经是小写,我们可以更高效:

def vigenereencrypt(message,keyword):
    output = []
    for x, y in zip(message.lower(), cycle(keyword.lower())):
        change = (alphabet.index(x) + alphabet.index(y)) % 26
        output.append(alphabet[change])
    return "".join(output)

然后我们可以将循环体减少到一行..

def vigenereencrypt(message,keyword):
    output = []
    for x, y in zip(message.lower(), cycle(keyword.lower())):
        output.append(alphabet[(alphabet.index(x) + alphabet.index(y)) % 26])
    return "".join(output)

...所以我们可以把它变成列表理解:

def vigenereencrypt(message,keyword):
    output = (
        alphabet[(alphabet.index(x) + alphabet.index(y)) % 26]
        for x, y in zip(message.lower(), cycle(keyword.lower()))
    )
    return "".join(output)

我觉得我们可以用map(alphabet.index, ...)做些什么,但我想不出一种比列表理解更好的方法。

答案 2 :(得分:0)

你可以用一堆索引代替zip ...

string