livepython.net

308. Python Program to Play One Step of the Game of Life

HardPhase 3 · Challenge

This takes several steps and some care, but you know every tool it uses: split(), a list of strings, nested for loops and if. Work out Example 1 on squared paper first.

Overview

The Game of Life was made by the mathematician John Conway in 1970. Simple rules about neighbours make patterns that grow, move and die. Counting neighbours in a grid is also how many board games and image tools work.

Problem Statement

Lars wants to watch tiny patterns live and die on a grid of cells. Each cell is alive (#) or dead (.). The neighbours of a cell are the 8 cells around it: above, below, left, right and the 4 corners. Cells outside the grid count as dead.

Make the next step of the grid with these rules:

  • A live cell with 2 or 3 live neighbours stays alive.
  • A live cell with fewer than 2 live neighbours dies, because it is lonely.
  • A live cell with more than 3 live neighbours dies, because it is crowded.
  • A dead cell with exactly 3 live neighbours comes alive. Every other dead cell stays dead.

All cells change at the same time. So count the neighbours in the old grid, not in the new one. Print the new grid, one row per line, with the same size as the old one.

Examples

Example 1. Input:

5 5
.....
..#..
..#..
..#..
.....

gives:

.....
.....
.###.
.....
.....

Why: the middle cell has 2 live neighbours, so it stays alive. The top and bottom live cells have only 1, so they die. The dead cells left and right of the middle have 3 live neighbours each, so they come alive.

Example 2. Input:

3 3
###
###
###

gives:

#.#
...
#.#

Why: each corner has 3 live neighbours, so it stays alive. Each middle cell of a side has 5 and the centre has 8, so they all die.

Input

  1. The first line has two whole numbers with a space between them: the number of rows and the number of columns (1 to 20 each).
  2. Then one line for each row, from top to bottom. Each line has exactly as many characters as there are columns, each # or ., with no spaces.

Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

The new grid: the same number of rows and columns, with # and . and no spaces. The tests try 8 different inputs.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 12 · Working With Strings
solution.py
# write your code here

EXPECTED OUTPUT

1.....
2.....
3.###.
4.....
5.....

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.