For keyword: hello H E L O A B C D F G I J K M N P Q R S T U V W X Y Z and map vertically >>> mixed_keyword("college", "UNIVERSITY", True) # doctest: +NORMALIZE_WHITESPACE {'A': 'C', 'B': 'A', 'C': 'I', 'D': 'P', 'E': 'U', 'F': 'Z', 'G': 'O', 'H': 'B',
(
keyword: str, plaintext: str, verbose: bool = False, alphabet: str = ascii_uppercase
)
| 2 | |
| 3 | |
| 4 | def mixed_keyword( |
| 5 | keyword: str, plaintext: str, verbose: bool = False, alphabet: str = ascii_uppercase |
| 6 | ) -> str: |
| 7 | """ |
| 8 | For keyword: hello |
| 9 | |
| 10 | H E L O |
| 11 | A B C D |
| 12 | F G I J |
| 13 | K M N P |
| 14 | Q R S T |
| 15 | U V W X |
| 16 | Y Z |
| 17 | and map vertically |
| 18 | |
| 19 | >>> mixed_keyword("college", "UNIVERSITY", True) # doctest: +NORMALIZE_WHITESPACE |
| 20 | {'A': 'C', 'B': 'A', 'C': 'I', 'D': 'P', 'E': 'U', 'F': 'Z', 'G': 'O', 'H': 'B', |
| 21 | 'I': 'J', 'J': 'Q', 'K': 'V', 'L': 'L', 'M': 'D', 'N': 'K', 'O': 'R', 'P': 'W', |
| 22 | 'Q': 'E', 'R': 'F', 'S': 'M', 'T': 'S', 'U': 'X', 'V': 'G', 'W': 'H', 'X': 'N', |
| 23 | 'Y': 'T', 'Z': 'Y'} |
| 24 | 'XKJGUFMJST' |
| 25 | |
| 26 | >>> mixed_keyword("college", "UNIVERSITY", False) # doctest: +NORMALIZE_WHITESPACE |
| 27 | 'XKJGUFMJST' |
| 28 | """ |
| 29 | keyword = keyword.upper() |
| 30 | plaintext = plaintext.upper() |
| 31 | alphabet_set = set(alphabet) |
| 32 | |
| 33 | # create a list of unique characters in the keyword - their order matters |
| 34 | # it determines how we will map plaintext characters to the ciphertext |
| 35 | unique_chars = [] |
| 36 | for char in keyword: |
| 37 | if char in alphabet_set and char not in unique_chars: |
| 38 | unique_chars.append(char) |
| 39 | # the number of those unique characters will determine the number of rows |
| 40 | num_unique_chars_in_keyword = len(unique_chars) |
| 41 | |
| 42 | # create a shifted version of the alphabet |
| 43 | shifted_alphabet = unique_chars + [ |
| 44 | char for char in alphabet if char not in unique_chars |
| 45 | ] |
| 46 | |
| 47 | # create a modified alphabet by splitting the shifted alphabet into rows |
| 48 | modified_alphabet = [ |
| 49 | shifted_alphabet[k : k + num_unique_chars_in_keyword] |
| 50 | for k in range(0, 26, num_unique_chars_in_keyword) |
| 51 | ] |
| 52 | |
| 53 | # map the alphabet characters to the modified alphabet characters |
| 54 | # going 'vertically' through the modified alphabet - consider columns first |
| 55 | mapping = {} |
| 56 | letter_index = 0 |
| 57 | for column in range(num_unique_chars_in_keyword): |
| 58 | for row in modified_alphabet: |
| 59 | # if current row (the last one) is too short, break out of loop |
| 60 | if len(row) <= column: |
| 61 | break |
no test coverage detected