Given an encrypted message and a possible 3-character key, decrypt the message. If the decrypted message contains a invalid character, i.e. not an ASCII letter, a digit, punctuation or whitespace, then we know the key is incorrect, so return None. >>> try_key([0, 17, 20, 4, 27],
(ciphertext: list[int], key: tuple[int, ...])
| 42 | |
| 43 | |
| 44 | def try_key(ciphertext: list[int], key: tuple[int, ...]) -> str | None: |
| 45 | """ |
| 46 | Given an encrypted message and a possible 3-character key, decrypt the message. |
| 47 | If the decrypted message contains a invalid character, i.e. not an ASCII letter, |
| 48 | a digit, punctuation or whitespace, then we know the key is incorrect, so return |
| 49 | None. |
| 50 | >>> try_key([0, 17, 20, 4, 27], (104, 116, 120)) |
| 51 | 'hello' |
| 52 | >>> try_key([68, 10, 300, 4, 27], (104, 116, 120)) is None |
| 53 | True |
| 54 | """ |
| 55 | decoded: str = "" |
| 56 | keychar: int |
| 57 | cipherchar: int |
| 58 | decodedchar: int |
| 59 | |
| 60 | for keychar, cipherchar in zip(cycle(key), ciphertext): |
| 61 | decodedchar = cipherchar ^ keychar |
| 62 | if decodedchar not in VALID_INTS: |
| 63 | return None |
| 64 | decoded += chr(decodedchar) |
| 65 | |
| 66 | return decoded |
| 67 | |
| 68 | |
| 69 | def filter_valid_chars(ciphertext: list[int]) -> list[str]: |
no outgoing calls
no test coverage detected