机器人回原点

问题描述

问题:

一个机器人从位置 (0,0)(原点)开始,位于 2D 平面上。给定它的一系列动作,判断这个机器人完成动作后是否在(0,0)处结束。

移动序列用一个字符串表示,字符moves[i]代表它的第i个移动。有效的移动是 R(右)、L(左)、U(上)和 D(下)。如果机器人在完成所有移动后返回原点,则返回 true。否则返回false。

注意:机器人“面对”的方式无关紧要。 “R”总是让机器人向右移动一次,“L”总是让它向左移动,等等。另外,假设机器人每次移动的幅度都相同。

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.

我有以下解决方案,对于序列 = "UD" 似乎是错误的,它应该返回 True。有人可以帮助我了解我在这里做错了什么以及如何解决吗?

class Solution:

    class Mover:
        def __init__(self,x,y):
            self.x,self.y = x,y
        def new_pos(self,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

    def move_sequences(self,sequences):
        for moves in sequences:
            return (solution.judge_circle(moves))

if __name__ == "__main__":
    solution = Solution()
    sequences = "UD"
    print(solution.move_sequences(sequences))

解决方法

这个解决方案似乎想得太多了。您可以对 4 个方向中的每一个进行计数器,并确定相对于 UD 和相对于 LR 是否相同s。 return s.count("U") == s.count("D") and s.count("L") == s.count("R") 为您提供了一个线性解决方案,可以通过类似

的方式优化为单次传递
from collections import Counter
d = Counter(moves)
return d["D"] == d["U"] and d["R"] == d["L"]

至于您的代码,

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

我觉得很有趣。在第一次迭代时返回意味着循环毫无意义。 moves 此处的名称具有误导性——它只是一个字符 "U"judge_circle 已经做了一个循环,所以如果你真的想强制执行它,你只需要一个循环而不是两个。

,

您的任务很简单:

def judge_circle(moves):
    if moves.lower().count('U') == moves.lower().count('D') and moves.lower().count('L') == moves.lower().count('R'):
        return True
    else:
        return False
print(judge_circle('UD'))

您只需检查“上”的数量是否等于“下”的数量,“左”是否等于“右”。

,

好的,来自重构建议的一部分,您可以轻松地修复您的脚本。

def move_sequences(self,sequences):
    for moves in sequences:
        return (solution.judge_circle(moves))

失败,因为您在序列中传递一个字符串并且 for 循环在字母上循环,将每个字母传递给 Judge_circle。 删除 for 循环并将序列传递给 Judge_circle!