简体   繁体   English

Python:使用关键字和字母表的其余部分填充5x5字符矩阵

[英]Python: Filling a 5x5 char matrix with a keyword and the rest of the alphabet

Programming the Playfair cipher in case anyone has heard about it. 编程Playfair密码以防任何人听说过它。

I ask the user to input a keyword (Example: bookkeeping), I then remove repeated letters (Example: bokeping). 我要求用户输入一个关键字(例如:簿记),然后删除重复的字母(例如:bokeping)。 I need to create a 5x5 matrix and fill it with chars but declaring 我需要创建一个5x5矩阵并用chars填充它但声明

    matrix = [][]

is marked as "Invalid syntax". 被标记为“语法无效”。 I then need to fill up the matrix with the unique characters and then the rest of the letters of the alphabet (after removing the unique keyword characters) to end up with (i and j are placed on the same position): 然后我需要用唯一的字符填充矩阵,然后填写字母表的其余字母(在删除唯一的关键字字符后)以结束(i和j放在相同的位置):

    [b, o, k, e, p]
    [ij, n, g, a, c]
    [d, f, h, l, m]
    [q, r, s, t, u]
    [v, w, x, y, z]

Question 1: How do I properly declare the matrix to use it for this? 问题1:如何正确声明矩阵才能将其用于此目的?

Question 2: How do I fill up the matrix with the keyword and then the rest of the characters? 问题2:如何使用关键字填充矩阵,然后填写其余字符?

Other than that, any suggestions? 除此之外,还有什么建议吗?

Thank you for your help. 谢谢您的帮助。

Python has groupby : Python有groupby

>>> from itertools import groupby
>>> s = 'aabbccc'
>>> [k for k, g in groupby(s)]
['a', 'b', 'c']

Question 1: How do I properly declare the matrix to use it for this? 问题1:如何正确声明矩阵才能将其用于此目的?

A matrix is a list of lists. 矩阵是列表的列表。 You declare it like this: m = [[x,y] for x in range(3) for y in range(3)] 你声明它是这样的: m = [[x,y] for x in range(3) for y in range(3)]

You can create a matrix with a nested list structure. 您可以使用嵌套列表结构创建矩阵。

For example the following code defines a 3x3 matrix. 例如,以下代码定义了3x3矩阵。

M = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

M[1]  # Row 2

[4, 5, 6]

M[1][2]  # Row 2, item 3

6

You can use a list comprehension to process the structure. 您可以使用列表推导来处理结构。

[row[1] for row in M]    # Column 2

[2, 5, 8]

For the purpose of the exercise you should just replace all j characters with i in both the pass phrase and cleartext, then you dont need to worry about the double character. 为了练习的目的,您应该在密码短语和明文中用i替换所有j字符,然后您不必担心双重字符。

Then to build the matrix you can do the following: 然后,要构建矩阵,您可以执行以下操作:

from itertools import chain

key = "bookkeeping".replace("j", "i")
alphabet = "abcdefghiklmnopqrstuvwxyz" # note no J

# dedup the list of characters
slots = []
for x in chain(key, alphabet):
  if not x in slots: slots.append(x)

# get our matrix using list slices
matrix = [ slots[i:i+5] for i in xrange(0, 25, 5) ]
print matrix

Result: 结果:

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

Hadn't come across playfair before - is a nice little algorithmic challenge! 以前没有遇到过playfair--这是一个很好的小算法挑战!

If you are paranoid about libraries like I am, then this is the solution of you. 如果你对我这样的图书馆感到偏执,那么这就是你的解决方案。

def raw_inp(msg):
    #This function makes sure the raw_input function is available in
    #both python 2.x or 3.x
    try:
        return raw_input(msg)
    except NameError:
        return input(msg)

def unique_array(arr):
    #This function removes duplicates of array values
    check = []
    for i in arr:
        if i not in check:
            check.append(i)
    return check

def form(key):
    key = key.lower() #make sure key is all lowercase
    alpha = []
    key_arr = [] #Convert key to array
    key_arr.extend(key)#Convert key to array
    key = key_arr #Convert key to array
    alpha.extend("abcdefghijklmnopqrstuvwxyz") #Convert alphabet to array
    arr = (key+alpha)
    new_arr = []
    finish_arr = []
    return_arr = []
    arr = unique_array(arr) #Removes any duplicate letters before we start
    for i in arr:
        if i in alpha: #if the character is in the alphabet
            if i == "i" or i == "j": #if it is i or j, place it together
                new_arr.append("ij")
            else:
                new_arr.append(i) #or else place the letter in the array
    x = 0 #array index
    i = 0
    new_arr = unique_array(new_arr)
    while x < 5:
        finish_arr.append([])
        finish_arr[x] = []
        y = 0
        while y < 5:
            finish_arr[x].append(new_arr[i])
            y += 1
            i += 1
        x += 1
    for i in finish_arr:
        return_arr.append(unique_array(i))
    return return_arr


key = raw_inp("Key: ") #get key

arr = (form(key)) #

for i in arr:
    print i

Sorry about the weird style. 抱歉奇怪的风格。 I programmed it in another way then switched to this way. 我以另一种方式编程,然后切换到这种方式。

This code was meant to be understandable, not short or efficient. 此代码是可以理解的,而不是简短或有效的。 Please comment if you don't understand something 如果您不明白,请发表评论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM