Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Safe Pawns on Chessboard (1st solution) solution in Clear category for Pawn Brotherhood by MarHar
def safe_pawns(pawns: set) -> int:
'''
Given the locations of pawns on a chessboard, calculates how many of the pawns are protected by other pawns.
A pawn is safe if there exists a pawn in the row beneath it and the columns adjacent to it.
'''
# list of safe pawns
safe = []
# list of columns, with N/A buffering the ends to avoid errors
cols = ['N/A','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','N/A']
# go through each pawn location
for p in pawns:
# separate location into letter and number
location = (p[0], int(p[1]) )
# if pawn is on row 1, it's not safe, so skip to next
if location[1] == 1:
continue
# previous row could contain protecting pawns
# but row 1 is the first possible
goodrow = max(1, int(p[1]) - 1 )
# find index number to represent col letter in the array:
cindex = cols.index(p[0])
# the adjacent columns could contain protecting pawns
goodcols = ( cols[ cindex-1 ], cols[ cindex+1 ] )
# possible protecting pawn locations (by combining data from goodrow & goodcols)
protectors = ( goodcols[0] + str(goodrow), goodcols[1] + str(goodrow) )
# if a protecting pawn exists, add this pawn to the safe list.
if protectors[0] in pawns or protectors[1] in pawns:
safe.append(p)
print(f"{len(safe)} pawns are safe.")
# return number of safe pawns
return len(safe)
print("Example:")
print(safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}))
assert safe_pawns({"d2", "f4", "d4", "b4", "e3", "g5", "c3"}) == 6
assert safe_pawns({"f4", "g4", "d4", "b4", "e4", "e5", "c4"}) == 1
print("The mission is done! Click 'Check Solution' to earn rewards!")
Oct. 28, 2023
Comments: