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

Function try_key

project_euler/problem_059/sol1.py:44–66  ·  view source on GitHub ↗

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, ...])

Source from the content-addressed store, hash-verified

42
43
44def 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
69def filter_valid_chars(ciphertext: list[int]) -> list[str]:

Callers 1

filter_valid_charsFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected