我的python方法无法正常工作,跳过列表中的项目(playfair密码)

时间:2011-03-25 02:58:22

标签: python

我正在尝试编写一个带密钥和字母表的方法,并创建一个playfair密码框。对于那些不知道它是什么的人来说,它需要密钥并将其放入一个5 x 5的字母网格中,如果需要则溢出到下一行,然后添加字母表中的其余字母。每个字母只应出现在框中一次。我正在尝试使用包含5个内部列表的列表来执行此操作,每个列表包含5个项目。唯一的问题是,该方法应该跳过字母,但事实并非如此。这是方法和输出,任何人都可以帮助我吗?

def makePlayFair(key, alpha):
box = []
#join the key and alphabet string so that you only have to itterate over one string
keyAlpha = ""
keyAlpha = keyAlpha.join([key, alpha])
ind = 0
for lines in range(5):
    line = []
    while len(line) < 5:
        if isIn(keyAlpha[ind], box) or isIn(keyAlpha[ind], line):
            print(isIn(keyAlpha[ind],box))
            ind += 1
            continue
        else:
            line.append(keyAlpha[ind])
            ind += 1
    box.append(line)
return box

def isIn(item, block):
    there = None
    for each_item in block:

        if type(each_item) == type([]):
            for nested_item in each_item:
                if item == nested_item:
                    there = True
                    break
                else:
                    there = False
        else:       
            if item == each_item:
                there = True
                break
            else:
                there = False
    return there

>>> makePlayFair("hello", alphabet) #alphabet is a string with all the letters in it

> `[['h', 'e', 'l', 'o', 'a'], ['b', 'c', 'd', 'f', 'g'], ['h', 'i', 'j', 'k', 'l'], ['m', 'n', 'o', 'p', 'q'], ['r', 's', 't', 'u', 'v']]`

提前感谢您的帮助!

欢呼,布拉德

3 个答案:

答案 0 :(得分:1)

您的问题出在isIn:

你的break语句只会突破内部的for循环。然后代码继续迭代第二个for循环。这意味着只考虑最后一个。您必须确保退出两个循环才能使其正常工作。

通过执行以下操作可以使整个过程更简单:

def makePlayFair(key, alpha):


    letters = []
    for letter in key + alpha:
        if letter not in letters:
            letters.append(letter)

    box = []
    for line_number in range(5):
        box.append( letters[line_number * 5: (line_number+1) * 5])

答案 1 :(得分:1)

首先制作字母列表,然后将它们分解为5x5网格:

def takeNatATime(n, seq):
    its = [iter(seq)]*n
    return zip(*its)

def makePlayfair(s):
    keystr = []
    for c in s + "abcdefghijklmnopqrstuvwxyz":
        if c not in keystr:
            keystr.append(c)
    return list(takeNatATime(5, keystr))

print makePlayfair("hello")

打印:

[('h', 'e', 'l', 'o', 'a'), ('b', 'c', 'd', 'f', 'g'), ('i', 'j', 'k', 'm', 'n'), ('p', 'q', 'r', 's', 't'), ('u', 'v', 'w', 'x', 'y')]

答案 2 :(得分:0)

这是我的尝试:

#!/usr/bin/env python
from string import ascii_uppercase
import re

def boxify(key):
    cipher = [] 
    key = re.sub('[^A-Z]', '', key.upper())[:25]

    for i in range(max(25 - len(key), 0)):
            for letter in ascii_uppercase:
                if letter not in key:
                    key += letter
                    break

    for i in range(0, 25, 5):
        cipher.append(list(key[i:i+5]))

    return cipher


if __name__ == "__main__":
    print boxify("This is more than twenty-five letters, i'm afraid.")
    print boxify("But this isn't!")