一系列运动后机器人距起点的距离

2024-04-25 04:35:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图写一个程序,其中采取的方向和大小的清单,并输出的距离,机器人从其起始位置。在

我在执行以下代码时遇到一个错误,但我无法确定为什么会出现错误。在

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


Tags: 代码import程序距离len错误机器人position
2条回答

很可能你把空格和制表符弄混了。在本例中,将符号放在幅值内并使用x和{}进行过滤可能更容易,如下所示:

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距离:

^{pr2}$

以及特定方向上的总y距离:

In [18]: sum( [md[0]  for md in mDr if md[1] =='Y'] )
Out[18]: -1

您可以对x执行相同的操作,然后用这种方法计算距离。在

这是我的离题反应(你的问题是混合制表符和空格,我的答案是简单重写)。在

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而不是{}进行循环。在
  • 逻辑“移动到哪里”从if elif elif移到字典xymoves
  • 拒绝接受工艺指导,这是不可预料的
  • math.sqrt始终返回float,因此删除了对float的转换

注意,带有xymoves的字典可以扩展到其他方向,例如,使用“N”表示北,“NE”表示东北等

相关问题 更多 >