彼得诺维格的生命游戏

Peter Norvig's Game of Life

我在看这段代码 Peter Norvig's Game of Life implementation 当我注意到这一点时:

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)}

使用 counts 而不是 possible_cells 的原因是什么?

Norvig 解释 in the comments(紧接在 IPython 单元格 In [1] 中的代码上方):

Note that in next_generation the neighbor_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, and counts is used to check if a cell has the right number of neighbors.