Python编码两个字母

2024-04-26 01:19:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个python playfair密码,但在创建过程中遇到了一些问题。我有一张五乘五的桌子,上面有以下信息:

 [['A', 'B', 'C', 'D', 'E'],
 ['F', 'G', 'H', 'I', 'Y'],
 ['K', 'L', 'M', 'N', 'O'],
 ['P', 'Q', 'R', 'S', 'T'],
 ['U', 'V', 'W', 'X', 'Z']]

我应该一次加密两封信。当给定输入encrypt(B,N)时,结果输出应该是DL。输入中的第一个字母应该返回与B在同一行中的字母,但它有N列。我希望有人能为我解释一种实现这一点的方法。你知道吗

在这里友好用户的帮助下,一些代码是这样的:

def find_index(letter, table):
    for i,li in enumerate(table):
        try:
            j=li.index(letter)
            return i,j
        except ValueError:
            pass    

    raise ValueError("'{}' not in matrix".format(letter))
print "Row:Column"
print find_index('I', table)  


def encode(a, b):
    if a == b:
        print "ERROR: letters to encode_pair must be distinct"
    print find_index (a,table)
    print find_index (b, table)

Tags: in密码index过程def字母tableli
3条回答

您需要保存find_index(a,table)和find_index(a,table)的返回,如果我理解正确的话,这就是您需要实现的代码类型

def encode(a, b):
    if a == b:
        print "ERROR: letters to encode_pair must be distinct"
    print find_index (a,table)
    print find_index (b, table) 
    index_a= find_index (a,table)
    index_b = find_index (a,table)
    new_a_index = [index_a[0], index_b[1]]
    new_b_index = [index_b[0], index_a[1]]
    new_a = table[new_a_index]
    new_b = table[new_b_index]

最后的步骤可以一步完成,但我试图弄清楚,以确保你明白我在做什么,并纠正我,如果我误解了

那很有趣。。。谢谢。你知道吗

In [2]:



class Encoder(object):
    m = [['A', 'B', 'C', 'D', 'E'],
     ['F', 'G', 'H', 'I', 'Y'],
     ['K', 'L', 'M', 'N', 'O'],
     ['P', 'Q', 'R', 'S', 'T'],
     ['U', 'V', 'W', 'X', 'Z']]    

    def encode(self, first, second):
        first_row_idx, first_col_idx = self.get_rowcol(first)
        second_row_idx, second_col_idx = self.get_rowcol(second)        
        encoded_first = self.m[first_row_idx][second_col_idx]
        encoded_second = self.m[second_row_idx][first_col_idx]
        return encoded_first, encoded_second

    def get_rowcol(self, letter):
        letter = letter.upper()
        for row_idx, row in enumerate(self.m):
            for col_idx, col_letter in enumerate(row):
                if col_letter == letter:
                    return row_idx, col_idx
        raise ValueError("({}) not found in matrix!".format(letter))


e = Encoder()
e.encode("B", "N")

Out[2]:
('D', 'L')

可以使用python中的ord()获取char的ASCII值。你知道吗

s='A'

更改\u s=chr(ord(s)+2)

所以结果出来的是变化

相关问题 更多 >