解决这个问题的面向对象方法是什么?

2024-03-29 14:11:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力解决这个问题

There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

Example 1:

  • Input: moves = "UD"
  • Output: true
  • Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

Example 2:

  • Input: moves = "LL"
  • Output: false
  • Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.

Example 3:

  • Input: moves = "RRDD"
  • Output: false

Example 4:

  • Input: moves = "LDRRLRUULR"
  • Output: false

尽管我使用计数器和条件来解决这个问题,但我还是想看看如何使用Python的OOP组件来解决这个问题。我如何将有效的移动(R(右)、L(左)、U(上)和D(下)分离到单独的方法中,以便更好地抽象,以便将来可以添加更多的方法?重构后的代码会是什么样子?这就是解决方案:

class Solution(object):
    def judgeCircle(self, moves):
        x = y = 0
        for move in moves:
            if move == 'U': y -= 1
            elif move == 'D': y += 1
            elif move == 'L': x -= 1
            elif move == 'R': x += 1

        return x == y == 0

Tags: ofthefalsemovereturnisrobotit
1条回答
网友
1楼 · 发布于 2024-03-29 14:11:29

这里有一种通过encapsulating数据和作用于数据的代码来实现的方法——这两种都是OOP的关键特性。请注意,使用“getter”和“setter”并不是“pythonic”(因为它们通常是不必要的,如果出于某种原因需要,可以追溯添加它们)

class Solution:

    class Mover:
        def __init__(self, x, y):
            self.x, self.y = x, y
        def new_pos(self, x, y):
            return x + self.x, y + self.y

    WALKS = dict(U=Mover(0, -1), D=Mover(0, 1),
                 L=Mover(-1, 0), R=Mover(1, 0))

    def judge_circle(self, moves):
        x = y = 0
        for id in moves:
            x, y = self.WALKS[id].new_pos(x, y)

        return x == y == 0


solution = Solution()
sequences = "UD", "LL", "RRDD", "LDRRLRUULR"

for moves in sequences:
    print(solution.judge_circle(moves))

相关问题 更多 >