Python 中的康威生命游戏 - 竞争性编程 - 如何优化
我正在解决 生命游戏问题.com/ieeextreme-practice/task/d12a7784af1a3d3f6d88601c81a4bb81/" rel="nofollow noreferrer">csacademy 并且我无法在更大的投入上击败时间。对优化代码有帮助吗?
我尝试更改一些内容,例如使用 np.array() 而不是 list,并且不将原始输入转换为 1 和 0(原始输入是“*”和“-”,需要以这种方式打印)。
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个数学解决方案似乎有助于通过更多测试,但仍有一些失败。
This mathematical solution seems to help pass more tests, but there are still a few that fail.