Skip to content

Commit d41b9da

Browse files
authored
range(len()) is almost always a hint to use enumerate()
1 parent ed55cfc commit d41b9da

File tree

1 file changed

+23
-17
lines changed

1 file changed

+23
-17
lines changed

Diff for: ciphers/running_key_cipher.py

+23-17
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
"""
2+
https://en.wikipedia.org/wiki/Running_key_cipher
3+
"""
4+
5+
16
def running_key_encrypt(key: str, plaintext: str) -> str:
27
"""
38
Encrypts the plaintext using the Running Key Cipher.
@@ -10,12 +15,13 @@ def running_key_encrypt(key: str, plaintext: str) -> str:
1015
key = key.replace(" ", "").upper()
1116
key_length = len(key)
1217
ciphertext = []
18+
ord_a = ord("A")
1319

14-
for i in range(len(plaintext)):
15-
p = ord(plaintext[i]) - ord("A")
16-
k = ord(key[i % key_length]) - ord("A")
20+
for i, char in enumerate(plaintext):
21+
p = ord(char) - ord_a
22+
k = ord(key[i % key_length]) - ord_a
1723
c = (p + k) % 26
18-
ciphertext.append(chr(c + ord("A")))
24+
ciphertext.append(chr(c + ord_a))
1925

2026
return "".join(ciphertext)
2127

@@ -32,23 +38,22 @@ def running_key_decrypt(key: str, ciphertext: str) -> str:
3238
key = key.replace(" ", "").upper()
3339
key_length = len(key)
3440
plaintext = []
41+
ord_a = ord("A")
3542

36-
for i in range(len(ciphertext)):
37-
c = ord(ciphertext[i]) - ord("A")
38-
k = ord(key[i % key_length]) - ord("A")
43+
for i, char in enumerate(ciphertext):
44+
c = ord(char) - ord_a
45+
k = ord(key[i % key_length]) - ord_a
3946
p = (c - k) % 26
40-
plaintext.append(chr(p + ord("A")))
47+
plaintext.append(chr(p + ord_a))
4148

4249
return "".join(plaintext)
4350

4451

4552
def test_running_key_encrypt() -> None:
4653
"""
4754
>>> key = "How does the duck know that? said Victor"
48-
>>> plaintext = "DEFEND THIS"
49-
>>> ciphertext = running_key_encrypt(key, plaintext)
50-
>>> decrypted_text = running_key_decrypt(key, ciphertext)
51-
>>> decrypted_text == "DEFENDTHIS"
55+
>>> ciphertext = running_key_encrypt(key, "DEFEND THIS")
56+
>>> running_key_decrypt(key, ciphertext) == "DEFENDTHIS"
5257
True
5358
"""
5459

@@ -59,11 +64,12 @@ def test_running_key_encrypt() -> None:
5964
doctest.testmod()
6065
test_running_key_encrypt()
6166

62-
key = "How does the duck know that? said Victor"
6367
plaintext = input("Enter the plaintext: ").upper()
68+
print(f"\n{plaintext = }")
69+
70+
key = "How does the duck know that? said Victor"
6471
encrypted_text = running_key_encrypt(key, plaintext)
65-
decrypted_text = running_key_decrypt(key, encrypted_text)
72+
print(f"{encrypted_text = }")
6673

67-
print("\nPlaintext:", plaintext)
68-
print("Encrypted:", encrypted_text)
69-
print("Decrypted:", decrypted_text)
74+
decrypted_text = running_key_decrypt(key, encrypted_text)
75+
print(f"{decrypted_text = }")

0 commit comments

Comments
 (0)