Coordinate.getNeighbours() and Grid.getNeighboursOf() can be generators; no need to create extra lists every time

This commit is contained in:
Stefan Harmuth 2022-12-12 08:11:29 +01:00
parent 5df82d2359
commit 00de38a277
2 changed files with 9 additions and 14 deletions

View File

@ -113,11 +113,9 @@ class Coordinate:
else:
nb_list = [(-1, 0), (1, 0), (0, -1), (0, 1)]
return [
Coordinate(self.x + dx, self.y + dy)
for dx, dy in nb_list
if minX <= self.x + dx <= maxX and minY <= self.y + dy <= maxY
]
for dx, dy in nb_list:
if minX <= self.x + dx <= maxX and minY <= self.y + dy <= maxY:
yield self.__class__(self.x + dx, self.y + dy)
else:
if includeDiagonal:
nb_list = [(x, y, z) for x in [-1, 0, 1] for y in [-1, 0, 1] for z in [-1, 0, 1]]
@ -125,11 +123,9 @@ class Coordinate:
else:
nb_list = [(-1, 0, 0), (0, -1, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, -1)]
return [
Coordinate(self.x + dx, self.y + dy, self.z + dz)
for dx, dy, dz in nb_list
if minX <= self.x + dx <= maxX and minY <= self.y + dy <= maxY and minZ <= self.z + dz <= maxZ
]
for dx, dy, dz in nb_list:
if minX <= self.x + dx <= maxX and minY <= self.y + dy <= maxY and minZ <= self.z + dz <= maxZ:
yield self.__class__(self.x + dx, self.y + dy, self.z + dz)
def getAngleTo(self, target: Coordinate, normalized: bool = False) -> float:
"""normalized returns an angle going clockwise with 0 starting in the 'north'"""

View File

@ -224,10 +224,9 @@ class Grid:
minX=self.minX, minY=self.minY, minZ=self.minZ,
maxX=self.maxX, maxY=self.maxY, maxZ=self.maxZ
)
if includeDefault:
return neighbours
else:
return [x for x in neighbours if x in self.__grid]
for x in neighbours:
if includeDefault or x in self.__grid:
yield x
def getNeighbourSum(self, pos: Coordinate, includeNegative: bool = True, includeDiagonal: bool = True) -> Numeric:
neighbour_sum = 0