Написать программу, реализующей полибианский квадрат — Python(Питон)

#!/usr/bin/env python
 
# Polybius square cryptography
 
matrix = [['a','b','c','d','e'],
         ['f','g','h','i','k'],
         ['l','m','n','o','p'],
         ['q','r','s','t','u'],
         ['v','w','x','y','z']];
 
matrixHeight = len(matrix);
matrixWidth = len(matrix[0]);
 
def getCryptoChar(char, cipher = True):
    for indexHeight in range(0, matrixHeight):
        for indexWidth in range(0, matrixWidth):
            if char == matrix[indexHeight][indexWidth]:
                if (cipher == True):
                    return matrix[(indexHeight + 1) % matrixHeight][indexWidth];
                else:
                    return matrix[(indexHeight - 1) % matrixHeight][indexWidth];
    return char; # return input character, if not found
    pass;
 
 
def encryption(message):
    newMessage= "";
    for messageIndex in range(0, len(message)):
        newMessage += getCryptoChar(message[messageIndex]);
    return newMessage;
 
def decryption(message):
    newMessage= "";
    for messageIndex in range(0, len(message)):
        newMessage += getCryptoChar(message[messageIndex], False);
    return newMessage;
 
 
 
def main():
    message = "hello world!";
    print "Message is: " + message;
 
    cypherMessage = encryption(message);
    print "cypher message is: " + cypherMessage;
 
    decypherMessage = decryption(cypherMessage);
    print "decypher message is: " + decypherMessage;
    pass;
 
if __name__ == "__main__":
    main();
#!/usr/local/bin/python
# coding: utf-8
__author__ = 'spouk'
 
import string
 
class Polibi:
    def __init__(self, language='en'):
        self.languages = language
        self.step = 8
        self.matrix = []
        self.stroka = string.ascii_letters
        self.fix = '-'
        self.crypto = ''
        self.decrypto = ''
        self.origin = None
 
    def make_matrix(self, language='en'):
        """формируем матрицу из англоязычных символов, аргумент en как пример для возможности расширения"""
        if self.languages == 'en':
            for line in [self.stroka[index: index + self.step] for index in range(0, len(self.stroka), self.step)]:
                if len(line) < self.step:
                    line = ''.join([line, self.fix * (self.step - len(line))])
                self.matrix.append(list(line))
 
            if len(self.matrix) < self.step * self.step:
                self.matrix.append([self.fix for x in range(0, self.step)])
 
    def __getsym(self, sym, type_operation='code'):
        """проводим получение данных по символу, возвращает букварь где ключ - символ замены, значение ключа позиция в матрице"""
        assert type_operation in ['code', 'decode'], '==>Wrong type operation {}'.format(self.__class__)
        pos_sym = {}
        for index in range(self.step):
            if sym in self.matrix[index]:
                sym_index_line = self.matrix[index].index(sym)
                sym_index_row = index
 
                if type_operation == 'code':
                    if index in [5, 6] and self.matrix[index + 1][sym_index_line] == self.fix or index == 7:
                        sym_index_row = 0
                if type_operation == 'decode':
                    if not index:
                        srez = [self.matrix[x][sym_index_line] for x in range(self.step) if self.matrix[x][sym_index_line] != self.fix]
                        sym_index_row = srez.index(srez[-1:][0])
 
                pos_sym[self.matrix[sym_index_row][sym_index_line]] = (sym_index_row, sym_index_line)
        return pos_sym
 
    def code_str_method_1(self, stroka):
        """шифруем, хехе, строку"""
        self.make_matrix(language=self.languages)
        self.__view_matrix()
        self.origin = stroka
 
        for value in [self.__getsym(sym) for sym in stroka]:
            for sym, pos in value.items():
                    self.crypto= ''.join([self.crypto, sym])
 
    def decode_str_method_1(self, stroka):
        """дешифруем строку self.crypto как пример"""
        self.make_matrix(language=self.languages)
 
        for value in [self.__getsym(sym, type_operation='decode') for sym in stroka]:
            for sym, pos in value.items():
                self.decrypto= ''.join([self.decrypto, sym])
 
    def __view_matrix(self):
        """смотрим матрицу"""
        for n, x in enumerate(self.matrix, 0):
            print "{:<5}{:<10}".format(n, x)
 
    @property
    def view_last_result(self):
        """смотрим результат последней операции по строке"""
        print "Origin==>  {}\nCrypto==>  {}\nDecrypto==> {}".format(self.origin, self.crypto, self.decrypto)
 
 
c=Polibi()
c.code_str_method_1('SOMETEXT')
c.decode_str_method_1(c.crypto)
c.view_last_result
0    ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
1    ['i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
2    ['q', 'r', 's', 't', 'u', 'v', 'w', 'x']
3    ['y', 'z', 'A', 'B', 'C', 'D', 'E', 'F']
4    ['G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']
5    ['O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V']
6    ['W', 'X', 'Y', 'Z', '-', '-', '-', '-']
7    ['-', '-', '-', '-', '-', '-', '-', '-']
Origin==>  SOMETEXT
Crypto==>  eOMEfEbf
Decrypto==> SOMETEXT
word = 'Cryptography'   #'Криптография'   #'SOMETEXT'
 
class Polibi:
    def __init__(self):
        if 65 <= min([ord(i) for i in word]) <= 122:
            self.b = [['A', 'B', 'C', 'D', 'E'],
                      ['F', 'G', 'H', 'I', 'K'],
                      ['L', 'M', 'N', 'O', 'P'],
                      ['Q', 'R', 'S', 'T', 'U'],
                      ['V', 'W', 'X', 'Y', 'Z']]
        elif 1040 <= min([ord(i) for i in word]) <= 1103:
            self.b = [['А', 'Б', 'В', 'Г', 'Д', 'Е'],
                      ['Ё', 'Ж', 'З', 'И', 'Й', 'К'],
                      ['Л', 'М', 'Н', 'О', 'П', 'Р'],
                      ['С', 'Т', 'У', 'Ф', 'Х', 'Ц'],
                      ['Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь'],
                      ['Э', 'Ю', 'Я', '-', '+', '=']]
        self.matrixHeight, self.matrixWidth = len(self.b), len(self.b[0])
        self.coor_horizontal, self.coor_vertical = [], []
        self.answer = []
        self.len = len(word)
        self.non_repeat_word = str()
        for i in range(len(word)):
            if not word[i] in word[0:i]:
                self.non_repeat_word += (word[i])
 
    # region Выполнение Метода 1
    def method_1(self):
        for i in range(len(self.coor_horizontal)):
            if self.coor_vertical[i] + 1 <= self.matrixHeight:
                self.coor_vertical[i] += 1
            else:
                self.coor_vertical[i] = 1
            self.answer.append(
                              self.b
                              [self.coor_vertical[i] - 1]
                              [self.coor_horizontal[i] - 1]
                              )
        return ''.join(self.answer)
 
    def enumeration_method_1(self, b, symbol):
        flag = False
        for j in range(self.matrixHeight):
            for i in range(self.matrixWidth):
                if b[i][j].count(symbol.upper()) == 1:
                    self.coor_horizontal.append(j + 1)
                    self.coor_vertical.append(i + 1)
                    flag = True
                    break
            if flag:
                flag = False
                break
        return (self.coor_vertical, self.coor_horizontal)
 
# region Выполнение Метода 2
    def method_2(self):
        self.answer, self.coor_vertical, self.coor_horizontal = [], [], []
        for k in range(len(word)):
            symbol = word[k:len(word) - (len(word) - 1 - k)]
            self.enumeration_method_1(self.b, symbol)
        self.change_self_b()
        return self.method_1()
        print(end='')
 
    def enumeration_method_2(self, b, symbol):
        flag = False
        for j in range(self.matrixHeight):
            for i in range(self.matrixWidth):
                if b[i][j].count(symbol.upper()) == 1:
                    self.coor_horizontal.append(j + 1)
                    self.coor_vertical.append(i + 1)
                    flag = True
                    break
            if flag:
                flag = False
                break
 
    def change_self_b(self):
        b2 = ' '.join(self.non_repeat_word).split()
        for u in range(len(self.b)):
            b2.extend(self.b[u])
        b2 = ''.join(b2)
 
        b3 = str()
        for i in range(len(b2)):
            if not b2[i] in b2[0:i]:
                b3 += (b2[i])
        b2 = []
        loc = 0
        for i in range(len(self.b)):
            for j in range(len(self.b[0])):
                if j == len(self.b[0]) - 1:
                    loc += 1
            b2.extend([' '.join(b3[(j + 1) * (loc - 1):(j + 1) * loc]).split()])
 
        self.b = b2
 
#region Пересчет координат
    def coordinate(self):
        for k in range(len(word)):
            symbol = word[k:len(word) - (len(word) - 1 - k)]
            if symbol.lower() != 'j':
                self.coor_vertical, self.coor_horizontal = self.enumeration_method_1(self.b, symbol)
            else:
                self.coor_vertical, self.coor_horizontal = self.enumeration_method_1(self.b, 'i')
 
 
bla = Polibi()
bla.coordinate()
print('Введенное слово                {}\nЗашифованое слово Методом 1    {}\nЗашифованое слово Методом 2    {}'.format(word.upper(), bla.method_1().upper(), bla.method_2().upper()))

Leave a Comment