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 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 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)
331
432
533def decode(ciphered_text: str, a: int, b: int) -> str:
6 pass
34 m = 26 # Size of the alphabet
35
36 # Edge Case: Check if a and m are coprime
37 if gcd(a, m) != 1:
38 raise ValueError("a and m must be coprime.")
39
40 # Edge Case: Calculate modular multiplicative inverse of a
41 a_inv = mod_inverse(a, m)
42
43 result = []
44 ciphered_text = ciphered_text.replace(' ', '').lower()
45
46 for char in ciphered_text:
47 if char.isalpha():
48 # Edge Case: Decrypt alphabetic characters
49 y = ord(char) - ord('a')
50 decrypted_index = (a_inv * (y - b)) % m
51 result.append(chr(decrypted_index + ord('a')))
52 else:
53 # Edge Case: Keep digits as they are
54 result.append(char)
55
56 return ''.join(result)
57
58
59def gcd(a: int, b: int) -> int:
60 # Edge Case: Calculate greatest common divisor
61 while b:
62 a, b = b, a % b
63 return a
64
65
66def mod_inverse(a: int, m: int) -> int:
67 # Edge Case: Calculate modular multiplicative inverse
68 # Add iteration limit to prevent potential infinite loop
69 for x in range(1, m + 1):
70 if (a * x) % m == 1:
71 return x
72 # This should never happen if gcd(a, m) == 1
73 raise ValueError("Modular inverse does not exist")
74# Handled Edge Cases: a and m not coprime, non-alphanumeric characters, alphabetic encryption, digit handling, grouping into chunks, modular multiplicative inverse calculation, alphabetic decryption
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.