Skip to content

Commit 2ec3750

Browse files
create monoalphabetic cipher (TheAlgorithms#3449)
* create monoalphabetic cipher * update file * update file * update file * update file * update file * update after testing flake8 on this code * update file * update file * update file * update file * update file * update file
1 parent 3bbec1d commit 2ec3750

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

ciphers/mono_alphabetic_ciphers.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2+
3+
4+
def translate_message(key, message, mode):
5+
"""
6+
>>> translate_message("QWERTYUIOPASDFGHJKLZXCVBNM","Hello World","encrypt")
7+
'Pcssi Bidsm'
8+
"""
9+
chars_a = LETTERS if mode == "decrypt" else key
10+
chars_b = key if mode == "decrypt" else LETTERS
11+
translated = ""
12+
# loop through each symbol in the message
13+
for symbol in message:
14+
if symbol.upper() in chars_a:
15+
# encrypt/decrypt the symbol
16+
sym_index = chars_a.find(symbol.upper())
17+
if symbol.isupper():
18+
translated += chars_b[sym_index].upper()
19+
else:
20+
translated += chars_b[sym_index].lower()
21+
else:
22+
# symbol is not in LETTERS, just add it
23+
translated += symbol
24+
return translated
25+
26+
27+
def encrypt_message(key: str, message: str) -> str:
28+
"""
29+
>>> encrypt_message("QWERTYUIOPASDFGHJKLZXCVBNM", "Hello World")
30+
'Pcssi Bidsm'
31+
"""
32+
return translate_message(key, message, "encrypt")
33+
34+
35+
def decrypt_message(key: str, message: str) -> str:
36+
"""
37+
>>> decrypt_message("QWERTYUIOPASDFGHJKLZXCVBNM", "Hello World")
38+
'Itssg Vgksr'
39+
"""
40+
return translate_message(key, message, "decrypt")
41+
42+
43+
def main():
44+
message = "Hello World"
45+
key = "QWERTYUIOPASDFGHJKLZXCVBNM"
46+
mode = "decrypt" # set to 'encrypt' or 'decrypt'
47+
48+
if mode == "encrypt":
49+
translated = encrypt_message(key, message)
50+
elif mode == "decrypt":
51+
translated = decrypt_message(key, message)
52+
print(f"Using the key {key}, the {mode}ed message is: {translated}")
53+
54+
55+
if __name__ == "__main__":
56+
import doctest
57+
58+
doctest.testmod()
59+
main()

0 commit comments

Comments
 (0)