Returns a cipher map given a keyword. :param key: keyword to use :return: dictionary cipher map
(key: str)
| 18 | |
| 19 | |
| 20 | def create_cipher_map(key: str) -> dict[str, str]: |
| 21 | """ |
| 22 | Returns a cipher map given a keyword. |
| 23 | |
| 24 | :param key: keyword to use |
| 25 | :return: dictionary cipher map |
| 26 | """ |
| 27 | # Create a list of the letters in the alphabet |
| 28 | alphabet = [chr(i + 65) for i in range(26)] |
| 29 | # Remove duplicate characters from key |
| 30 | key = remove_duplicates(key.upper()) |
| 31 | offset = len(key) |
| 32 | # First fill cipher with key characters |
| 33 | cipher_alphabet = {alphabet[i]: char for i, char in enumerate(key)} |
| 34 | # Then map remaining characters in alphabet to |
| 35 | # the alphabet from the beginning |
| 36 | for i in range(len(cipher_alphabet), 26): |
| 37 | char = alphabet[i - offset] |
| 38 | # Ensure we are not mapping letters to letters previously mapped |
| 39 | while char in key: |
| 40 | offset -= 1 |
| 41 | char = alphabet[i - offset] |
| 42 | cipher_alphabet[alphabet[i]] = char |
| 43 | return cipher_alphabet |
| 44 | |
| 45 | |
| 46 | def encipher(message: str, cipher_map: dict[str, str]) -> str: |
no test coverage detected