【发布时间】:2021-04-21 19:13:56
【问题描述】:
我正在处理这个代码挑战:
给定一个只能在四个方向上移动的 2D 机器人/机器人,在 10x10 网格中向前移动是 UP(U),向后移动是 DOWN(D)、LEFT(L)、RIGHT(R)。机器人不能超出 10x10 的区域。
给定一个包含移动指令的字符串。
执行指令后输出机器人的坐标。机器人初始位置在原点(0, 0)。
Example:
Input : move = “UDDLRL”
Output : (-1, -1)
Explanation:
Move U : (0, 0)–(0, 1)
Move D : (0, 1)–(0, 0)
Move D : (0, 0)–(0, -1)
Move L : (0, -1)–(-1, -1)
Move R : (-1, -1)–(0, -1)
Move L : (0, -1)–(-1, -1)
Therefore final position after the complete
movement is: (-1, -1)
我在不使用 10x10 网格信息的情况下使代码正常工作。如何以 OOP 方式将 10x10 网格信息合并到我的解决方案中?我的解决方案不遵循 OOP 原则。
# function to find final position of
# robot after the complete movement
def finalPosition(move):
l = len(move)
countUp, countDown = 0, 0
countLeft, countRight = 0, 0
# traverse the instruction string 'move'
for i in range(l):
# for each movement increment its respective counter
if (move[i] == 'U'):
countUp += 1
elif(move[i] == 'D'):
countDown += 1
elif(move[i] == 'L'):
countLeft += 1
elif(move[i] == 'R'):
countRight += 1
# required final position of robot
print("Final Position: (", (countRight - countLeft),
", ", (countUp - countDown), ")")
# Driver code
if __name__ == '__main__':
move = "UDDLLRUUUDUURUDDUULLDRRRR"
finalPosition(move)
【问题讨论】:
-
使用 10x10 网格与没有 10x10 网格的代码有何不同?
-
我想知道我是否应该先创建一个 10X10 的网格。这个问题只是陈述了一个 10 X 10 的网格。我猜机器人不能超出 10 X 10 的区域。
-
那么你应该检查你的计数不能变成负数并且不能超过9,对吧?你试过了吗?
-
我明白了。会试一试。 @trincot
-
@trincot 现在使用您的解决方案更有意义。 +1
标签: python-3.x oop robot