如何将最近的邻居功能更改为不对角线工作

How to change nearest neighbors function to not work diagonally

我正在使用最近邻函数,但我不知道如何让它只在水平和垂直方向上工作,现在它在所有方向上都可以工作。代码如下:

nnlst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

MAP_WIDTH = 3
MAP_HEIGHT = 3


def nearest_neighbors(map_x, map_y):
    coordinates_list = []
    for x_ in range(max(0, map_x - 1), min(MAP_WIDTH, map_x + 2)):
        for y_ in range(max(0, map_y - 1), min(MAP_HEIGHT, map_y + 2)):
            # we are ignoring result when x_ and y_ equals variable we ask for
            if (map_x, map_y) == (x_, y_):
                continue
            coordinates_list.append([x_, y_])
    return coordinates_list

print "function result"
print "nearest neighbors of", nnlst[0][1]
nearest_neighbor_coordinates_list = nearest_neighbors(0, 1)

for coordinates in nearest_neighbor_coordinates_list:
    print coordinates, "=", nnlst[coordinates[0]][coordinates[1]]

如您现在所见,它适用于所有方向。

您需要再添加一个条件以防止包含对角线:

def nearest_neighbors(map_x, map_y):
    coordinates_list = []
    for x_ in range(max(0, map_x - 1), min(MAP_WIDTH, map_x + 2)):
        for y_ in range(max(0, map_y - 1), min(MAP_HEIGHT, map_y + 2)):
            # we are ignoring result when x_ and y_ equals variable we ask for, also the diagonal neigbors that differ in both x & y coordinates
            if (map_x, map_y) == (x_, y_) or (map_x != x_ and map_y != y_):
                continue
            coordinates_list.append([x_, y_])
    return coordinates_list

获得想要的结果:

function result
nearest neighbors of 2
[0, 0] = 1
[0, 2] = 3
[1, 1] = 5

或者,您可以明确列出所有 "admissible" 位移:

for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
    x_ = min(MAP_WIDTH, max(0, map_x + dx))
    y_ = min(MAP_HEIGHT, max(0, map_y + dy))

    if (map_x, map_y) == (x_, y_):
        continue

    ...

对于可能性很小的问题,我会把它们全部拼出来,然后 pre-compute 每个位置的函数结果。这样就可以消除该功能,并将问题简化为进行简单的 table look-up 操作。

我的意思是:

nnlist = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

MAP_WIDTH = len(nnlist[0])
MAP_HEIGHT = len(nnlist)

nearest_neighbors = {}  # is now a dictionary
for x in range(MAP_WIDTH):
    for y in range(MAP_HEIGHT):
        neighbors = [[nx, ny] for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]
                                  if -1 < nx < MAP_WIDTH and -1 < ny < MAP_HEIGHT]
        nearest_neighbors[(x, y)] = neighbors

print "look-up result"
print "nearest neighbors of", nnlist[0][1]
nearest_neighbor_coordinates_list = nearest_neighbors[(0, 1)]

for coordinates in nearest_neighbor_coordinates_list:
    print coordinates, "=", nnlist[coordinates[0]][coordinates[1]]