Skip to content

Commit dba8eec

Browse files
Lonercodepre-commit-ci[bot]cclauss
authored
added gronsfeld cipher implementation (TheAlgorithms#11835)
* added gronsfeld cipher implementation * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * from string import ascii_uppercase * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update gronsfeld_cipher.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <[email protected]>
1 parent cfd6d09 commit dba8eec

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Diff for: ciphers/gronsfeld_cipher.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from string import ascii_uppercase
2+
3+
4+
def 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: integer modulo 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+
42+
if __name__ == "__main__":
43+
from doctest import testmod
44+
45+
testmod()

0 commit comments

Comments
 (0)