Reputation: 7
So I have this function called replace_elem
, written below:
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]
I want to write this function below:
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
"""
The hint was that I would use the replace_elem
twice, but what I'm wondering is that replace_elem
only takes in one index to give the location for what to replace so I'm curious as to how I could access lets say the first row and 3rd column index in python using only one subscript notation. Note I also have to return the whole board and not just the row
This isn't homework but self study as the material for this course is posted online for free and course has finished.
Upvotes: 0
Views: 982
Reputation: 1431
I believe this what you're looking for. My assumption here is an empty spot in the board will be 0.
I also had to modify your replace_elem
as you should be looking for the index and replacing that value with 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))]
examples:
board = [[0, 0],[0,0]]
row, new_board = put_piece(board, 2, 0, 'X')
print('row: %s, board: %s' %(row, new_board))
Output: 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))
Output: 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))
Output: row: -1, board: [['O', 0], ['X', 0]]
Upvotes: 1