机器人经过一系列移动后与起始点的距离
我正在尝试写一个程序,这个程序可以接受一系列方向和距离,然后输出机器人离起始位置的距离。
我在运行下面的代码时遇到了一个错误,但我无法找出为什么会出现这个错误。
import math
position = [0,0]
direction = ['+Y','-X','-Y','+X','-X','-Y','+X']
magnitude = [9,7,4,8,3,6,2]
i = 0
while i < len(direction):
if direction[i] == '+Y': position[0] += magnitude[i]
elif direction[i] == '-Y': position[0] -= magnitude[i]
elif direction[i] == '+X': position[1] += magnitude[i]
elif direction[i] == '-X': position[1] -= magnitude[i]
else: pass
i += 1
print float(math.sqrt(position[1]**2+position[0]**2))
补充:
我遇到的错误是:
IndentationError: unindent does not match any outer indentation level
2 个回答
-1
这是我对这个问题的偏题反应(你的问题是混用了制表符和空格,我的回答很简单,就是重写代码)。
import math
xymoves = {"+X": (1, 0), "-X": (-1, 0), "+Y": (0, 1), "-Y": (0, -1)}
position = [0, 0]
directions = ['+Y', '-X', '-Y', '+X', '-X', '-Y', '+X']
assert all(xymove in xymoves for xymove in directions)
magnitudes = [9, 7, 4, 8, 3, 6, 2]
for direction, magnitude in zip(directions, magnitudes):
xmove, ymove = xymoves[direction]
position[0] += magnitude * xmove
position[1] += magnitude * ymove
print math.sqrt(position[1]**2+position[0]**2)
改动如下:
- 使用
for
循环,而不是用while
循环,并且用一个增加的索引。 - 决定“移动到哪里”的逻辑从
if elif elif
移到了一个字典xymoves
中。 - 拒绝处理那些不符合预期的方向。
math.sqrt
总是返回一个float
类型,所以去掉了转换成float
的步骤。
注意,字典 xymoves
可以扩展到其他方向,比如用 "N" 表示北,"NE" 表示东北等等。
0
很可能你把空格和制表符搞混了。在这种情况下,把符号放在大小范围内,然后用 x
和 y
来过滤,可能会更简单,像这样:
In [15]: mDr = [ (int(d[0]+m), d[1]) for (d, m) in zip(direction, map(str, magnitude))]
In [16]: mDr
Out[16]: [(9, 'Y'), (-7, 'X'), (-4, 'Y'), (8, 'X'), (-3, 'X'), (-6, 'Y'), (2, 'X')]
这样一来,你就能很容易地得到总的 x 和 y 距离。例如,y 距离:
In [17]: [md[0] for md in mDr if md[1] =='Y']
Out[17]: [9, -4, -6]
还有特定方向上的总 y
距离:
In [18]: sum( [md[0] for md in mDr if md[1] =='Y'] )
Out[18]: -1
你可以对 x
也做同样的操作,然后这样计算距离。