2013 09 01
This was done under the following constraints:
Make it somewhat modular and readable. This meant not being able to stick everything inside the main loop.
Use (and abuse) as many Python features as possible.
Allow it to receive the initial state from the standard UNIX console.
Have it pass PEP8.
Here it is, just under 40 lines including whitespace:
Some things I learned while doing this:
itertools.productcan save a few nested loops.
Lambdas can be defined as class properties, effectively turning them into methods. This works even for magic methods, which is surprisingly acceptable within PEP8.
The whole transition logic for each cell can be reduced into
neighbors == 3 or is_alive and neighbors == 2.
The list multiplication syntax will create references and not copies of the lists if they are nested. For example, I tried doing the following to create the empty board:
[[False] * w] * h
And while that seemed to work initially, it took me a while to realize that every instance of
[[False] * w] was a reference to the same list. I had to settle for the somewhat dirtier approach of using list comprehension for the outer dimension of the matrix.
A simple test for the script (with just one glider) can be run with the following command:
$ printf "010\n001\n111" | python gameoflife.py