It's a few weeks old homework, and it's already graded. How can I improve my code?
empty(n), which gets the board size as an argument, and returns an empty board with the given size. For instance, empty(4) must return
['', '', '', ''].
Trueif the given board is empty and
Falseif it's not.
inSeries(board)that returns a string representation of the given board. Call
inSeries([' ', 'a', '', '', '', 'x', 'x', 'x', '', 'y', 'y', '', ''])must return
' a xxx yy '.
space(board, position, length), which returns
Trueif a ship of the given length can be put (starting) at the position on the given (possibly already non-empty) board. If not, the function returns
False. Ships must not touch each other (but the can touch the border of the board).
placed(board, position, length, label), which puts the ship with the given label and the given length at the given position on the board -- if this is possible -- and returns
True. If putting the ship at this position is illegal, the function returns
exists(board, label)that return
Trueif there is a ship with the given label on the board, and
Falseif there's not.
allTags(board)that return a list of labels of all ships on the board. The labels can be in arbitrary order. Call
allTags(['a', '', 'x', 'x', 'x', '', 'y', 'y', '', ''])can return, for instance,
['y', 'a', 'x'].
shot(board, position), which simulates targeting the given position on the board. The function returns
0, in case of a miss,
1, if a ship is hit, but not yet completely sunk,
2, if the ship is sunk (e.g. the player hit the last piece of the ship), but the game is not over yet,
3, if the last piece of the last ship is sunk and the game is over. Besides, the function must of course update the state of the board.
This is my code, working:
def empty(n): return ['']*n def isEmpty(board): return all(a=='' for a in board) def inSeries(board): board = map(lambda x:x if x!= '' else ' ',board) return "".join(board) def space(board, position, lenght): a=False if board[position] == '' and isEmpty(board[position:position+lenght+1]) and len(board) >= position+lenght: a=True if position+lenght+1 < len(board) and board[lenght+position] != '': return False if position != 0 and board[position-1] != '': return False return a def placed(board, position, lenght, label): if space(board, position, lenght): for i in range(lenght): board[position+i] = label return True else: return False def exists(board, label): return label in inSeries(board) def allTags(board): return list(set("".join(board))) def shot(board, position): if board[position] == '': return 0 elif board[position] != '' and board.count(board[position]) ==1 and len(allTags(board)) >1: board[position] = '' return 2 elif board[position] != '' and board.count(board[position]) >1: board[position] = '' return 1 else: board[position] ='' return 3