'Conway's Game of Life in Python - Competitive Programming - how to optimize
I am solving Game of Life problem on csacademy and I can't manage to beat the time on larger inputs. Any help on optimizing the code?
I tried changing things, like using np.array() instead of list, and not converting the original input to 1s and 0s (original is '*' and '-', and needs to be printed that way).
from copy import deepcopy
import numpy as np
aliveToDead = {0, 1, 4, 5, 6, 7, 8}
deadToAlive = {3}
def countNeighbors(M, n, m, i, j):
s = M[i, (j + 1) % m] + M[i, j - 1] + M[(i + 1) % n, j] + M[i - 1, j]
s += M[i - 1, j - 1] + M[(i + 1) % n, (j + 1) % m] + M[i - 1, (j + 1) % m] + M[(i + 1) % n, j - 1]
return s
def gameOfLife(mat, n, m, C):
cells = deepcopy(mat)
for c in range(C):
for i in range(n):
for j in range(m):
neighbors = countNeighbors(mat, n, m, i, j)
if mat[i, j] == 1 and neighbors in aliveToDead:
cells[i, j] = 0
elif mat[i, j] == 0 and neighbors in deadToAlive:
cells[i, j] = 1
mat = deepcopy(cells)
return mat
def buildList(n):
return np.array([[0 if x == '-' else 1 for x in input()] for i in range(n)])
def printResult(mat):
mat = mat.astype(str)
mat[mat == "1"] = '*'
mat[mat == "0"] = '-'
for row in mat:
print(*row, sep="")
def main():
n, m, c = map(int, input().split())
mat = buildList(n)
result = gameOfLife(mat, n, m, c)
printResult(result)
if __name__ == "__main__":
main()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
