-1

我正在尝试使用 python 制作凯撒密码,这就是我能做到的:

alphabet = ['abcdefghijklmnopqrstuvwxyz']

def create(shift):
    dictionary={}
    emptylist=[]
    int(shift)
    for x in alphabet:
        emptylist.append(x)
        code = ""
        for letters in emptylist:
            code = code + chr(ord(letters) + shift)
            dictionary[letters]=code
    return dictionary

它可以让我输入我的班次值,然后打印:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    create(2)
  File "C:/Users/Pete/Documents/C- Paisley/A-Level/Computing/dictionarytolist.py", line 11, in create
    code = code + chr(ord(letters) + shift)
TypeError: ord() expected a character, but string of length 26 found

最终产品应该是打印移位的字母。

4

2 回答 2

2

一个更简单的方法是


def create(shift):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    return alphabet[shift:] + alphabet[:shift]

于 2012-09-25T19:07:33.327 回答
1

您可以尝试将此代码用于您的密码。关于如何使用它应该是相当不言自明的。

>>> UPPER, LOWER = ord('A'), ord('a')
>>> def encode(text, shift):
    data = list(text)
    for i, c in enumerate(data):
        if c.isalpha():
            base = UPPER if c.isupper() else LOWER
            data[i] = chr((ord(c) - base + shift) % 26 + base)
    return ''.join(data)

>>> def decode(text, shift):
    return encode(text, -shift)

>>> encode('This is a test.', 0)
'This is a test.'
>>> encode('This is a test.', 1)
'Uijt jt b uftu.'
>>> encode('This is a test.', 2)
'Vjku ku c vguv.'
>>> encode('This is a test.', 26)
'This is a test.'
>>> encode('This is a test.', 3)
'Wklv lv d whvw.'
>>> decode(_, 3)
'This is a test.'
>>> 
于 2012-09-25T21:45:10.143 回答