所以我必须用5条规则来做康威的生命游戏:
示例:
>>> A = [ [0,0,0,0,0],
[0,0,1,0,0],
[0,0,1,0,0],
[0,0,1,0,0],
[0,0,0,0,0]]
>>> printBoard(A)
00000
00100
00100
00100
00000
>>> A2 = next_life_generation( A )
>>> printBoard(A2)
00000
00000
01110
00000
00000
>>> A3 = next_life_generation( A2 )
>>> printBoard(A3)
00000
00100
00100
00100
00000
and so on... .
注意,next_life_generation(A)返回一个新的板,所以我可以继续将A重新绑定到每一代 到目前为止,这是我的代码:
def countNeighbors(row, col, A):
count = 0
for row in range(len(A) - 1, len(A) + 2):
for col in range(len(A) - 1, len(A) + 2):
if A[row][col] == 1:
count += 1
return count
def next_life_generation(A):
for row in range(1, len(A) - 1):
for col in range(1, len(A[0]) - 1):
if A[row][col] == 0 and countNeighbors(row, col, A) == 3:
A[row][col] = 1
if countNeighbors(row, col, A) < 2:
A[row][col] = 0
elif countNeighbors(row, col, A) > 3:
A[row][col] = 0
return A
我的问题是我得到了这个错误:
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
A = next_life_generation(A)
line 88, in next_life_generation
if countNeighbors(row, col, A) < 2:
line 79, in countNeighbors
if A[row][col] == 1:
IndexError: list index out of range
如果有人能帮助我,我将不胜感激!