Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Pawn Brotherhood by donnythelegend
def safe_pawns(pawns: set) -> int:
# Initialize empty list for coordinates.
coords = []
# Initialize counter variable safe.
safe = 0
# Loop through pawns.
for i in pawns:
# Append coordinate values to coords.
# The first element of each string in pawns is the column, and the second is the row.
# We convert this into a list of [row (int), column (int)] elements for easy manipultion.
# The ord() values for chars 'a', 'b', ..., 'h' is 97, 98, ... 104
# Subtracting 96 makes them 1, 2, ..., 8, which matches the row coordinate values.
# Note that the same solution can be reached without the subtraction,
# but it makes it a bit more convenient to work with.
coords.append([int(i[1]), ord(i[0]) - 96])
# Loop through coords.
for c in coords:
# There are two scenarios that the task considers to be safe:
# - There is a pawn one row behind, and one column to the left.
# - There is a pawn one row behind, and one column to the right.
# Check for these scenarios, and add 1 to safe if True.
if ([c[0] - 1, c[1] - 1] in coords) or ([c[0] - 1, c[1] + 1] in coords):
safe += 1
# Return safe.
return safe
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
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
April 20, 2021
Comments: