I have given the Mars Rover challenge a go in Python as DSA practice.
Here is the challenge:
A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.
In order to control a rover , NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading._
Test Input:
5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM
Expected Output:
1 3 N
5 1 E
I am still relatively new to Python so know this is a bit basic - but I wondered if I could get some general feedback on my code for best coding practice?
RIGHT_ROTATE = {
'N':'E',
'E':'S',
'S':'W',
'W':'N'
}
LEFT_ROTATE = {
'N':'W',
'W':'S',
'S':'E',
'E':'N'
}
class MarsRover():
def __init__(self, X, Y, direction):
self.X = X
self.Y = Y
self.direction = direction
def rotate_right(self):
self.direction = RIGHT_ROTATE[self.direction]
def rotate_left(self):
self.direction = LEFT_ROTATE[self.direction]
def move(self):
if self.direction == 'N':
self.Y += 1
elif self.direction == 'E':
self.X += 1
elif self.direction == 'S':
self.Y -= 1
elif self.direction == 'W':
self.X -= 1
def __str__(self):
return str(self.X) + " " + str(self.Y) + " " + self.direction
@classmethod
def get_rover_position(self):
position = input("Position:")
X = int(position[0])
Y = int(position[2])
direction = position[4]
return self(X, Y, direction)
class Plateau():
def __init__(self, height, width):
self.height = height
self.width = width
@classmethod
def get_plateau_size(self):
plateau_size = input("Plateau size:")
height = int(plateau_size[0])
width = int(plateau_size[2])
return self(height, width)
def main():
plateau = Plateau.get_plateau_size()
while True:
rover = MarsRover.get_rover_position()
current_command = 0
command = input("Please input directions for rover.")
command_length = len(command)
while current_command <= command_length - 1:
if command[current_command] == 'L':
rover.rotate_left()
current_command += 1
elif command[current_command] == 'R':
rover.rotate_right()
current_command += 1
elif command[current_command] == 'M':
rover.move()
current_command += 1
result = str(rover)
print(result)
if __name__ == '__main__':
main()