Brief introduction: so the point of the question is that the author doesn't really talk about good or bad code quality and I really wanted some feedback to have a grasp of how the code for others to read should look like. I mean, for the very first solution of the task I would check different parameters manually just to finish it and the function looked really bulky, so I took some time to make it neat.
Task: the dictionary value represent a chess board, for example {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'}. Write a function named that takes a dictionary argument and returns True or False depending on if the board is valid.
A valid board will have exactly one black king and exactly one white king. Each player can only have at most 16 pieces, at most 8 pawns, and all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'. The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'. This function should detect when a bug has resulted in an improper chess board.
My solution:
def chessboardCheck(board):
piecesDict={'pawn':8,'knight':2,'bishop':2,'rook':2,'queen':1,'king':1} #to count pieces on the board
if list(board.values()).count('wking')!=1 or list(board.values()).count('bking')!=1: #kings check
print('The board is invalid: kings requirement not met.')
return False
for piece in board.values():
if piece[0] not in 'wb': #piece color
print('The board is invalid: improper color reference.')
return False
elif piece[1:] not in piecesDict.keys(): #piece type
print('The board is invalid: improper piece reference.')
return False
elif list(board.values()).count(piece) > piecesDict.get(piece[1:]): #pieces count
print('The board is invalid: improper pieces count.')
return False
for cell in board: #axis correctness
if cell[0] not in '12345678' or cell[1] not in 'abcdefgh':
print('The board is invalid: improper cell reference.')
return False
print('All checks are clear: the board is valid.')
return True
This is the least lines I could come up with, but if there are more shortcuts to take, please do not hesitate to point! Also I would like to hear opinions on introducing variables: I tried to avoid them wherever I knew how, but maybe it's not always the way to go? Thanks!