Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
pylint approved solution in Clear category for Pawn Brotherhood by kkkkk
# Possible letters for chess file positions. The numerical equivalent
# for a file can be determined by its index into the string below.
FILE_LETTERS = 'abcdefgh'
def protectors(location_str):
""" Find the pawn positions that protect the given location.
Protectors are located behind the pawn and to the left
or right.
"""
# Convert the incoming location string into numerical rank and file.
file_pos = FILE_LETTERS.index(location_str[0])
rank_pos = int(location_str[1])
safe_locs = []
# The pawn has protectors if it's not in the first rank and
# on the extreme left or right of the board.
if not (rank_pos == 1):
rank_pos -= 1
if file_pos > 0:
safe_locs.append(FILE_LETTERS[file_pos - 1] + str(rank_pos))
if file_pos < 7:
safe_locs.append(FILE_LETTERS[file_pos + 1] + str(rank_pos))
return safe_locs
def safe_pawns(pawn_set):
""" Count the number of pawns that are protected by other pawns.
For each pawn in the given pawn_set, determine it's possible
protectors and check whether those protectors exist. If they
do, that pawn is safe and the count of safe pawns is incremented.
"""
safe_cnt = 0
for pawn_loc in pawn_set:
safe_locs = protectors(pawn_loc)
if any(loc in pawn_set for loc in safe_locs):
safe_cnt += 1
return safe_cnt
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6
assert safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1
Aug. 5, 2014
Comments: