查找路径中的转弯数(坐标集)

Find the number of turns in path (set of coordinates)

a = [(24, 13), (23, 13), (22, 13), (21, 13), (20, 13),
     (19, 13), (19, 14), (19, 15), (18, 15), (17, 15),
     (16, 15), (15, 15), (14, 15), (13, 15), (13, 14),
     (13, 13), (13, 12), (13, 11), (13, 10), (12, 10),
     (11, 10), (10, 10), (9, 10), (8, 10), (7, 10),
     (7, 9), (7, 8), (7, 7), (7, 6), (7, 5), (7, 4),
     (6, 4), (5, 4), (4, 4)]

以上路径(一组唯一坐标)有 6 个转弯。

谁能帮我在 python 中编写相同的代码? 例如,对于上面的列表 a ,输出应该是 6.

length = len(a)-3
print length

for i in range(0,length):
    x1,y1 = a[i]
    x2,y2 = a[i+1]
    x3,y3 = a[i+2]

    if y1 is y2:
        if y1 is y3:
            x_flag = 1
        else:
            x_flag = 0

    if x_flag is 0:
        flag1 += 1
        print 'Turn'

print flag1

您可以将元组转换为 numpy 数组,并检查在两条腿之后,您是否在两个轴上都移动了。

arr = np.array(a)
((np.abs(arr[2:] - arr[:-2])>0).sum(axis=1)==2).sum()

可能不是最漂亮的解决方案,但最直接的方法是:

a = [(24, 13), (23, 13), (22, 13), (21, 13), (20, 13),
     (19, 13), (19, 14), (19, 15), (18, 15), (17, 15),
     (16, 15), (15, 15), (14, 15), (13, 15), (13, 14),
     (13, 13), (13, 12), (13, 11), (13, 10), (12, 10),
     (11, 10), (10, 10), (9, 10), (8, 10), (7, 10),
     (7, 9), (7, 8), (7, 7), (7, 6), (7, 5), (7, 4),
     (6, 4), (5, 4), (4, 4)]

count = 0
direction = -1

for i in range(1,len(a)):
    current_dir = 0 if a[i][0]-a[i-1][0] != 0 else 1
    if direction != -1:
        if current_dir != direction:
            # print("changing direction")
            count += 1
    direction = current_dir

print count

它假定您只会改变一个方向(即永远不会沿对角线移动)。

这是我的建议:

x0, y0 = a[0]
previous_move_dir = ''
turns_nb = -1  # start is not a turn
for x1, y1 in a[1:]:
    if x1 == x0 and abs(y1-y0) == 1:  # move is 1 in Y direction
        move_dir = 'Y'
    elif y1 == y0 and abs(x1-x0) == 1:  # move is 1 in X direction
        move_dir = 'X'
    else:  # move is anything else
        raise Exception('Bad coordinates definition')

    if move_dir != previous_move_dir:  # there is a direction change
        turns_nb += 1
    previous_move_dir = move_dir
    x0, y0 = x1, y1

print turns_nb