用Python编程;使用zip()方法编写Caesar Cipher

时间:2011-11-28 01:31:00

标签: python

我有一个家庭作业问题:使用Caesar cipher加密邮件。我需要能够让用户输入一个数字来加密加密。例如,移位4会将“A”变为“E”。用户还需要输入要翻译的字符串。该书说要使用zip()函数来解决问题。我不确定这是怎么回事。

我有这个(但它没有做任何事情):

def caesarCipher(string, shift):
    strings = ['abc', 'def']
    shifts = [2,3]
    for string, shift in zip(strings, shifts):
        # do something?

print caesarCipher('hello world', 1)

2 个答案:

答案 0 :(得分:3)

“zip”是Python的内置函数,而不是问题标题所暗示的特定类型的方法。

>>> help(zip)
Help on built-in function zip in module __builtin__:

zip(...)
    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is truncated
    in length to the length of the shortest argument sequence.

>>> 

答案 1 :(得分:1)

您可以使用zip()构建查找表(字典),并使用字典来加密文本。

from string import ascii_lowercase as alphabet

def cipher(plaintext, shift):
   # Build a lookup table between the alphabet and the shifted alphabet.
   table = dict(zip(alphabet, alphabet[shift:] + alphabet[0:shift]))
   # Convert each character to its shifted equivalent. 
   # N.B. This doesn't handle non-alphabetic characters
   return ''.join(table[c] for c in plaintext.lower())