Skip to content
Advertisement

Find neighbors coordinate (python)

I am creating code that calculates neighbor coordinates to passed coordinate.

I have list of lists with “directions” I want move to, first number is X-value, second number is Y-value.

directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]

Then I have a function to calculate new coordinates and store them in a list “results”

results = []

def NeighborsFinder(coordinate):
    originalCoordinate = coordinate
    for x in range(0, len(directions)):
        coordinate[0] += directions[x][0]
        coordinate[1] += directions[x][1]
        results.append(coordinate)
        print(coordinate)
        coordinate = originalCoordinate

Example: if I pass coordinate [2, 3]

Then correct output should be list with coordinates: [2, 4] [2, 2], [3, 3], [1, 3]

Well but what happens to me is that its adding +1, but not substracting -1 so my output look like this: [2, 4], [2, 3], [3, 3], [2, 3].

Advertisement

Answer

Okay, so that code does not do what you intend it to do. Lists are mutable which means that

>>> coordinate = [2, 3]
>>> oldCoordinate = coordinate
>>> coordinate.append(5)
>>> coordinate
[2, 3, 5]
>>> oldCoordinate  # oldCoordinate has changed too
[2, 3, 5]

an option would be to use copy

>>> coordinate = [2, 3]
>>> oldCoordinate = coordinate.copy()
>>> coordinate.append(5)
>>> coordinate
[2, 3, 5]
>>> oldCoordinate
[2, 3]

but even with that, there are things to change here cause your code is hard to reason about, it would be better to do that

def NeighborsFinder(coordinate, directions):
    newCoordinates = []
    for x, y in directions:
        newCoordinates.append([coordinate[0] + x, coordinate[1] + y])
    print(newCoordinates)

it’s shorter, more beautiful and way easier to reason about

EDIT: But it can be even better actually, it can be a clear one liner

def neighbors_finder(coordinate, directions):
    return [[x + coordinate[0], y + coordinate[0]] for x, y in directions]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement