@@ -42,7 +42,6 @@ def index_of_coincidence(frequencies: dict, length: int) -> float:
42
42
of times it appears in the text as a percentage}
43
43
:param length: the length of the text
44
44
:return: the index of coincidence
45
- >>> index_of_coincidence({'A':1,'D':2,'E':3,'F':1,'H':1,'L': 2,'N':1,'T':1,'W':1}, 13) 0.0641025641025641
46
45
"""
47
46
index = 0.0
48
47
for value in frequencies .values ():
@@ -60,18 +59,20 @@ def calculate_indexes_of_coincidence(ciphertext: str, step: int) -> list:
60
59
:param step: the step when traversing through the cipher
61
60
:return: a list with the indexes of coincidence
62
61
"""
63
- indexes_of_coincidence = list ()
62
+ indexes_of_coincidence = []
64
63
length = len (ciphertext )
65
64
66
65
# for every starting point in [0, step)
67
66
for j in range (step ):
68
- frequencies = dict [str , int ]
67
+ frequencies : dict [str , int ] = {}
69
68
c = 0
70
69
for i in range (0 + j , length , step ):
71
70
c += 1
72
71
try : # in case the frequencies dictionary does not already have
73
72
# this key
74
- frequencies [ciphertext [i ]] += 1
73
+ letter = ciphertext [i ]
74
+ temp = frequencies [letter ]
75
+ frequencies [ciphertext [i ]] = temp + 1
75
76
except KeyError :
76
77
frequencies [ciphertext [i ]] = 1
77
78
if c > 1 : # to avoid division by zero in the index_of_coincidence
@@ -94,7 +95,7 @@ def friedman_method(ciphertext: str, max_keylength: int | None = None) -> int:
94
95
should check, if None then it defaults to the length of the cipher
95
96
:return: the length of the key
96
97
"""
97
- # sets the default value of MAX_KEYLENGTH
98
+ # sets the default value of max_keylength
98
99
if max_keylength is None :
99
100
max_keylength = len (ciphertext )
100
101
@@ -176,7 +177,12 @@ def find_key(ciphertext: str, key_length: int) -> str:
176
177
) # shift the list cyclically one position to the left
177
178
key .append (max1 [1 ])
178
179
179
- return "" .join (chr (num + a ) for num in key ) # return the key as a string
180
+ key_as_list_of_letters = []
181
+ for num in key :
182
+ if num is not None :
183
+ key_as_list_of_letters .append (chr (num + a ))
184
+
185
+ return "" .join (key_as_list_of_letters ) # return the key as a string
180
186
181
187
182
188
def find_key_from_vigenere_cipher (ciphertext : str ) -> str :
@@ -185,7 +191,7 @@ def find_key_from_vigenere_cipher(ciphertext: str) -> str:
185
191
ciphertext. It uses Friedman's method and statistical analysis. It works
186
192
best for large pieces of text written in the english language.
187
193
"""
188
- clean_ciphertext_list = list ()
194
+ clean_ciphertext_list = []
189
195
for symbol in ciphertext .upper ():
190
196
if symbol in LETTERS :
191
197
clean_ciphertext_list .append (symbol )
0 commit comments