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

Function encrypt

ciphers/rail_fence_cipher.py:4–38  ·  view source on GitHub ↗

Shuffles the character of a string by placing each of them in a grid (the height is dependent on the key) in a zigzag formation and reading it left to right. >>> encrypt("Hello World", 4) 'HWe olordll' >>> encrypt("This is a message", 0) Traceback (most recent

(input_string: str, key: int)

Source from the content-addressed store, hash-verified

2
3
4def encrypt(input_string: str, key: int) -> str:
5 """
6 Shuffles the character of a string by placing each of them
7 in a grid (the height is dependent on the key) in a zigzag
8 formation and reading it left to right.
9
10 >>> encrypt("Hello World", 4)
11 'HWe olordll'
12
13 >>> encrypt("This is a message", 0)
14 Traceback (most recent call last):
15 ...
16 ValueError: Height of grid can't be 0 or negative
17
18 >>> encrypt(b"This is a byte string", 5)
19 Traceback (most recent call last):
20 ...
21 TypeError: sequence item 0: expected str instance, int found
22 """
23 temp_grid: list[list[str]] = [[] for _ in range(key)]
24 lowest = key - 1
25
26 if key <= 0:
27 raise ValueError("Height of grid can't be 0 or negative")
28 if key == 1 or len(input_string) <= key:
29 return input_string
30
31 for position, character in enumerate(input_string):
32 num = position % (lowest * 2) # puts it in bounds
33 num = min(num, lowest * 2 - num) # creates zigzag pattern
34 temp_grid[num].append(character)
35 grid = ["".join(row) for row in temp_grid]
36 output_string = "".join(grid)
37
38 return output_string
39
40
41def decrypt(input_string: str, key: int) -> str:

Callers

nothing calls this directly

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected