| 1 | import random |
| 2 | import string |
| 1 | 3 | from typing import Optional |
| 2 | 4 | |
| 3 | 5 | class Cipher: |
| 4 | 6 | def __init__(self, key: Optional[str] = None) -> None: |
| 5 | | pass |
| 7 | if key is None: |
| 8 | # Edge Case: No key provided - generate random key of at least 100 lowercase letters |
| 9 | self.key = ''.join(random.choices(string.ascii_lowercase, k=100)) |
| 10 | else: |
| 11 | # Edge Case: Empty key provided - treat as invalid and generate random key |
| 12 | if not key: |
| 13 | self.key = ''.join(random.choices(string.ascii_lowercase, k=100)) |
| 14 | else: |
| 15 | # Edge Case: Key with non-alphabetic characters - only keep lowercase letters |
| 16 | cleaned_key = ''.join(filter(str.isalpha, key)).lower() |
| 17 | # Edge Case: Key with no valid alphabetic characters after cleaning |
| 18 | if not cleaned_key: |
| 19 | self.key = ''.join(random.choices(string.ascii_lowercase, k=100)) |
| 20 | else: |
| 21 | self.key = cleaned_key |
| 6 | 22 | |
| 7 | 23 | def encode(self, text: str) -> str: |
| 8 | | pass |
| 24 | # Edge Case: Empty plaintext |
| 25 | if not text: |
| 26 | return "" |
| 27 | |
| 28 | result = [] |
| 29 | key_length = len(self.key) |
| 30 | |
| 31 | for i, char in enumerate(text): |
| 32 | # Edge Case: Non-alphabetic characters in plaintext - preserve them |
| 33 | if not char.isalpha(): |
| 34 | result.append(char) |
| 35 | continue |
| 36 | |
| 37 | # Edge Case: Uppercase letters in input - convert to lowercase |
| 38 | char = char.lower() |
| 39 | |
| 40 | key_char = self.key[i % key_length] |
| 41 | shift = ord(key_char) - ord('a') |
| 42 | char_code = ord(char) - ord('a') |
| 43 | new_code = (char_code + shift) % 26 |
| 44 | result.append(chr(new_code + ord('a'))) |
| 45 | |
| 46 | return ''.join(result) |
| 47 | # Handled Edge Cases: empty plaintext, non-alphabetic characters in plaintext, uppercase letters in input |
| 9 | 48 | |
| 10 | 49 | def decode(self, text: str) -> str: |
| 11 | | pass |
| 50 | # Edge Case: Empty ciphertext |
| 51 | if not text: |
| 52 | return "" |
| 53 | |
| 54 | result = [] |
| 55 | key_length = len(self.key) |
| 56 | |
| 57 | for i, char in enumerate(text): |
| 58 | # Edge Case: Non-alphabetic characters in ciphertext - preserve them |
| 59 | if not char.isalpha(): |
| 60 | result.append(char) |
| 61 | continue |
| 62 | |
| 63 | # Edge Case: Uppercase letters in input - convert to lowercase |
| 64 | char = char.lower() |
| 65 | |
| 66 | key_char = self.key[i % key_length] |
| 67 | shift = ord(key_char) - ord('a') |
| 68 | char_code = ord(char) - ord('a') |
| 69 | new_code = (char_code - shift) % 26 |
| 70 | result.append(chr(new_code + ord('a'))) |
| 71 | |
| 72 | return ''.join(result) |
| 73 | # Handled Edge Cases: empty ciphertext, non-alphabetic characters in ciphertext, uppercase letters in input |