【问题标题】:Find the number of turns in path (set of coordinates)查找路径中的转数(坐标集)
【发布时间】:2015-02-03 13:08:51
【问题描述】:
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

【问题讨论】:

  • “转”是什么意思?没关系……明白了……
  • 绘制上述坐标时,编号为图中的匝数定义为转弯
  • edit问题包含您的代码。如您所见,多行代码在 cmets 中效果不佳。
  • 我猜 OP 的意思是 Winding Number

标签: python list path


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    这是我的建议:

    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
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-12
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 2022-01-22
        • 2018-02-11
        • 2011-01-14
        相关资源
        最近更新 更多