Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import dataclasses 

2 

3 

4@dataclasses.dataclass 

5class Rover: 

6 x: int 

7 y: int 

8 direction: str 

9 

10 valid_commands = ("F", "B", "R", "L") 

11 

12 direction_map = { 

13 "NORTH": (0, 1, "WEST", "EAST"), 

14 "EAST": (1, 0, "NORTH", "SOUTH"), 

15 "SOUTH": (0, -1, "EAST", "WEST"), 

16 "WEST": (-1, 0, "SOUTH", "NORTH"), 

17 } 

18 

19 def is_valid_command(self, command): 

20 for ch in command: 

21 if ch not in self.valid_commands: 

22 return False 

23 

24 return True 

25 

26 def move(self, command: str): 

27 if not self.is_valid_command(command): 

28 raise ValueError("invalid command. The rover does not move") 

29 

30 for ch in command: 

31 self._move_one_step(ch) 

32 

33 return self.x, self.y, self.direction 

34 

35 def _move_one_step(self, command): 

36 if command == "B": 

37 self.x -= self.direction_map[self.direction][0] 

38 self.y -= self.direction_map[self.direction][1] 

39 if command == "F": 

40 self.x += self.direction_map[self.direction][0] 

41 self.y += self.direction_map[self.direction][1] 

42 if command == "R": 

43 self.direction = self.direction_map[self.direction][3] 

44 if command == "L": 

45 self.direction = self.direction_map[self.direction][2]