首页 > 解决方案 > 找到要充电的机器人

问题描述

有一个机器人想去充电点给自己充电。机器人从原点 (0,0) 在二维平面中移动。机器人可以按照给定的步骤向上、向下、向左和向右移动。机器人运动轨迹如下图所示:

UP 5
DOWN 3
LEFT 3
RIGHT 2

那么,程序的输出应该是:2

我的代码是

pos = {
    "x": 0, 
    "y": 0
}

while True:

    n = input()
    if not n:
        break

    direction,steps=n.split()
    if direction == "UP":
        pos["y"] += int(steps)
    elif direction == "DOWN":
        pos["y"] -= int(steps)
    elif direction == "LEFT":
        pos["x"] -= int(steps)
    elif direction == "RIGHT":
        pos["x"] += int(steps)
print (int(round((pos["x"]**2 + pos["y"]**2)**0.5)))

我收到一个错误 ValueError: not enough values to unpack (expected 2, got 1)

标签: python-3.x

解决方案


我有一个替代解决方案:

pos = {"x":0,"y":0}
num = int(input())

for _ in range (num):
    command =  input().split(" ")      # ACCEPT MOVEMENT COMMAND AND STORE AS A LIST
    if command[0] == "UP":             # EXTRACT DIRECTION AND COMPARE
        pos["y"] += int(command[1])    # INCREMENT/DECREMENT APPROPRIATE CO-ORDINATES
    if command[0] == "DOWN":
        pos["y"] -= int(command[1])
    if command[0] == "LEFT":
        pos["x"] -= int(command[1])
    if command[0] == "RIGHT":
        pos["x"] += int(command[1])

print(int(round((pos["x"]**2 + pos["y"]**2)**0.5)))   # DISTANCE FROM ORIGIN

也许这更容易理解。


推荐阅读