Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Chess Knight by PythonLearner
from itertools import chain
from typing import Iterable
Coordinate = tuple[int, int]
LETTERS = {i+1: letter for i, letter in enumerate("abcdefgh")}
NUMBERS = {letter: i for i, letter in LETTERS.items()}
CHESSBOARD_SIZE = 8
POSITION_DELTAS = ((-2, -1), (-2, 1), (2, -1), (2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2))
def translate_chess(position: str) -> Coordinate:
return NUMBERS[position[0]], int(position[1])
def translate_coordinate(position: Coordinate) -> str:
return f"{LETTERS[position[0]]}{position[1]}"
def generate_moves(start: Coordinate) -> Iterable[Coordinate]:
x, y = start
return ((x+delta_x, y+delta_y) for delta_x, delta_y in POSITION_DELTAS)
def is_valid_position(position: Coordinate) -> bool:
x, y = position
return 1 <= x <= CHESSBOARD_SIZE and 1 <= y <= CHESSBOARD_SIZE
def coordinate_chess_knight(start: Coordinate, moves: int) -> set[Coordinate]:
positions = set(filter(is_valid_position, generate_moves(start)))
if moves > 1:
positions.update(chain(*(coordinate_chess_knight(position, moves-1) for position in positions)))
return positions
def chess_knight(start: str, moves: int) -> list[str]:
return sorted(map(translate_coordinate, coordinate_chess_knight(translate_chess(start), moves)))
if __name__ == '__main__':
print("Example:")
print(chess_knight('a1', 1))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert chess_knight('a1', 1) == ['b3', 'c2']
assert chess_knight('h8', 2) == ['d6', 'd8', 'e5', 'e7', 'f4', 'f7', 'f8', 'g5', 'g6', 'h4', 'h6', 'h8']
print("Coding complete? Click 'Check' to earn cool rewards!")
Nov. 22, 2021
Comments: