MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / decode

Function decode

ciphers/playfair_cipher.py:121–150  ·  view source on GitHub ↗

Decode the input string using the provided key. >>> decode("BMZFAZRZDH", "HAZARD") 'FIREHAZARD' >>> decode("HNBWBPQT", "AUTOMOBILE") 'DRIVINGX' >>> decode("SLYSSAQS", "CASTLE") 'ATXTACKX'

(ciphertext: str, key: str)

Source from the content-addressed store, hash-verified

119
120
121def 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
153if __name__ == "__main__":

Callers 1

playfair_cipher.pyFile · 0.70

Calls 2

chunkerFunction · 0.85
generate_tableFunction · 0.70

Tested by

no test coverage detected