'identity test game of life
I'm writing the conway's game code in python. My code is like this:
def update_board(board: list[list[int]]) -> list[list[int]]:
rows = len(board)
cols = len(board[0])
count = 0
copy_board = deepcopy(board)
indx = [-1, -1, -1, 0, 0, 1, 1, 1]
indy = [-1, 0, 1, -1, 1, -1, 0, 1]
for i in range(rows):
for j in range(cols):
for k, value in enumerate(indx):
if check(i + value, j + indy[k], rows,
cols) and copy_board[i + indx[k]][j + indy[k]]:
count += 1
# Apply the rule to each cell
if count < 2 or count > 3:
board[i][j] = 0
elif count == 3:
board[i][j] = 1
# Reset the count for the next cell
count = 0
return board
It need to pass through the identity test:
def test_is_not_identity() -> None:
"""Test board update is not done in place."""
board = [[0 for _ in range(4)] for _ in range(4)]
assert board is not update_board(board)
and the stills test (I don't know what it does):
def test_stills(name: str, proto: str) -> None:
"""Test still lifes."""
board = parse_board(proto)
assert board == update_board(deepcopy(board)), name
but it doesn't pass although I updated the board in place so I don't understand.
Solution 1:[1]
You should return the copy_board
instead of board
. Also moodify copy_booard
instead of board
itself
def update_board(board: list[list[int]]) -> list[list[int]]:
rows = len(board)
cols = len(board[0])
count = 0
copy_board = deepcopy(board)
indx = [-1, -1, -1, 0, 0, 1, 1, 1]
indy = [-1, 0, 1, -1, 1, -1, 0, 1]
for i in range(rows):
for j in range(cols):
for k, value in enumerate(indx):
if check(i + value, j + indy[k], rows,
cols) and board[i + indx[k]][j + indy[k]]:
count += 1
# Apply the rule to each cell
if count < 2 or count > 3:
copy_board[i][j] = 0
elif count == 3:
copy_board[i][j] = 1
# Reset the count for the next cell
count = 0
return copy_board
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ymmx |