我正在尝试编写一个程序,该程序获取方向和大小的列表,并输出机器人从其起始位置的距离。
执行以下代码时出错,但我无法确定导致错误的原因。
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
答案 0 :(得分: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
执行相同操作,然后计算距离。{1}
答案 1 :(得分:-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的字典可以用其他方向扩展,例如使用&#34; N&#34;对于North,&#34; NE&#34;为东北等。