Skip to content

Commit 5c0a5c4

Browse files
committed
optimized life.py for CPython, ended up slowing it down a little for PyPy...
1 parent 7494db9 commit 5c0a5c4

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

examples/life.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,20 @@ def clear(self):
3939
def toggle(self, x, y):
4040
self.live_cells.symmetric_difference_update([(x, y)])
4141

42+
def wrap_edges(self):
43+
for x in range(-1, self.width + 1):
44+
self.set(x, -1, self.get(x, -1))
45+
self.set(x, self.height, self.get(x, self.height))
46+
for y in range(self.height):
47+
self.set(-1, y, self.get(-1, y))
48+
self.set(self.width, y, self.get(self.width, y))
49+
4250

4351
def get_neighbours(self, x, y):
44-
count = 0
45-
for neighbour_x in [-1, 0, 1]:
46-
for neighbour_y in [-1, 0, 1]:
47-
if 0 == neighbour_x == neighbour_y:
48-
continue
49-
count += self.get(x + neighbour_x, y + neighbour_y)
50-
return count
52+
return len(self.live_cells & {(x - 1, y - 1), (x, y - 1),
53+
(x + 1,y - 1), (x + 1, y),
54+
(x + 1, y + 1), (x, y + 1),
55+
(x - 1, y + 1), (x - 1, y)})
5156

5257
def rule(self, is_alive, neighbours):
5358
"""
@@ -66,7 +71,7 @@ def rule(self, is_alive, neighbours):
6671
return neighbours == 3
6772

6873
def step(self):
69-
74+
self.wrap_edges()
7075
next_generation = set()
7176
for x in range(self.width):
7277
for y in range(self.height):

0 commit comments

Comments
 (0)