If Statements (Part 1)
Three years ago, a hackathon changed my life.
Well, it influenced my coding philosophy anyway.
The rules of the hackathon were this: Work with a partner to write Conway's Game of Life in an hour in some language / framework. Then, at the end of the hour, throw away your work, and start over with a new partner / language / framework. All in all, we wrote Game of Life seven times in a day.
It turns out, once you've practiced it a couple times, writing the Game of Life in an hour is pretty doable. So, as the day went on, various extra challenges arose, like: Write it in haskell, write it in the web, write it in python..... with no if statements.
That one appealed to me. Python with no if-statements.
I managed to write it. This is the code. (I'm posting in flagrant violation of the rules of the hackathon)
class Game:
def __init__(self):
self.cells = []
def neighbors(self, cell):
x, y = cell
return [(x-1, y-1), (x, y-1), (x+1, y-1), (x-1, y),
(x+1, y), (x-1,y+1), (x, y+1), (x+1, y+1)]
def next(self):
neighbor_count = {}
for center in self.cells:
for cell in self.neighbors(center):
neighbor_count[cell] =
neighbor_count.get(cell, 0) + 1
def alive(cell):
n = neighbor_count[cell]
return n == 3 or (cell in self.cells and n == 2)
self.cells = list(set(filter(alive, self.cells +
reduce(list.__add__, map(self.neighbors, self.cells)))))
def __repr__(self):
return repr(self.cells)
You can try it at the command line. Here's how you make the classic glider:
>>> g = Game([(0,0), (1,0), (2,0), (2,1), (1,2)])
Then type this over and over, and you'll see the glider move:
>>> g.next(); g
Anyway, Game of Life aside, I want you to try this. Try to figure out how to rewrite your code, whatever it is, without if statements. You might learn something. I did.