Skip to content

Commit fa75ee4

Browse files
DjaouadNMdhruvmanila
authored andcommitted
Update ciphers/caesar_cipher.py with type hints (TheAlgorithms#3860)
* Update caesar_cipher.py improved for conciseness and readability * Add type hints Co-authored-by: Dhruv Manilawala <[email protected]>
1 parent fa33c98 commit fa75ee4

File tree

1 file changed

+8
-24
lines changed

1 file changed

+8
-24
lines changed

ciphers/caesar_cipher.py

+8-24
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
from string import ascii_letters
2+
from typing import Dict, Optional
23

34

4-
def encrypt(input_string: str, key: int, alphabet=None) -> str:
5+
def encrypt(input_string: str, key: int, alphabet: Optional[str] = None) -> str:
56
"""
67
encrypt
78
=======
@@ -79,7 +80,7 @@ def encrypt(input_string: str, key: int, alphabet=None) -> str:
7980
return result
8081

8182

82-
def decrypt(input_string: str, key: int, alphabet=None) -> str:
83+
def decrypt(input_string: str, key: int, alphabet: Optional[str] = None) -> str:
8384
"""
8485
decrypt
8586
=======
@@ -144,7 +145,7 @@ def decrypt(input_string: str, key: int, alphabet=None) -> str:
144145
return encrypt(input_string, key, alphabet)
145146

146147

147-
def brute_force(input_string: str, alphabet=None) -> dict:
148+
def brute_force(input_string: str, alphabet: Optional[str] = None) -> Dict[int, str]:
148149
"""
149150
brute_force
150151
===========
@@ -193,31 +194,18 @@ def brute_force(input_string: str, alphabet=None) -> dict:
193194
# Set default alphabet to lower and upper case english chars
194195
alpha = alphabet or ascii_letters
195196

196-
# The key during testing (will increase)
197-
key = 1
198-
199-
# The encoded result
200-
result = ""
201-
202197
# To store data on all the combinations
203198
brute_force_data = {}
204199

205200
# Cycle through each combination
206-
while key <= len(alpha):
207-
# Decrypt the message
208-
result = decrypt(input_string, key, alpha)
209-
210-
# Update the data
211-
brute_force_data[key] = result
212-
213-
# Reset result and increase the key
214-
result = ""
215-
key += 1
201+
for key in range(1, len(alpha) + 1):
202+
# Decrypt the message and store the result in the data
203+
brute_force_data[key] = decrypt(input_string, key, alpha)
216204

217205
return brute_force_data
218206

219207

220-
def main():
208+
if __name__ == "__main__":
221209
while True:
222210
print(f'\n{"-" * 10}\n Menu\n{"-" * 10}')
223211
print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n")
@@ -248,7 +236,3 @@ def main():
248236
elif choice == "4":
249237
print("Goodbye.")
250238
break
251-
252-
253-
if __name__ == "__main__":
254-
main()

0 commit comments

Comments
 (0)