Finished
11def encode(message, rails):
2 pass
2 # Edge Case: zero or negative number of rails
3 if rails <= 0:
4 raise ValueError("Number of rails must be positive")
5
6 # Edge Case: empty message
7 if not message:
8 return ""
9
10 # Edge Case: single rail
11 if rails == 1:
12 return message
13
14 # Create rails as list of lists
15 fence = [[] for _ in range(rails)]
16
17 # Variables to track current rail and direction
18 rail = 0
19 direction = 1
20
21 # Place each character in the appropriate rail
22 for char in message:
23 fence[rail].append(char)
24
25 # Change direction at top and bottom rails
26 if rail == 0:
27 direction = 1
28 elif rail == rails - 1:
29 direction = -1
30
31 rail += direction
32
33 # Concatenate all rails
34 return ''.join(''.join(row) for row in fence)
35 # Handled Edge Cases: zero or negative number of rails, empty message, single rail
336
437
538def decode(encoded_message, rails):
6 pass
39 # Edge Case: zero or negative number of rails
40 if rails <= 0:
41 raise ValueError("Number of rails must be positive")
42
43 # Edge Case: empty encoded message
44 if not encoded_message:
45 return ""
46
47 # Edge Case: single rail
48 if rails == 1:
49 return encoded_message
50
51 # Edge Case: number of rails greater than message length
52 if rails > len(encoded_message):
53 return encoded_message
54
55 # Create a matrix to represent the fence
56 fence = [['' for _ in range(len(encoded_message))] for _ in range(rails)]
57
58 # Mark the positions that will have characters
59 rail = 0
60 direction = 1
61 for i in range(len(encoded_message)):
62 fence[rail][i] = '*'
63
64 if rail == 0:
65 direction = 1
66 elif rail == rails - 1:
67 direction = -1
68
69 rail += direction
70
71 # Fill the fence with characters from the encoded message
72 index = 0
73 for r in range(rails):
74 for c in range(len(encoded_message)):
75 if fence[r][c] == '*':
76 fence[r][c] = encoded_message[index]
77 index += 1
78
79 # Read the message by following the zigzag pattern
80 result = []
81 rail = 0
82 direction = 1
83 for i in range(len(encoded_message)):
84 result.append(fence[rail][i])
85
86 if rail == 0:
87 direction = 1
88 elif rail == rails - 1:
89 direction = -1
90
91 rail += direction
92
93 return ''.join(result)
94 # Handled Edge Cases: zero or negative number of rails, empty encoded message, single rail, number of rails greater than message length
Test NameStatus
test_decode_with_five_rails
Pass
test_decode_with_six_rails
Pass
test_decode_with_three_rails
Pass
test_encode_with_ending_in_the_middle
Pass
test_encode_with_three_rails
Pass
test_encode_with_two_rails
Pass

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