在Python中使用zip()方法编写凯撒密码

-1 投票
2 回答
814 浏览
提问于 2025-04-17 07:11

我有一个作业问题:要用一种叫做凯撒密码的方法来加密一条信息。我需要让用户输入一个数字,这个数字用来决定加密的位移。例如,位移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 个回答

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

你可以用 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())

撰写回答