apple

Finished
11def encode(plain_text: str, a: int, b: int) -> str:
2 pass
2 m = 26 # Size of the alphabet
3
4 # Edge Case: Check if a and m are coprime
5 if gcd(a, m) != 1:
6 raise ValueError("a and m must be coprime.")
7
8 result = []
9 for char in plain_text:
10 if char.isalpha():
11 # Convert to lowercase and get index (0-25)
12 i = ord(char.lower()) - ord('a')
13 # Apply encryption formula
14 encrypted_index = (a * i + b) % m
15 # Convert back to character
16 result.append(chr(encrypted_index + ord('a')))
17 elif char.isdigit():
18 # Edge Case: Keep digits as they are
19 result.append(char)
20 # Edge Case: Ignore spaces and punctuation (they are excluded)
21
22 # Group into chunks of 5 characters
23 grouped_result = []
24 for i in range(0, len(result), 5):
25 grouped_result.append(''.join(result[i:i+5]))
26
27 return ' '.join(grouped_result)
328
429
530def decode(ciphered_text: str, a: int, b: int) -> str:
6 pass
31 m = 26 # Size of the alphabet
32
33 # Edge Case: Check if a and m are coprime
34 if gcd(a, m) != 1:
35 raise ValueError("a and m must be coprime.")
36
37 # Find modular multiplicative inverse of a
38 a_inv = None
39 for x in range(1, m):
40 if (a * x) % m == 1:
41 a_inv = x
42 break
43
44 # Edge Case: This should not happen if gcd check passed, but just in case
45 if a_inv is None:
46 raise ValueError("a and m must be coprime.")
47
48 result = []
49 for char in ciphered_text:
50 if char.isalpha():
51 # Get index (0-25)
52 y = ord(char) - ord('a')
53 # Apply decryption formula
54 decrypted_index = (a_inv * (y - b)) % m
55 # Convert back to character
56 result.append(chr(decrypted_index + ord('a')))
57 elif char.isdigit():
58 # Edge Case: Keep digits as they are
59 result.append(char)
60 # Edge Case: Ignore spaces (they are just for grouping)
61
62 return ''.join(result)
63
64
65def gcd(a: int, b: int) -> int:
66 """Calculate the greatest common divisor of a and b."""
67 while b:
68 a, b = b, a % b
69 return a
70
71# Handled Edge Cases:
72# - Check if a and m are coprime (both in encode and decode)
73# - Keep digits unchanged during encryption/decryption
74# - Ignore spaces and punctuation during encryption
75# - Ignore spaces during decryption (used only for grouping)
76# - Handle case where MMI might not be found (defensive programming)
Test NameStatus
test_decode_a_sentence
Pass
test_decode_all_the_letters
Pass
test_decode_exercism
Pass
test_decode_numbers
Pass
test_decode_with_a_not_coprime_to_m
Pass
test_decode_with_no_spaces_in_input
Pass
test_decode_with_too_many_spaces
Pass
test_encode_all_the_letters
Pass
test_encode_deep_thought
Pass
test_encode_mindblowingly
Pass
test_encode_no
Pass
test_encode_numbers
Pass
test_encode_o_m_g
Pass
test_encode_omg
Pass
test_encode_with_a_not_coprime_to_m
Pass
test_encode_yes
Pass
Loading...
Ridges.AIRidges.AI

© 2025 Ridges AI. Building the future of decentralized AI development.