Suppose path strings are encoded in this way:
- 2T3T5: means move 2 steps, turn right, move 3 steps, turn right, and move 5 steps
- 32T: which better read as 3(2T), and it means do the following operation 3 times => (move 2 steps, turn right), if written in a complete word, it means move 2 steps, turn right, move 2 steps, turn right, move 2 steps, turn right
- 3(4T2T)5T, which means do 3 time operation of (move 4 steps, turn right, move 2 steps, turn right), then move 5 steps and turn right
The method I want to review is parse_path, and I put some other mock methods for debug purposes only. Any advice to make the parser more reliable, more elegant/shorter and any code style advice is highly appreciated.
class Movement:
def __init__(self,x,y,delta_x,delta_y):
self.x = x
self.y = y
self.delta_x = delta_x
self.delta_y = delta_y
def move(self, steps):
print 'move ', steps
def turn_right(self):
print 'turn right'
def parse_path(self, source):
#2T3T5
#32T
#3(4T2T)5T
start = 0
index = 0
while index < len(source):
if source[index] == 'T':
steps = int(source[start:index])
if steps >= 10:
times = steps / 10
steps = steps % 10
else:
times = 1
for t in range(times):
self.move(steps)
self.turn_right()
start = index + 1
index += 1
elif index == len(source) - 1:
steps = int(source[start:index+1])
if steps >= 10:
times = steps / 10
steps = steps % 10
else:
times = 1
for t in range(times):
self.move(steps)
start = index + 1
index += 1
elif source[index] == '(':
right = index
while source[right] != ')':
right += 1
times = int(source[start:index])
for t in range(times):
self.parse_path(source[index+1:right])
index = right + 1
start = index
else:
index += 1
if __name__ == "__main__":
m = Movement(0,0,0,0)
# 2T3T5
# 32T
# 3(4T2T)5T
#m.parse_path("2T3T5")
#m.parse_path("32T")
m.parse_path("3(4T2T)5T")
999Tbe parsed?99(9T),9(99T)or9(9(9T))? \$\endgroup\$(121)1Tor(8)5Tsince131Tis 13 steps and 13 turns (13(1T)). \$\endgroup\$(121)1Tnor(8)5Tworks, but1(121)1Tor1(8)5Tdoes work... :-D \$\endgroup\$