2012-09-25 132 views
-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 

最終產品應該是它打印移位的字母。

+5

你要問一個更具體的問題。 – CrazyCasta

+3

任何問題都可以開始。 –

+0

任何人都可以告訴我我哪裏出錯了嗎? – PazzaPythonNewbie

回答

2

靜止簡單的方法是

 

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

這不會工作,如果字符串比'其他的東西'abcdefghijklmnopqrstuvwxyz''爲'「foo''with'移= 1'返回'」 oof''。 –

+0

我以爲我們只是創造的密碼。這產生對應於明文字母(回想密碼字母,我不應該回答了這樣一個不適當的提問) – BostonJohn

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.' 
>>>