Generates a template based on the key and fills it in with the characters of the input string and then reading it in a zigzag formation. >>> decrypt("HWe olordll", 4) 'Hello World' >>> decrypt("This is a message", -10) Traceback (most recent call last):
(input_string: str, key: int)
| 39 | |
| 40 | |
| 41 | def decrypt(input_string: str, key: int) -> str: |
| 42 | """ |
| 43 | Generates a template based on the key and fills it in with |
| 44 | the characters of the input string and then reading it in |
| 45 | a zigzag formation. |
| 46 | |
| 47 | >>> decrypt("HWe olordll", 4) |
| 48 | 'Hello World' |
| 49 | |
| 50 | >>> decrypt("This is a message", -10) |
| 51 | Traceback (most recent call last): |
| 52 | ... |
| 53 | ValueError: Height of grid can't be 0 or negative |
| 54 | |
| 55 | >>> decrypt("My key is very big", 100) |
| 56 | 'My key is very big' |
| 57 | """ |
| 58 | grid = [] |
| 59 | lowest = key - 1 |
| 60 | |
| 61 | if key <= 0: |
| 62 | raise ValueError("Height of grid can't be 0 or negative") |
| 63 | if key == 1: |
| 64 | return input_string |
| 65 | |
| 66 | temp_grid: list[list[str]] = [[] for _ in range(key)] # generates template |
| 67 | for position in range(len(input_string)): |
| 68 | num = position % (lowest * 2) # puts it in bounds |
| 69 | num = min(num, lowest * 2 - num) # creates zigzag pattern |
| 70 | temp_grid[num].append("*") |
| 71 | |
| 72 | counter = 0 |
| 73 | for row in temp_grid: # fills in the characters |
| 74 | splice = input_string[counter : counter + len(row)] |
| 75 | grid.append(list(splice)) |
| 76 | counter += len(row) |
| 77 | |
| 78 | output_string = "" # reads as zigzag |
| 79 | for position in range(len(input_string)): |
| 80 | num = position % (lowest * 2) # puts it in bounds |
| 81 | num = min(num, lowest * 2 - num) # creates zigzag pattern |
| 82 | output_string += grid[num][0] |
| 83 | grid[num].pop(0) |
| 84 | return output_string |
| 85 | |
| 86 | |
| 87 | def bruteforce(input_string: str) -> dict[int, str]: |
no test coverage detected