It's a few weeks old homework, and it's already graded. How can I improve my code?
Write function
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['', '', '', '']
.Write function
isEmpty(board)
returnsTrue
if the given board is empty andFalse
if it's not.Write function
inSeries(board)
that returns a string representation of the given board. CallinSeries([' ', 'a', '', '', '', 'x', 'x', 'x', '', 'y', 'y', '', ''])
must return' a xxx yy '
.Write function
space(board, position, length)
, which returnsTrue
if 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 returnsFalse
. Ships must not touch each other (but the can touch the border of the board).Write function
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 returnsTrue
. If putting the ship at this position is illegal, the function returnsFalse
.Write function
exists(board, label)
that returnTrue
if there is a ship with the given label on the board, andFalse
if there's not.Write function
allTags(board)
that return a list of labels of all ships on the board. The labels can be in arbitrary order. CallallTags(['a', '', 'x', 'x', 'x', '', 'y', 'y', '', ''])
can return, for instance,['y', 'a', 'x']
.Write function
shot(board, position)
, which simulates targeting the given position on the board. The function returns0
, 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