i was looking at this code Peter Norvig's Game of Life implementation when i noticed this:
def next_generation(world):
"The set of live cells in the next generation."
possible_cells = counts = neighbor_counts(world)
return {cell for cell in possible_cells
if (counts[cell] == 3)
or (counts[cell] == 2 and cell in world)}
What is the reason to use counts
instead of possible_cells
?
Norvig explains in the comments (immediately above the code in the IPython cell In [1]
):
Note that in
next_generation
theneighbor_counts
is used two ways so I decided to use two different names for clarity:possible_cells
is used to iterate over all cells that might be live, andcounts
is used to check if a cell has the right number of neighbors.