Skip to content

Instantly share code, notes, and snippets.

@bmispelon
Created May 29, 2012 17:11
Show Gist options
  • Select an option

  • Save bmispelon/2829570 to your computer and use it in GitHub Desktop.

Select an option

Save bmispelon/2829570 to your computer and use it in GitHub Desktop.
Binary matrices
from collections import MutableMapping
class BinMatrix(MutableMapping):
def __init__(self, width, height):
self.width = width
self.height = height
self.ALIVE = 1
self.DEAD = 0
self._set = set()
def __getitem__(self, (x, y)):
return self.ALIVE if (x, y) in self._set else self.DEAD
def __setitem__(self, (x, y), value):
if value:
self._set.add((x, y))
else:
self._set.discard((x, y))
def __delitem__(self, (x, y)):
self._set.discard((x, y))
def __len__(self):
return self.width * self.height
def __iter__(self):
for x in self.columns():
for y in self.rows():
yield (x, y)
def rows(self):
return xrange(self.height)
def columns(self):
return xrange(self.width)
def rows_items(self):
for y in self.rows():
yield (y, (self[(x, y)] for x in self.columns()))
def rows_values(self):
for _, v in self.rows_items():
yield v
def columns_items(self):
for x in self.columns():
yield (x, (self[(x, y)] for y in self.columns()))
def columns_values(self):
for _, v in self.columns_items():
yield v
def neighbors(self, (x, y)):
pass # TODO
def neighbors_items(self, (x, y)):
for u, v in self.neighbors((x, y)):
yield self[(u, v)]
def neighbors_values(self, (x, y)):
for _, v in self.neighbors_items((x, y)):
yield v
def display(self, char_alive='X', char_dead='.'):
d = {self.ALIVE: char_alive, self.DEAD: char_dead}
return '\n'.join(
''.join(d[cell] for cell in row) for row in self.rows_values()
)
def __str__(self):
return self.display()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment