| 1 | import math |
| 2 | import re |
| 3 | |
| 1 | 4 | def cipher_text(plain_text: str) -> str: |
| 2 | | pass |
| 5 | # Edge Case: empty input string |
| 6 | if not plain_text: |
| 7 | return "" |
| 8 | |
| 9 | # Normalize the text: remove spaces and punctuation, convert to lowercase |
| 10 | normalized = re.sub(r'[^a-zA-Z0-9]', '', plain_text).lower() |
| 11 | |
| 12 | # Edge Case: input with only spaces and punctuation |
| 13 | if not normalized: |
| 14 | return "" |
| 15 | |
| 16 | n = len(normalized) |
| 17 | |
| 18 | # Edge Case: single character input |
| 19 | if n == 1: |
| 20 | return normalized + " " |
| 21 | |
| 22 | # Find the dimensions of the rectangle |
| 23 | c = math.ceil(math.sqrt(n)) |
| 24 | r = math.ceil(n / c) |
| 25 | |
| 26 | # Edge Case: perfect square length text |
| 27 | # Ensure c >= r and c - r <= 1 |
| 28 | while c < r or c - r > 1: |
| 29 | c += 1 |
| 30 | r = math.ceil(n / c) |
| 31 | |
| 32 | # Create the rectangle by filling rows |
| 33 | rectangle = [] |
| 34 | for i in range(r): |
| 35 | start = i * c |
| 36 | end = start + c |
| 37 | row = normalized[start:end] |
| 38 | # Pad the last row if needed |
| 39 | if len(row) < c: |
| 40 | row += " " * (c - len(row)) |
| 41 | rectangle.append(row) |
| 42 | |
| 43 | # Read down the columns to create the encoded message |
| 44 | encoded_chunks = [] |
| 45 | for col in range(c): |
| 46 | chunk = "" |
| 47 | for row in range(r): |
| 48 | chunk += rectangle[row][col] |
| 49 | encoded_chunks.append(chunk) |
| 50 | |
| 51 | return " ".join(encoded_chunks) |
| 52 | |
| 53 | # Handled Edge Cases: empty input string, single character input, input with only spaces and punctuation, perfect square length text, text length requiring padding |