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)
| 2 | |
| 3 | |
| 4 | def 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 | |
| 41 | def decrypt(input_string: str, key: int) -> str: |