Encode the given plaintext using the Playfair cipher. Takes the plaintext and the key as input and returns the encoded string. >>> encode("Hello", "MONARCHY") 'CFSUPM' >>> encode("attack on the left flank", "EMERGENCY") 'DQZSBYFSDZFMFNLOHFDRSG' >>> encode("Sorry!", "SPE
(plaintext: str, key: str)
| 81 | |
| 82 | |
| 83 | def encode(plaintext: str, key: str) -> str: |
| 84 | """ |
| 85 | Encode the given plaintext using the Playfair cipher. |
| 86 | Takes the plaintext and the key as input and returns the encoded string. |
| 87 | |
| 88 | >>> encode("Hello", "MONARCHY") |
| 89 | 'CFSUPM' |
| 90 | >>> encode("attack on the left flank", "EMERGENCY") |
| 91 | 'DQZSBYFSDZFMFNLOHFDRSG' |
| 92 | >>> encode("Sorry!", "SPECIAL") |
| 93 | 'AVXETX' |
| 94 | >>> encode("Number 1", "NUMBER") |
| 95 | 'UMBENF' |
| 96 | >>> encode("Photosynthesis!", "THE SUN") |
| 97 | 'OEMHQHVCHESUKE' |
| 98 | """ |
| 99 | |
| 100 | table = generate_table(key) |
| 101 | plaintext = prepare_input(plaintext) |
| 102 | ciphertext = "" |
| 103 | |
| 104 | for char1, char2 in chunker(plaintext, 2): |
| 105 | row1, col1 = divmod(table.index(char1), 5) |
| 106 | row2, col2 = divmod(table.index(char2), 5) |
| 107 | |
| 108 | if row1 == row2: |
| 109 | ciphertext += table[row1 * 5 + (col1 + 1) % 5] |
| 110 | ciphertext += table[row2 * 5 + (col2 + 1) % 5] |
| 111 | elif col1 == col2: |
| 112 | ciphertext += table[((row1 + 1) % 5) * 5 + col1] |
| 113 | ciphertext += table[((row2 + 1) % 5) * 5 + col2] |
| 114 | else: # rectangle |
| 115 | ciphertext += table[row1 * 5 + col2] |
| 116 | ciphertext += table[row2 * 5 + col1] |
| 117 | |
| 118 | return ciphertext |
| 119 | |
| 120 | |
| 121 | def decode(ciphertext: str, key: str) -> str: |
no test coverage detected