Decode the input string using the provided key. >>> decode("BMZFAZRZDH", "HAZARD") 'FIREHAZARD' >>> decode("HNBWBPQT", "AUTOMOBILE") 'DRIVINGX' >>> decode("SLYSSAQS", "CASTLE") 'ATXTACKX'
(ciphertext: str, key: str)
| 119 | |
| 120 | |
| 121 | def decode(ciphertext: str, key: str) -> str: |
| 122 | """ |
| 123 | Decode the input string using the provided key. |
| 124 | |
| 125 | >>> decode("BMZFAZRZDH", "HAZARD") |
| 126 | 'FIREHAZARD' |
| 127 | >>> decode("HNBWBPQT", "AUTOMOBILE") |
| 128 | 'DRIVINGX' |
| 129 | >>> decode("SLYSSAQS", "CASTLE") |
| 130 | 'ATXTACKX' |
| 131 | """ |
| 132 | |
| 133 | table = generate_table(key) |
| 134 | plaintext = "" |
| 135 | |
| 136 | for char1, char2 in chunker(ciphertext, 2): |
| 137 | row1, col1 = divmod(table.index(char1), 5) |
| 138 | row2, col2 = divmod(table.index(char2), 5) |
| 139 | |
| 140 | if row1 == row2: |
| 141 | plaintext += table[row1 * 5 + (col1 - 1) % 5] |
| 142 | plaintext += table[row2 * 5 + (col2 - 1) % 5] |
| 143 | elif col1 == col2: |
| 144 | plaintext += table[((row1 - 1) % 5) * 5 + col1] |
| 145 | plaintext += table[((row2 - 1) % 5) * 5 + col2] |
| 146 | else: # rectangle |
| 147 | plaintext += table[row1 * 5 + col2] |
| 148 | plaintext += table[row2 * 5 + col1] |
| 149 | |
| 150 | return plaintext |
| 151 | |
| 152 | |
| 153 | if __name__ == "__main__": |
no test coverage detected