python

Finished
11def encode(plain_text: str, a: int, b: int) -> str:
2 pass
3
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 plain_text = plain_text.lower()
10
11 for char in plain_text:
12 # Edge Case: Skip non-alphanumeric characters
13 if not char.isalnum():
14 continue
15
16 if char.isalpha():
17 # Edge Case: Encrypt alphabetic characters
18 i = ord(char) - ord('a')
19 encrypted_index = (a * i + b) % m
20 result.append(chr(encrypted_index + ord('a')))
21 else:
22 # Edge Case: Keep digits as they are
23 result.append(char)
24
25 # Edge Case: Group the result into chunks of 5 characters
26 grouped_result = []
27 for i in range(0, len(result), 5):
28 grouped_result.append(''.join(result[i:i+5]))
29
30 return ' '.join(grouped_result)
431
532def decode(ciphered_text: str, a: int, b: int) -> str:
6 pass
33 m = 26 # Size of the alphabet
34
35 # Edge Case: Check if a and m are coprime
36 if gcd(a, m) != 1:
37 raise ValueError("a and m must be coprime.")
38
39 # Edge Case: Find the modular multiplicative inverse of a
40 a_inv = mod_inverse(a, m)
41
42 result = []
43 ciphered_text = ciphered_text.replace(' ', '') # Remove spaces
44
45 for char in ciphered_text:
46 if char.isalpha():
47 # Edge Case: Decrypt alphabetic characters
48 y = ord(char) - ord('a')
49 decrypted_index = (a_inv * (y - b)) % m
50 result.append(chr(decrypted_index + ord('a')))
51 else:
52 # Edge Case: Keep digits as they are
53 result.append(char)
54
55 return ''.join(result)
56
57# Helper function to compute the greatest common divisor
58def gcd(x: int, y: int) -> int:
59 while y:
60 x, y = y, x % y
61 return x
62
63# Helper function to compute the modular multiplicative inverse
64def mod_inverse(a: int, m: int) -> int:
65 # Edge Case: Find x such that (a * x) % m == 1
66 for x in range(1, m):
67 if (a * x) % m == 1:
68 return x
69 # Edge Case: This should not happen if a and m are coprime
70 raise ValueError("Modular inverse does not exist.")
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.