I've started learning python a few days ago, and I'm actually very impressed by its capabilities and syntax flexibility but today I encountered a strange bug that I've never seen in other programming languages, I suppose that it is caused by my limited knowladge of Python, I will appreciate any help and explanation of such behaviour.
I have a simple for loop in which I iterate over a list of nodes, in each iteration I add neighbours to current node, but it seems like they are added not just to current node but also to every other node in the collection, so at the end instead of having nodes with maximum 8 neighbours I end up having nodes with (8 * number of nodes in collection) neighbours, I have no idea what I missed here.
def evaluate_neighbours(nodes):
for node in nodes:
node.neighbours.append(n for n in nodes if n.x == node.x - 1 and n.y == node.y)
node.neighbours.append(n for n in nodes if n.x == node.x + 1 and n.y == node.y)
node.neighbours.append(n for n in nodes if n.y == node.y - 1 and n.x == node.x)
node.neighbours.append(n for n in nodes if n.y == node.y + 1 and n.x == node.x)
node.neighbours.append(n for n in nodes if n.y == node.y + 1 and n.x == node.x + 1)
node.neighbours.append(n for n in nodes if n.y == node.y + 1 and n.x == node.x - 1)
node.neighbours.append(n for n in nodes if n.x == node.x - 1 and n.y == node.y + 1)
node.neighbours.append(n for n in nodes if n.x == node.x + 1 and n.y == node.y - 1)
EDIT:
Node class and code that generates nodes is following:
class Node:
x = 0
y = 0
neighbours = []
alive = False
def __init__(self, _x, _y, _alive):
self.x = _x
self.y = _y
self.alive = _alive
def generate_grid(data):
nodes = []
for index_y, y in enumerate(data):
for index_x, x in enumerate(y):
if x == "X":
nodes.append(Node(index_x, index_y, True))
else:
nodes.append(Node(index_x, index_y, False))
return nodes