• 1
    Input and Output Data
    • Tasks
  • 2
    Conditions
    • Tasks
  • 3
    For Loop
    • Tasks
  • 4
    Strings
    • Tasks
  • 5
    While Loop
    • Tasks
  • 6
    Lists
    • Tasks
  • 7
    Two-Dimensional Arrays
    • Tasks
  • 8
    Dictionaries
    • Tasks
  • 9
    Sets
    • Tasks
  • 10
    Functions and Recursion
    • Tasks
  • к

Занятие 6. Lists

Difficulty level:

Task«Blowing the ferze»

You are a grandmaster and you need to write a program that receives the coordinates of the eight fereze on the input on the standard chessboard 8 & Times; 8 and conducts a complete analysis of their arrangement.

Input format

Eight lines, each of which contains two integers from 1 to 8, separated by a gap & mdash; The coordinates of one queen (first line number, then column number).

Output format

rn
    rn
  • script 1: The attack is discovered.
    If at least one pair of ferose beats each other, the program should be: Rn
      RN
    1. yes .
    2. rn
    3. on the next line indicate the coordinates of the first attacked pair and type of attack. For example: 1 1 and 8 8 beat each other diagonally.
    4. rn
    5. After that, draw the chessboard 8 & Times; 8 with the arranged ferry.
    6. rn rn
    7. script 2: no.
      If not a single pair It hits each other (the arrangement is correct), the program should: rn
        rn
      1. display the word & nbsp; no
      2. rn
      3. after that to draw chessboard 8 & Times; 8 with the placed Ferzy.
      4. rn rn rn
      5. Board visualization:
        The board should be presented in the form of a 8x8 grid. Empty cells are indicated by the symbol & nbsp; . symbol q.
      6. rn
rn

Example

Input

1 1
2 3
3 5
4 7
5 2
6 4
7 6
8 8

Output

Yes
1 1 and 8 8 beat each other diagonally.
Q. . . . . . .
. . Q. . . . .
. . . . Q. . .
. . . . . . Q.
. Q. . . . . .
. . . Q. . . .
. . . . . Q. .
. . . . . . . Q

Hint

There will be no clue here, decide for yourself!

main.py
Test 1
Test 2
Test 3
Test 4
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
Developer’s solution
def read_and_validate_coordinates():
    """
    Считывает 8 пар координат, проверяет их на корректность.
    Возвращает список кортежей с координатами или None в случае ошибки.
    """
    coords = []
    try:
        for _ in range(8):
            # Считываем строку и разделяем на части
            parts = input().split()
            # Проверяем, что в строке ровно два элемента
            if len(parts) != 2:
                raise ValueError
            # Преобразуем в целые числа
            row, col = int(parts[0]), int(parts[1])
            # Проверяем, что координаты в диапазоне от 1 до 8
            if not (1 <= row <= 8 and 1 <= col <= 8):
                raise ValueError
            coords.append((row, col))
    except (ValueError, IndexError):
        # ValueError возникает при неудачном int() или если условия не выполнены
        # IndexError может возникнуть, если split() дал меньше 2 элементов (хотя len(parts) это покрывает)
        return None
    return coords

def find_attacking_pair(coords):
    """
    Ищет первую атакующую пару ферзей.
    Возвращает кортеж (queen1, queen2, attack_type) или None, если атак нет.
    """
    # Проверка на дубликаты координат (ферзи на одной клетке)
    if len(coords) != len(set(coords)):
        # Найдем первую дублирующуюся пару
        seen = set()
        duplicate = None
        for q in coords:
            if q in seen:
                duplicate = q
                break
            seen.add(q)
        
        # Найдем индексы дубликатов
        indices = [i for i, x in enumerate(coords) if x == duplicate]
        q1 = coords[indices[0]]
        q2 = coords[indices[1]]
        # Ферзи на одной клетке - это и горизонтальная, и вертикальная атака.
        # Выберем "вертикали" для определенности.
        return q1, q2, "вертикали"

    # Проверяем все уникальные пары ферзей
    for i in range(len(coords)):
        for j in range(i + 1, len(coords)):
            r1, c1 = coords[i]
            r2, c2 = coords[j]

            # Проверка по горизонтали
            if r1 == r2:
                return coords[i], coords[j], "горизонтали"
            
            # Проверка по вертикали
            if c1 == c2:
                return coords[i], coords[j], "вертикали"
            
            # Проверка по диагонали
            if abs(r1 - r2) == abs(c1 - c2):
                return coords[i], coords[j], "диагонали"
                
    return None, None, None

def print_board(coords):
    """
    Печатает шахматную доску 8x8 с расставленными ферзями.
    """
    board = [['.' for _ in range(8)] for _ in range(8)]
    for r, c in coords:
        # Координаты (1,1) соответствуют индексу [0][0]
        board[r - 1][c - 1] = 'Q'
    
    for row in board:
        print(' '.join(row))

def main():
    """
    Главная функция программы.
    """
    coordinates = read_and_validate_coordinates()
    
    if coordinates is None:
        print("Ошибка: координаты должны быть числами от 1 до 8.")
        return
        
    q1, q2, attack_type = find_attacking_pair(coordinates)
    
    if attack_type:
        print("YES")
        print(f"{q1[0]} {q1[1]} и {q2[0]} {q2[1]} бьют друг друга по {attack_type}.")
        print_board(coordinates)
    else:
        print("NO")


main()

🎉 Congratulations! 🎉

You did an excellent job with the task! It was a challenging problem, but you found the correct solution. You are one step closer to mastering programming! Keep up the good work, because every stage you pass makes you even stronger.

AD

Advertisement

red-snake blue-snake green-snake

Running your code...

Помощник ИИ

Привет! Я твой помощник по программированию. Задавай любые вопросы по Python, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!