why does this code return the value false?
It should return false only if one of the pieces exceeds it’s max total or if the king pieces are missing, a loop at the end prints the sum for each piece and none of them have exceeded the max limit. But for some reason it still returns false…..
chessboard = {
'1h': 'bking',
'6c': 'wqueen',
'2g': 'bbishop',
'5h': 'bqueen',
'3e': 'wking',
'4c': 'brook',
}
def check_validity(board):
if sum(value == 'wpawn' or value == 'bpawn' for value in board.values()) > 8:
return False
elif sum(value == 'wknight' or value == 'bknight' or value == 'bbishop' or value == 'wbishop' or value == 'wrook' or value == 'brook' for value in board.values()) > 2:
return False
elif sum(value == 'wqueen' or value == 'bqueen' for value in board.values()) > 1:
return False
elif sum(value == 'wking' or value == 'bking' for value in board.values()) != 1:
return False
elif sum(value == b or value == w for value in board.values[0]) > 16:
return False
else:
return True
print(check_validity(chessboard))
for key, values in chessboard.items():
print(values, sum(value == values for value in chessboard.values()))
output:
False
bking 1
wqueen 1
bbishop 1
bqueen 1
wking 1
brook 1
>Solution :
Each of your sums count several types of pieces, then see if the count is higher than the max of each individual one of those pieces. In your example the sum for the kings would return 2, which is higher than 1 so the function would return false. Try this:
def check_validity(board):
pieces = ['wpawn', 'bpawn', 'wknight', 'bknight', 'bbishop', 'wbishop', 'wrook', 'brook', 'wqueen', 'bqueen', 'wking', 'bking']
max_pieces = [8, 8, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1]
for piece in zip(pieces, max_pieces):
if sum(value == piece[0] for value in board.values()) > piece[1]:
return False
return True