所以我有一个名为replace_elem
的函数,如下所示:
def replace_elem(lst, index, elem):
"""Create and return a new list whose elements are the same as those in
LST except at index INDEX, which should contain element ELEM instead.
>>> old = [1, 2, 3, 4, 5, 6, 7]
>>> new = replace_elem(old, 2, 8)
>>> new
[1, 2, 8, 4, 5, 6, 7]
>>> new is old # check that replace_elem outputs a new list
False
"""
assert index >= 0 and index < len(lst), 'Index is out of bounds'
return [elem if i == lst[index] else i for i in lst]
我想在下面写这个函数:
def put_piece(board, max_rows, column, player):
"""Puts PLAYER's piece in the bottommost empty spot in the given column of
the board. Returns a tuple of two elements:
1. The index of the row the piece ends up in, or -1 if the column
is full.
2. The new board
>>> rows, columns = 2, 2
>>> board = create_board(rows, columns)
>>> row, new_board = put_piece(board, rows, 0, 'X')
>>> row
1
>>> row, new_board = put_piece(new_board, rows, 0, 'O')
>>> row
0
>>> row, new_board = put_piece(new_board, rows, 0, 'X')
>>> row
-1
"""
提示是我会使用replace_elem
两次,但我想知道的是replace_elem
只接受一个索引来给出替换内容的位置所以我很好奇我怎么可以访问让我们说python中的第一行和第三列索引只使用一个下标符号。注意我还必须返回整个板而不仅仅是行
这不是家庭作业,而是作为本课程材料的自学,免费在线发布,课程已经完成。
答案 0 :(得分:1)
我相信你正在寻找的东西。我在这里的假设是董事会中的空位为0。
我还必须修改你的replace_elem
,因为你应该寻找索引并用elem替换该值。
def replace_elem(lst, index, elem):
assert index >= 0 and index < len(lst), 'Index out of bounds'
return [elem if i == index else lst[i] for i in range(len(lst))]
def put_piece(board, max_rows, column, player):
# return the column in board
board_col = list(map(lambda x: x[column], board))
try:
# find an the last empty element - empty == 0
row = len(board_col) - board_col[::-1].index(0) - 1
except ValueError:
return -1, board
new_col = replace_elem(board_col, row, player)
return row, [[board[r][c] if c != column else new_col[r] for c in range(len(board[r]))] for r in range(len(board))]
的示例:
board = [[0, 0],[0,0]]
row, new_board = put_piece(board, 2, 0, 'X')
print('row: %s, board: %s' %(row, new_board))
输出:row: 1, board: [[0, 0], ['X', 0]]
row, new_board = put_piece(new_board, 2, 0, 'O')
print('row: %s, board: %s' %(row, new_board))
输出:row: 0, board: [['O', 0], ['X', 0]]
row, new_board = put_piece(new_board, 2, 0, 'X')
print('row: %s, board: %s' %(row, new_board))
输出:row: -1, board: [['O', 0], ['X', 0]]