Created
December 24, 2013 22:52
-
-
Save arkadijs/8118537 to your computer and use it in GitHub Desktop.
Coderetreat: Java 8 vs Scala http://ldn.lv/events/138303652/ (Python quietly sneaks in)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
def cell_transition(alive, neighbour_count): | |
return neighbour_count in (2, 3) if alive else neighbour_count == 3 | |
class RectField(object): | |
def __init__(self, size, cells): | |
self.size = size | |
self.cells = cells | |
@classmethod | |
def empty_field(cls, size): | |
return cls(size, [0]*(size**2)) | |
def xy(self, n): | |
return n % self.size, n // self.size | |
def neighbour_indexes(self, n): | |
x, y = self.xy(n) | |
return [i + j * self.size for i, j in [ | |
(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), | |
] if 0 <= i < self.size and 0 <= j < self.size] | |
def cell_neighbours(self, n): | |
return sum(self.cells[i] for i in self.neighbour_indexes(n)) | |
def next(self): | |
next_cells = [ | |
cell_transition(cell, self.cell_neighbours(n)) | |
for n, cell in enumerate(self.cells) | |
] | |
return self.__class__(self.size, next_cells) | |
def __str__(self): | |
return ''.join( | |
('X' if cell else '.') + ('\n' if x == self.size - 1 else '') | |
for cell, x in ((cell, self.xy(n)[0]) for n, cell in enumerate(self.cells)) | |
) | |
@classmethod | |
def field_from_text(cls): | |
text = """ | |
..... | |
..X.. | |
..X.. | |
..X.. | |
..... | |
""" | |
return cls(5, [c == 'X' for c in text if c in '.X']) | |
if __name__ == "__main__": | |
field = RectField.field_from_text() | |
while True: | |
print(field) | |
time.sleep(1) | |
field = field.next() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment