Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- # --- read ---
- def read_file(filename: str) -> list[str]:
- chessboards = ''
- with open(filename, 'r') as file:
- for line in file:
- chessboards += line[:-1] if len(line) > 1 else ' '
- return chessboards[:-1].split(' ')
- def as_matrix(chessboard: str) -> np.array:
- rows = []
- while len(chessboard):
- rows.append(list(chessboard[:8]))
- chessboard = chessboard[8:]
- return np.array(rows)
- # --- 1 ---
- def empty_column_count(chessboard: np.array) -> int:
- counter = 0
- for column in chessboard.transpose():
- counter += 1 if len(set(column)) == 1 else 0
- return counter
- # --- 2 ---
- def check_chessboard_balance(chessboard: str) -> int:
- white = sorted(list(filter(lambda chessman: chessman.isupper(), chessboard)))
- black = sorted(list(filter(lambda chessman: chessman.islower(), chessboard)))
- black_as_capitalized = [chessman.upper() for chessman in black]
- return len(white * 2) if white == black_as_capitalized else 0
- # --- 3 ---
- def check(key):
- def checked(chessboard: np.array):
- return check_side(chessboard, key=key)
- return checked
- def check_side(chessboard: np.array, key) -> bool:
- for horizontal in chessboard:
- if check_row(horizontal.tolist(), key):
- return True
- for vertical in chessboard.transpose():
- if check_row(vertical.tolist(), key):
- return True
- return False
- def check_row(row, key) -> bool:
- king = 'K' if key == 'white' else 'k'
- rook = 'w' if key == 'white' else 'W'
- if king not in row:
- return False
- row_chessmen = [chessman for chessman in row if chessman.isalpha()]
- king_position = row_chessmen.index(king)
- if rook in row_chessmen[king_position - 1:king_position + 1]:
- return True
- # --- read ---
- data = read_file('szachy.txt')
- chessboards = list(map(as_matrix, data))
- # --- 1 ---
- empty_column_chessboards = list(filter(lambda count: count, map(empty_column_count, chessboards)))
- print('---1---')
- print(len(empty_column_chessboards))
- print(max(empty_column_chessboards))
- # --- 2 ---
- balanced_chessboards = list(filter(lambda count: count, map(check_chessboard_balance, data)))
- print('---2---')
- print(len(balanced_chessboards))
- print(min(balanced_chessboards))
- # --- 3 ---
- white_checked = check(key="white")
- black_checked = check(key="black")
- black_points = sum(list(map(white_checked, chessboards)))
- white_points = sum(list(map(black_checked, chessboards)))
- print('---3---')
- print(black_points)
- print(white_points)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement