Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Deviating from hint-like beginnings. solution in Clear category for Pawn Brotherhood by tigercat2000
def safe_pawns(pawns):
# Initialize an empty set that will contain coordinate pairs of our pawns.
pawn_indexes = set()
# Iterate through the pawn coordinate sets.
for p in pawns:
# ... and decode them into x,y coordinates, instead of letter,number.
# The rows are already a usable integer in a string, but they need to be made 0-indexed.
row = int(p[1]) - 1
# The columns are refered to by a letter coordinate. Convert the letter into ascii and subtract 97 to get the number it's refering to.
col = ord(p[0]) - 97
# Add the determined row and column to our pawn index set.
pawn_indexes.add((row, col))
# Initialize count of safe pawns at 0. Nobody is safe until we check them.
count = 0
# Iterate through our pawns, getting both a row and column in the loop.
for row, col in pawn_indexes:
# Use a tuple for backup positions.
safe_places = ((row - 1, col - 1),
(row - 1, col + 1))
# Initialize a variable called is_safe as False for this loop iteration.
is_safe = False
# Loop through coordinate tuples inside of our backup position tuple.
for coords in safe_places:
# Check if the coordinate is one in our established pawn locations.
if coords in pawn_indexes:
# If it is, the pawn is 'safe', so mark the is_safe variable as True.
is_safe = True
# And exit the for..in loop early with a break, we don't need to make sure every position is covered, just one.
break
# Check if they were determined as safe in our backup position tuple.
if is_safe:
# If they were, increase the count of safe pawns.
count += 1
return count
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
Nov. 5, 2016