-2
from random import shuffle  

alphabet="abcdefghijklmnopqrstuvwxyz"  

def substitution(alphabet,plaintext):  

    # Create array to use to randomise alphabet position  
    randarray=range(0,len(alphabet))  
    shuffle(randarray)  

    key="Zebra"  

    #Create our substitution dictionary  
    dic={}  
    for i in range(0,len(alphabet)):  
        key+=alphabet[randarray[i]]  
        dic[alphabet[i]]=alphabet[randarray[i]]  

    #Convert each letter of plaintext to the corrsponding  
    #encrypted letter in our dictionary creating the cryptext  
    ciphertext=""  
    for l in plaintext:  
        if l in dic:  
            l=dic[l]  
        ciphertext+=l  
    for i in alphabet:  
        print i,  
    print  
    for i in key:  
        print i,  
    print  
    return ciphertext,key  

# This function decodes the ciphertext using the key and creating  
# the reverse of the dictionary created in substitution to retrieve  
# the plaintext again  
def decode(alphabet,ciphertext,key):  

    dic={}  
    for i in range(0,len(key)):  
        dic[key[i]]=alphabet[i]  

    plaintext=""  
    for l in ciphertext:  
        if l in dic:  
            l=dic[l]  
        plaintext+=l  

    return plaintext  

# Example useage  
plaintext="the cat sat on the mat"  
ciphertext,key=substitution(alphabet,plaintext)  
print "Key: ", key  
print "Plaintext:", plaintext  
print "Cipertext:", ciphertext  
print "Decoded  :", decode(alphabet,ciphertext,key)

このコードを実行すると、"IndexError: String index out of range"エラーが返されます。誰かがトラブルシューティングを手伝ってくれませんか。問題がわかりません。

トレースバック (最新の呼び出しが最後):
  File"/Users/Devlin/Desktop/Dev/Python/Substitution Cypher.py"、57 行目
    print "Decoded :", decode(alphabet,ciphertext,key)
  ファイル「/Users/Devlin/Desktop/Dev/Python/Substitution Cypher.py」、41 行目、デコード
    dic[key[i]]=alphabet[i] IndexError: 文字列インデックスが範囲外です
4

2 に答える 2

0

問題はここにあります:

def decode(alphabet,ciphertext,key):  
    dic={}  
    for i in range(0,len(key)):  
        dic[key[i]]=alphabet[i] # this line fails

この時点keyで常に 31 文字、つまりlen('Zebra') + len(alphabet). len(alphabet)常に 26 であり、alphabet[i]i > 25 の場合は失敗します。

ここで表されているものを誤解していると思いますkeyランダム化されたキーを生成substitutionする必要があります。これは、パスワードやソルトではありません。実際、このコードを から入手した元の記事を見ると、ランダム値ではなく、 にあることがわかります。key=""substitution

于 2012-09-04T05:52:30.363 に答える
0
for i in range(0,len(key)):  
    dic[key[i]]=alphabet[i] 

ここで、len(key) == len(alphabet) + 5. したがって、i(反復range(0, len(key))) は実際のアルファベットの長さよりも長くなります。これは一部によるものです

key="Zebra"  #HERE, YOU START WITH ZEBRA

#Create our substitution dictionary  
dic={}  
for i in range(0,len(alphabet)):  
    key+=alphabet[randarray[i]]  #AND HERE, YOU ADD TO ZEBRA
    dic[alphabet[i]]=alphabet[randarray[i]]  

繰り返しますが、keyよりも に多くの文字が含まれalphabetているため、エラーが発生します。

解決策は行を変更することです

key="Zebra"

key=""

そもそもなぜ「ゼブラ」にしたかったのですか?

* PSrange(x)は と同じなので、通常はetcrange(0, x)だけを記述してください... *range(len(key))

于 2012-09-04T05:52:42.193 に答える