MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / gronsfeld

Function gronsfeld

ciphers/gronsfeld_cipher.py:4–39  ·  view source on GitHub ↗

Encrypt plaintext with the Gronsfeld cipher >>> gronsfeld('hello', '412') 'LFNPP' >>> gronsfeld('hello', '123') 'IGOMQ' >>> gronsfeld('', '123') '' >>> gronsfeld('yes, ¥€$ - _!@#%?', '0') 'YES, ¥€$ - _!@#%?' >>> gronsfeld('yes, ¥€$ - _!@#%?', '01') 'YFS,

(text: str, key: str)

Source from the content-addressed store, hash-verified

2
3
4def gronsfeld(text: str, key: str) -> str:
5 """
6 Encrypt plaintext with the Gronsfeld cipher
7
8 >>> gronsfeld('hello', '412')
9 'LFNPP'
10 >>> gronsfeld('hello', '123')
11 'IGOMQ'
12 >>> gronsfeld('', '123')
13 ''
14 >>> gronsfeld('yes, ¥€$ - _!@#%?', '0')
15 'YES, ¥€$ - _!@#%?'
16 >>> gronsfeld('yes, ¥€$ - _!@#%?', '01')
17 'YFS, ¥€$ - _!@#%?'
18 >>> gronsfeld('yes, ¥€$ - _!@#%?', '012')
19 'YFU, ¥€$ - _!@#%?'
20 >>> gronsfeld('yes, ¥€$ - _!@#%?', '')
21 Traceback (most recent call last):
22 ...
23 ZeroDivisionError: division by zero
24 """
25 ascii_len = len(ascii_uppercase)
26 key_len = len(key)
27 encrypted_text = ""
28 keys = [int(char) for char in key]
29 upper_case_text = text.upper()
30
31 for i, char in enumerate(upper_case_text):
32 if char in ascii_uppercase:
33 new_position = (ascii_uppercase.index(char) + keys[i % key_len]) % ascii_len
34 shifted_letter = ascii_uppercase[new_position]
35 encrypted_text += shifted_letter
36 else:
37 encrypted_text += char
38
39 return encrypted_text
40
41
42if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected