-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_examples.py
More file actions
209 lines (178 loc) · 7.47 KB
/
test_examples.py
File metadata and controls
209 lines (178 loc) · 7.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python3
"""
Additional examples and tests for the StringWalker class.
"""
from string_walker import StringWalker
def test_basic_operations():
"""Test basic string walking operations."""
print("=== Basic Operations Test ===")
walker = StringWalker("Python Programming")
print(f"String: '{walker.get_string()}'")
print(f"Length: {walker.get_length()}")
print(f"Current position: {walker.get_current_position()}")
print(f"Current character: '{walker.get_current_character()}'")
print()
def test_navigation():
"""Test navigation methods."""
print("=== Navigation Test ===")
walker = StringWalker("ABCDEFGHIJK")
# Walk forward in steps
print("Walking forward:")
for i in range(5):
walker.walk_forward()
print(f"Position {walker.get_current_position()}: '{walker.get_current_character()}'")
print("\nWalking backward:")
for i in range(3):
walker.walk_backward()
print(f"Position {walker.get_current_position()}: '{walker.get_current_character()}'")
# Jump to specific positions
print("\nJumping to positions:")
positions = [0, 5, 10, 7, 2]
for pos in positions:
if walker.go_to_position(pos):
print(f"Position {pos}: '{walker.get_current_character()}'")
else:
print(f"Position {pos}: Invalid position")
print()
def test_character_replacement():
"""Test character replacement functionality."""
print("=== Character Replacement Test ===")
walker = StringWalker("Hello World")
print(f"Original: '{walker.get_string()}'")
# Replace characters at specific positions
replacements = [(0, 'J'), (6, 'P'), (10, '!')]
for pos, char in replacements:
if walker.replace_character_at(pos, char):
print(f"Replaced position {pos} with '{char}': '{walker.get_string()}'")
else:
print(f"Failed to replace position {pos}")
# Replace current character
walker.go_to_position(4)
print(f"Current position {walker.get_current_position()}: '{walker.get_current_character()}'")
walker.replace_current_character('X')
print(f"After replacing current: '{walker.get_string()}'")
print()
def test_bounds_checking():
"""Test bounds checking and error handling."""
print("=== Bounds Checking Test ===")
walker = StringWalker("Short")
print(f"String: '{walker.get_string()}' (length: {walker.get_length()})")
# Test out-of-bounds access
print("\nTesting out-of-bounds access:")
invalid_positions = [-1, 5, 10, 100]
for pos in invalid_positions:
char = walker.get_character_at(pos)
print(f"Position {pos}: {char}")
# Test out-of-bounds navigation
print("\nTesting out-of-bounds navigation:")
walker.go_to_start()
print(f"At start: position {walker.get_current_position()}")
# Try to walk backward from start
success = walker.walk_backward()
print(f"Walk backward from start: {success}")
# Try to walk forward beyond end
walker.go_to_end()
print(f"At end: position {walker.get_current_position()}")
success = walker.walk_forward()
print(f"Walk forward from end: {success}")
# Test invalid replacement
print("\nTesting invalid replacement:")
success = walker.replace_character_at(10, 'X') # Out of bounds
print(f"Replace at position 10: {success}")
success = walker.replace_character_at(0, 'AB') # Multiple characters
print(f"Replace with multiple chars: {success}")
print()
def test_edge_cases():
"""Test edge cases and special scenarios."""
print("=== Edge Cases Test ===")
# Empty string
print("Testing empty string:")
empty_walker = StringWalker("")
print(f"Empty string length: {empty_walker.get_length()}")
print(f"Current character: {empty_walker.get_current_character()}")
print(f"Can walk forward: {empty_walker.walk_forward()}")
print()
# Single character string
print("Testing single character string:")
single_walker = StringWalker("A")
print(f"String: '{single_walker.get_string()}'")
print(f"At start: {single_walker.is_at_start()}")
print(f"At end: {single_walker.is_at_end()}")
print(f"Can walk forward: {single_walker.walk_forward()}")
print(f"Can walk backward: {single_walker.walk_backward()}")
print()
def interactive_demo():
"""Interactive demonstration of StringWalker."""
print("=== Interactive Demo ===")
user_string = input("Enter a string to walk through: ")
if not user_string:
user_string = "Default String"
walker = StringWalker(user_string)
while True:
print(f"\nCurrent state: {walker}")
print("\nCommands:")
print("f <steps> - walk forward")
print("b <steps> - walk backward")
print("g <position> - go to position")
print("r <position> <char> - replace character at position")
print("c <char> - replace current character")
print("s - go to start")
print("e - go to end")
print("q - quit")
command = input("\nEnter command: ").strip().lower()
if command == 'q':
break
elif command.startswith('f '):
try:
steps = int(command.split()[1])
success = walker.walk_forward(steps)
print(f"Walked forward {steps} steps: {'Success' if success else 'Failed'}")
except (IndexError, ValueError):
print("Invalid format. Use: f <steps>")
elif command.startswith('b '):
try:
steps = int(command.split()[1])
success = walker.walk_backward(steps)
print(f"Walked backward {steps} steps: {'Success' if success else 'Failed'}")
except (IndexError, ValueError):
print("Invalid format. Use: b <steps>")
elif command.startswith('g '):
try:
position = int(command.split()[1])
success = walker.go_to_position(position)
print(f"Went to position {position}: {'Success' if success else 'Failed'}")
except (IndexError, ValueError):
print("Invalid format. Use: g <position>")
elif command.startswith('r '):
try:
parts = command.split()
position = int(parts[1])
char = parts[2]
success = walker.replace_character_at(position, char)
print(f"Replaced at position {position}: {'Success' if success else 'Failed'}")
except (IndexError, ValueError):
print("Invalid format. Use: r <position> <char>")
elif command.startswith('c '):
try:
char = command.split()[1]
success = walker.replace_current_character(char)
print(f"Replaced current character: {'Success' if success else 'Failed'}")
except (IndexError, ValueError):
print("Invalid format. Use: c <char>")
elif command == 's':
walker.go_to_start()
print("Went to start")
elif command == 'e':
walker.go_to_end()
print("Went to end")
else:
print("Unknown command")
if __name__ == "__main__":
# Run all tests
test_basic_operations()
test_navigation()
test_character_replacement()
test_bounds_checking()
test_edge_cases()
# Uncomment the line below to run interactive demo
# interactive_demo()