from array import *

def polybeEncryption(plaintext):
    plaintext  = plaintext.upper();
    print("The plaintext is: ", plaintext);
    ciphertext = "";
    size       = len(POLYBE);
    founded = False;
    for letter in plaintext:
        for i in range(0,size):
            for j in range(0,size):
                if(letter == POLYBE[i][j]):
                    ciphertext+= str(i)+ str(j);
                    founded = True;
                    break;
            if(founded):
                founded= False;
                break;
        if(letter == ' '):
            ciphertext+= ' ';
           
    return ciphertext;
    
def polybeDecryption(ciphertext):
    plaintext="";
    i = 0;
    while(i < len(ciphertext)):
        if(ciphertext[i] == ' ' or ciphertext[i+1] == ' '):
            plaintext = plaintext + ' ';
            print();
            i = i + 1;
            continue;

        plaintext = plaintext + POLYBE[int(ciphertext[i])][int(ciphertext[i+1])];
        i  = i + 2;
    return plaintext;

#the key in polybe square is crows
ALPHABET = 'ABCDEFGHIKLMNOPQRSTUVWXYZ'; 
POLYBE   = [['0','0','0','0','0'], ['0','0','0','0','0'], ['0','0','0','0','0'], ['0','0','0','0','0'], ['0','0','0','0','0']]
plaintext = input("input the plaintext you want to encrypt: ");
key       = input("input the key without repeating letters: ");
key       = key.upper();
key       = key.replace('J','I');
for c in key:
    for letter in ALPHABET:
        if(c == letter):
            ALPHABET = ALPHABET.replace(letter,'');
            break;
    
ALPHABET = key + ALPHABET;

k = 0;
for i in range(0,5):
    for j in range(0,5):
        POLYBE[i][j] = ALPHABET[k];
        k += 1;
        print(POLYBE[i][j], end=' ');
    print();

ciphertext = polybeEncryption(plaintext);
print(ciphertext);
plaintext  = polybeDecryption(ciphertext);
print("Try to combine both to get plaintext: ");
print("The plaintext assuming 22=I: ", plaintext);
print("The plaintext assuming 22=J: ", plaintext.replace('I','J')); 
