Conway Game of Life in a single line of Python

posted on 2021-11-29T19:49:26Z · view page on GitHub

On Wikipedia, Conway's game of life is described as a 2D grid of cells for which:

1. Any live cell with fewer than two live neighbours dies, as if by underpopulation.
2. Any live cell with two or three live neighbours lives on to the next generation.
3. Any live cell with more than three live neighbours dies, as if by overpopulation.
4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

This is simple enough. Let's implement this in a single line of python. More specifically, we'll be able to represent the game as a single generator expression. This is possible since the introduction of the Walrus Operator :=.

Anyway... Not sure why I did this:

Conway Game of life function¶

In [2]:
game_of_life = lambda initial_cells, num_steps: (cells := (set(initial_cells) if i == 0 else (cells.difference({(x, y) for (x, y) in cells if not 1 < len([(x + i, y + j) for i in (-1, 0, 1) for j in (-1, 0, 1) if (not i == j == 0 and (x + i, y + j) in cells)]) < 4 }).union({(x_, y_) for (x, y) in cells for (x_, y_) in ((x + i, y + j) for i in (-1, 0, 1) for j in (-1, 0, 1) if (not i == j == 0 and (x + i, y + j) not in cells)) if len([(x_ + i, y_ + j) for i in (-1, 0, 1) for j in (-1, 0, 1) if (not i == j == 0 and (x_ + i, y_ + j) in cells)]) == 3 }))) for i in range(num_steps))


Visualize¶

In [3]:
X, Y = np.mgrid[0:50, 0:50]
grid = np.zeros_like(X, dtype=int)

initial_cells = {(2, 2), (2, 1), (2, 0), (1, 0), (0, 1)}
num_steps = 120
for cells in game_of_life(initial_cells, num_steps):
clear_output(wait=True)
grid[:, :] = 0
for x, y in cells:
grid[x, -y] = 1
plt.figure(figsize=(5, 5))
plt.axis('scaled')
p = plt.pcolormesh(X, Y, grid, cmap="Greys")
plt.xticks(X[:,0]+0.5, ["" for _ in X[:, 0]])
plt.yticks(Y[0,:]+0.5, ["" for _ in Y[0, :]])
plt.grid(True)
plt.show()


If you like this post, consider leaving a comment or star it on GitHub.