I have this interpretation of John Conway's Game of Life in Python 3.3.1:
#JOHN CONWAY'S GAME OF LIFE
def countSurrounding(universe, a, b):
count = 0
surrounding = [[a - 1, b - 1],
[a - 1, b ],
[a - 1, b + 1],
[a , b - 1],
[a , b + 1],
[a + 1, b - 1],
[a + 1, b ],
[a + 1, b + 1]]
for a in range(0, 8):
try:
if universe[surrounding[a][0]][surrounding[a][1]] == 1:
count += 1
except IndexError: a
return count
def printUniverse(universe):
for a in universe:
print(a)
print("\n")
nextUniverse = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
for gen in range(0, 10):
universe = [a[:] for a in nextUniverse]
printUniverse(universe)
for a in range(0, 9):
for b in range(0, 9):
if universe[a][b] == 0 and countSurrounding(universe, a, b) == 3:
nextUniverse[a][b] = 1
elif universe[a][b] == 1 and countSurrounding(universe, a, b) not in (2, 3):
nextUniverse[a][b] = 0
How can I improve/optimize my code?
EDIT: After the answers below, I have updated my code:
#JOHN CONWAY'S GAME OF LIFE
def countSurrounding(universe, a, b):
count = 0
surrounding = ((a - 1, b - 1),
(a - 1, b ),
(a - 1, b + 1),
(a , b - 1),
(a , b + 1),
(a + 1, b - 1),
(a + 1, b ),
(a + 1, b + 1))
for a, b in surrounding:
if not(a < 0 or b < 0 or a >= len(universe) or b >= len(universe[a])) and universe[a][b]:
count += 1
return count
def printUniverse(universe):
for a in universe:
print(a)
print("\n")
nextUniverse = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
for gen in range(0, 10):
universe = [a[:] for a in nextUniverse]
printUniverse(universe)
for a in range(0, len(universe)):
for b in range(0, len(universe[a])):
if universe[a][b] == 0 and countSurrounding(universe, a, b) == 3:
nextUniverse[a][b] = 1
elif universe[a][b] == 1 and countSurrounding(universe, a, b) not in (2, 3):
nextUniverse[a][b] = 0
Any more improvements to be made? So far I have:
- Introduced a check in
countSurrounding
to replace theexcept IndexError
, so that the board does not wrap. - Made
surrounding
a tuple instead of a list - Changed
for a in range(0, 9)
tofor a in range(0, len(universe))
, as I assume that is more pythonic