|
1 | 1 | #!/usr/bin/env python3 |
2 | 2 |
|
3 | | -from typing import Tuple |
| 3 | +from typing import Optional |
4 | 4 |
|
5 | 5 |
|
6 | 6 | def decrypt_caesar_with_chi_squared( |
7 | 7 | ciphertext: str, |
8 | | - cipher_alphabet: str = None, |
9 | | - frequencies_dict: str = None, |
| 8 | + cipher_alphabet: Optional[list[str]] = None, |
| 9 | + frequencies_dict: Optional[dict[str, float]] = None, |
10 | 10 | case_sensetive: bool = False, |
11 | | -) -> Tuple[int, float, str]: |
| 11 | +) -> tuple[int, float, str]: |
12 | 12 | """ |
13 | 13 | Basic Usage |
14 | 14 | =========== |
@@ -123,9 +123,9 @@ def decrypt_caesar_with_chi_squared( |
123 | 123 | AttributeError: 'int' object has no attribute 'lower' |
124 | 124 | """ |
125 | 125 | alphabet_letters = cipher_alphabet or [chr(i) for i in range(97, 123)] |
126 | | - frequencies_dict = frequencies_dict or {} |
127 | 126 |
|
128 | | - if frequencies_dict == {}: |
| 127 | + # If the argument is None or the user provided an empty dictionary |
| 128 | + if not frequencies_dict: |
129 | 129 | # Frequencies of letters in the english language (how much they show up) |
130 | 130 | frequencies = { |
131 | 131 | "a": 0.08497, |
@@ -163,7 +163,7 @@ def decrypt_caesar_with_chi_squared( |
163 | 163 | ciphertext = ciphertext.lower() |
164 | 164 |
|
165 | 165 | # Chi squared statistic values |
166 | | - chi_squared_statistic_values = {} |
| 166 | + chi_squared_statistic_values: dict[int, tuple[float, str]] = {} |
167 | 167 |
|
168 | 168 | # cycle through all of the shifts |
169 | 169 | for shift in range(len(alphabet_letters)): |
@@ -215,22 +215,22 @@ def decrypt_caesar_with_chi_squared( |
215 | 215 | chi_squared_statistic += chi_letter_value |
216 | 216 |
|
217 | 217 | # Add the data to the chi_squared_statistic_values dictionary |
218 | | - chi_squared_statistic_values[shift] = [ |
| 218 | + chi_squared_statistic_values[shift] = ( |
219 | 219 | chi_squared_statistic, |
220 | 220 | decrypted_with_shift, |
221 | | - ] |
| 221 | + ) |
222 | 222 |
|
223 | 223 | # Get the most likely cipher by finding the cipher with the smallest chi squared |
224 | 224 | # statistic |
225 | | - most_likely_cipher = min( |
| 225 | + most_likely_cipher: int = min( |
226 | 226 | chi_squared_statistic_values, key=chi_squared_statistic_values.get |
227 | | - ) |
| 227 | + ) # type: ignore # First argument to `min` is not optional |
228 | 228 |
|
229 | 229 | # Get all the data from the most likely cipher (key, decoded message) |
230 | | - most_likely_cipher_chi_squared_value = chi_squared_statistic_values[ |
231 | | - most_likely_cipher |
232 | | - ][0] |
233 | | - decoded_most_likely_cipher = chi_squared_statistic_values[most_likely_cipher][1] |
| 230 | + ( |
| 231 | + most_likely_cipher_chi_squared_value, |
| 232 | + decoded_most_likely_cipher, |
| 233 | + ) = chi_squared_statistic_values[most_likely_cipher] |
234 | 234 |
|
235 | 235 | # Return the data on the most likely shift |
236 | 236 | return ( |
|
0 commit comments