python-3.x - 找到要充电的机器人
问题描述
有一个机器人想去充电点给自己充电。机器人从原点 (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)
解决方案
我有一个替代解决方案:
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
也许这更容易理解。
推荐阅读
- mongodb - 您未能连接到 MongoDB Atlas 集群。请确保您的 IP 白名单允许来自您的网络的连接
- ios - Xamarin:推送到达 ios 应用程序的问题;在应用程序之外到达没有问题
- r - 根据类别分组
- c# - 使用 C# 设置 Db2 语句终止符
- python - django - get() 返回多个电话 - 它返回 4
- python - AcyncClient python socketio
- java - 如何对数组进行分组?
- atlassian-sourcetree - 重命名文件/文件夹时,如何在提交日志/提交历史中查看旧名称详细信息
- android - AOSP 10:Android.mk 从多个 c 文件构建可执行 bin
- javascript - 使用 React/D3 从另一个文件引用 div id 时出错