qid
stringlengths
2
5
ground_truth_solution
stringlengths
249
2.65k
image_description
stringlengths
136
2.27k
test_script
stringlengths
444
3.15k
function_signature
stringlengths
218
961
image
imagewidth (px)
596
1.02k
q1
def solution(purple_dot: tuple, orange_dots: list) -> int: """ Determine the minimum number of iterations required to absorb all the orange dots. Parameters: purple_dot (tuple): The coordinates of the purple dot (x0, y0). orange_dots (list): A list of tuples, where each tuple represents the coordinates of an orange dot (xi, yi). Returns: int: The number of iterations. """ x0, y0 = purple_dot slopes = set() for x, y in orange_dots: if x == x0: slopes.add('vertical') elif y == y0: slopes.add('horizontal') else: slopes.add((y - y0) / (x - x0)) return len(slopes)
This image shows a grid containing purple dots and orange dots. Across four iterations, each iteration features a red line. The red line passes through the initial purple dots and some orange dots, and the orange dots crossed by the red line turn into purple dots. After four iterations, all the orange dots are turned into purple dots.
def test(): test_cases = [ ((2, 2), [(2, 4)], 1), ((3, 0), [(3, 1), (3, 2), (3, 3)], 1), ((0, 3), [(1, 3), (2, 3), (4, 3)], 1), ((2, 2), [(1, 1), (0, 0), (3, 3)], 1), ((2, 2), [(0, 2), (2, 4), (4, 4), (2, 0)], 3), ((2, 2), [], 0), ((0, 0), [(1, 1), (2, 2), (3, 3), (4, 4)], 1), ((2, 0), [(0, 0), (0, 1), (1, 3), (2, 1), (3, 2), (4, 0)], 5), ((2, 3), [(0, 3), (2, 1), (4, 3), (3, 4), (1, 5), (0, 5)], 5), ((5, 5), [(0, 0), (0, 5), (5, 0), (10, 5), (5, 10), (10, 10)], 3) ] for i, (purple, oranges, expected) in enumerate(test_cases): result = solution(purple, oranges) assert result == expected, f"Assert Error: Test case {i+1} failed: expected {expected}, got {result}" test()
def solution(purple_dot: tuple, orange_dots: list) -> int: """ Determine the minimum number of iterations required to absorb all the orange dots. Parameters: purple_dot (tuple): The coordinates of the purple dot (x0, y0). orange_dots (list): A list of tuples, where each tuple represents the coordinates of an orange dot (xi, yi). Returns: int: The number of iterations. """
q1-2
def solution(purple_dot: tuple, orange_dots: list) -> int: """ Determine the minimum number of iterations required to absorb all the orange dots. Parameters: purple_dot (tuple): The coordinates of the purple dot (x0, y0). orange_dots (list): A list of tuples, where each tuple represents the coordinates of an orange dot (xi, yi). Returns: int: The number of iterations. """ x0, y0 = purple_dot slopes = set() for x, y in orange_dots: if x == x0: slopes.add('vertical+' if y > y0 else 'vertical-') elif y == y0: slopes.add('horizontal+' if x > x0 else 'horizontal-') else: slopes.add(f'+_{(y - y0) / (x - x0)}' if y > y0 else f'-_{(y - y0) / (x - x0)}') return len(slopes)
This image shows a grid containing purple dots and orange dots. Across four iterations, each iteration features a red line (a one-way line). The red line passes through the initial purple dots and some orange dots, and the orange dots crossed by the red line turn into purple dots. After four iterations, all the orange dots are turned into purple dots.
def test(): test_cases = [ ((2, 2), [(2, 4)], 1), ((3, 0), [(3, 1), (3, 2), (3, 3)], 1), ((0, 3), [(1, 3), (2, 3), (4, 3)], 1), ((3, 1), [(3, 0), (3, 2), (3, 3)], 2), ((2, 3), [(1, 3), (0, 3), (4, 3)], 2), ((2, 2), [(1, 1), (0, 0), (3, 3)], 2), ((2, 2), [(0, 2), (2, 4), (4, 4), (2, 0)], 4), ((2, 2), [], 0), ((1, 1), [(0, 0), (2, 2), (3, 3), (4, 4)], 2), ((2, 0), [(0, 0), (0, 1), (1, 3), (2, 1), (3, 2), (4, 0)], 6), ((2, 3), [(0, 3), (2, 1), (4, 3), (3, 4), (1, 5), (0, 5)], 6), ((5, 5), [(0, 0), (0, 5), (5, 0), (10, 5), (5, 10), (10, 10), (3, 5)], 6) ] for i, (purple, oranges, expected) in enumerate(test_cases): result = solution(purple, oranges) assert result == expected, f"Assert Error: Test case {i+1} failed: expected {expected}, got {result}" test()
def solution(purple_dot: tuple, orange_dots: list) -> int: """ Determine the minimum number of iterations required to absorb all the orange dots. Parameters: purple_dot (tuple): The coordinates of the purple dot (x0, y0). orange_dots (list): A list of tuples, where each tuple represents the coordinates of an orange dot (xi, yi). Returns: int: The number of iterations. """
q1-3
def solution(purple_dot: tuple, orange_dots: list) -> int: """ Determine the minimum number of iterations required to absorb all the orange dots. Parameters: purple_dot (tuple): The coordinates of the purple dot (x0, y0). orange_dots (list): A list of tuples, where each tuple represents the coordinates of an orange dot (xi, yi). Returns: int: The number of iterations. """ x0, y0 = purple_dot slopes = set() for x, y in orange_dots: if x == x0: slopes.add('vertical') elif y == y0: slopes.add('horizontal') else: slopes.add((y - y0) / (x - x0)) return len(slopes) * 2
This image shows a grid containing purple dots and orange dots. Across eight iterations, each iteration features a red line. The red line passes through the initial purple dots and some orange dots, and the orange dots crossed by the red line turn into light orange, and in the next iteration, further transform into purple. After eight iterations, all the orange dots are turned into purple dots.
def test(): test_cases = [ ((2, 2), [(2, 4)], 2), ((3, 0), [(3, 1), (3, 2), (3, 3)], 2), ((0, 3), [(1, 3), (2, 3), (4, 3)], 2), ((2, 2), [(1, 1), (0, 0), (3, 3)], 2), ((2, 2), [(0, 2), (2, 4), (4, 4), (2, 0)], 6), ((2, 2), [], 0), ((0, 0), [(1, 1), (2, 2), (3, 3), (4, 4)], 2), ((2, 0), [(0, 0), (0, 1), (1, 3), (2, 1), (3, 2), (4, 0)], 10), ((2, 3), [(0, 3), (2, 1), (4, 3), (3, 4), (1, 5), (0, 5)], 10), ((5, 5), [(0, 0), (0, 5), (5, 0), (10, 5), (5, 10), (10, 10)], 6) ] for i, (purple, oranges, expected) in enumerate(test_cases): result = solution(purple, oranges) assert result == expected, f"Assert Error: Test case {i+1} failed: expected {expected}, got {result}" test()
def solution(purple_dot: tuple, orange_dots: list) -> int: """ Determine the minimum number of iterations required to absorb all the orange dots. Parameters: purple_dot (tuple): The coordinates of the purple dot (x0, y0). orange_dots (list): A list of tuples, where each tuple represents the coordinates of an orange dot (xi, yi). Returns: int: The number of iterations. """
q10
import pandas as pd def solution(n: int) -> pd.DataFrame: """ Given an n x n grid, determine the coordinates of a specific pattern that is formed on the grid. Parameters: n (int): The dimensions of the grid (which is an n*n 2D matrix). n is always an odd number. Returns: pd.DataFrame: A n*n 2D matrix where the coordinates of the black cells are marked with 1 and the rest are marked with 0. """ grid = pd.DataFrame(0, index=range(n), columns=range(n)) # Middle index mid = n // 2 # Set the center grid.iloc[mid, mid] = 1 # Set the diagonals for i in range(mid + 1): if (i-mid) % 2 == 1: continue grid.iloc[i, i] = 1 grid.iloc[i, n - 1 - i] = 1 grid.iloc[n - 1 - i, i] = 1 grid.iloc[n - 1 - i, n - 1 - i] = 1 return grid
This image shows five square grids of different sizes, each corresponding to a different value of n. n represents the size of the grid, and the black squares are arranged in a specific pattern. - When n = 1, the grid has only one square, and the single square is black. - When n = 3, an additional ring of white squares is added around the black square from the n = 1 grid. - When n = 5, an additional ring is added around the n = 3 grid, with black squares at the four corners. - When n = 7, another ring of white squares is added around the n = 5 grid. - When n = 9, an additional ring is added around the n = 7 grid, with black squares at the four corners. This image illustrates how the grid’s layers and the distribution of black squares evolve in a structured pattern as n increases.
import pandas as pd def reference(n): grid = pd.DataFrame(0, index=range(n), columns=range(n)) # Middle index mid = n // 2 # Set the center grid.iloc[mid, mid] = 1 # Set the diagonals for i in range(mid + 1): if (i-mid) % 2 == 1: continue grid.iloc[i, i] = 1 grid.iloc[i, n - 1 - i] = 1 grid.iloc[n - 1 - i, i] = 1 grid.iloc[n - 1 - i, n - 1 - i] = 1 return grid def test(): for n in range(3, 40, 4): expected = reference(n) result = solution(n) assert result.equals(expected), f"Assert Error: Input {n}, \nExpected:\n {expected}\n Got:\n {result}" test()
import pandas as pd def solution(n: int) -> pd.DataFrame: """ Given an n x n grid, determine the coordinates of a specific pattern that is formed on the grid. Parameters: n (int): The dimensions of the grid (which is an n*n 2D matrix). n is always an odd number. Returns: pd.DataFrame: A n*n 2D matrix where the coordinates of the black cells are marked with 1 and the rest are marked with 0. """
q10-2
import pandas as pd def solution(n: int) -> pd.DataFrame: """ Given an n x n grid, determine the coordinates of a specific pattern that is formed on the grid. Parameters: n (int): The dimensions of the grid (which is an n*n 2D matrix). n is always an odd number. Returns: pd.DataFrame: A n*n 2D matrix where the coordinates of the black cells are marked with 1 and the rest are marked with 0. """ grid = pd.DataFrame(0, index=range(n), columns=range(n)) # Middle index mid = n // 2 # Set the center grid.iloc[mid, mid] = 1 # Set the diagonals for i in range(mid + 1): if (i-mid) % 2 == 1: continue grid.iloc[i, mid] = 1 grid.iloc[mid, i] = 1 grid.iloc[n - 1 - i, mid] = 1 grid.iloc[mid, n - 1 - i] = 1 return grid
This image shows five square grids of different sizes, each corresponding to a different value of n. n represents the size of the grid, and the black squares are arranged in a specific pattern. - When n = 1, the grid has only one square, and the single square is black. - When n = 3, an additional ring of white squares is added around the black square from the n = 1 grid. - When n = 5, an additional ring is added around the n = 3 grid, with black squares appear at the center of each edge. - When n = 7, another ring of white squares is added around the n = 5 grid. - When n = 9, an additional ring is added around the n = 7 grid, with black squares appear at the center of each edge. This image illustrates how the grid’s layers and the distribution of black squares evolve in a structured pattern as n increases.
import pandas as pd def reference(n): grid = pd.DataFrame(0, index=range(n), columns=range(n)) # Middle index mid = n // 2 # Set the center grid.iloc[mid, mid] = 1 # Set the diagonals for i in range(mid + 1): if (i-mid) % 2 == 1: continue grid.iloc[i, mid] = 1 grid.iloc[mid, i] = 1 grid.iloc[n - 1 - i, mid] = 1 grid.iloc[mid, n - 1 - i] = 1 return grid def test(): for n in range(3, 40, 4): expected = reference(n) result = solution(n) assert result.equals(expected), f"Assert Error: Input {n}, \nExpected:\n {expected}\n Got:\n {result}" test()
import pandas as pd def solution(n: int) -> pd.DataFrame: """ Given an n x n grid, determine the coordinates of a specific pattern that is formed on the grid. Parameters: n (int): The dimensions of the grid (which is an n*n 2D matrix). n is always an odd number. Returns: pd.DataFrame: A n*n 2D matrix where the coordinates of the black cells are marked with 1 and the rest are marked with 0. """
q10-3
import pandas as pd def solution(n: int) -> pd.DataFrame: """ Given an n x n grid, determine the coordinates of a specific pattern that is formed on the grid. Parameters: n (int): The dimensions of the grid (which is an n*n 2D matrix). n is always an odd number. Returns: pd.DataFrame: A n*n 2D matrix where the coordinates of the black cells are marked with 1 and the rest are marked with 0. """ grid = pd.DataFrame(0, index=range(n), columns=range(n)) # Middle index mid = n // 2 # Set the center grid.iloc[mid, mid] = 0 # Set the diagonals for i in range(mid + 1): if (i-mid) % 2 == 0: continue grid.iloc[i, i] = 1 grid.iloc[i, n - 1 - i] = 1 grid.iloc[n - 1 - i, i] = 1 grid.iloc[n - 1 - i, n - 1 - i] = 1 return grid
This image shows five square grids of different sizes, each corresponding to a different value of n. n represents the size of the grid, and the black squares are arranged in a specific pattern. - When n = 1, the grid has only one square, and the single square is white. - When n = 3, an additional ring is added around the black square from the n = 1 grid, with black squares at the four corners. - When n = 5, an additional ring of white squares is added around the n = 3 grid - When n = 7, an additional ring is added around the n = 5 grid, with black squares at the four corners. - When n = 9, an additional ring of white squares is added around the n = 7 grid - When n = 9, an additional ring is added around the n = 9 grid, with black squares at the four corners. This image illustrates how the grid’s layers and the distribution of black squares evolve in a structured pattern as n increases.
import pandas as pd def reference(n): grid = pd.DataFrame(0, index=range(n), columns=range(n)) # Middle index mid = n // 2 # Set the center grid.iloc[mid, mid] = 0 # Set the diagonals for i in range(mid + 1): if (i-mid) % 2 == 0: continue grid.iloc[i, i] = 1 grid.iloc[i, n - 1 - i] = 1 grid.iloc[n - 1 - i, i] = 1 grid.iloc[n - 1 - i, n - 1 - i] = 1 return grid def test(): for n in range(3, 40, 4): expected = reference(n) result = solution(n) assert result.equals(expected), f"Assert Error: Input {n}, \nExpected:\n {expected}\n Got:\n {result}" test()
import pandas as pd def solution(n: int) -> pd.DataFrame: """ Given an n x n grid, determine the coordinates of a specific pattern that is formed on the grid. Parameters: n (int): The dimensions of the grid (which is an n*n 2D matrix). n is always an odd number. Returns: pd.DataFrame: A n*n 2D matrix where the coordinates of the black cells are marked with 1 and the rest are marked with 0. """
q11
from typing import Tuple def layer(x: int, y: int) -> int: """ Determine the layer of a point based on its coordinates. Parameters: x (int): The x-coordinate of the point. y (int): The y-coordinate of the point. Returns: int: The layer of the point. """ return max(x, y) def solution(point1: Tuple[int, int], point2: Tuple[int, int]) -> str: """ Determine the relationship between two points based on their layers. Parameters: point1 (Tuple[int, int]): The coordinates of the first point, where both x and y are non-negative integers. point2 (Tuple[int, int]): The coordinates of the second point, where both x and y are non-negative integers. Returns: str: Return 'A', 'B'. 'C'. """ x1, y1 = point1 x2, y2 = point2 layer1 = layer(x1, y1) layer2 = layer(x2, y2) if layer1 == layer2: return 'A' if abs(layer1 - layer2) == 1: return 'B' return 'C'
This image shows a coordinate system in which the points are classified into different layers based on a fixed pattern: - Layer 0 is the origin. - The points on Layer 1 are positioned on a square with side length 1, using the origin as the bottom-left corner. - The points on Layer 2 are positioned on a square with side length 2, using the origin as the bottom-left corner. - The points on Layer 3 are positioned on a square with side length 3, using the origin as the bottom-left corner. - The points on Layer 4 are positioned on a square with side length 4, using the origin as the bottom-left corner. This pattern progressively expands the layers outward, with each layer forming a larger square.
def test(): test_cases = [ ((2, 0), (2, 1), 'A'), ((0, 0), (4, 0), 'C'), ((1, 0), (2, 0), 'B'), ((0, 0), (0, 0), 'A'), ((3, 10), (4, 4), 'C'), ((5, 6), (7, 4), 'B'), ((9, 9), (9, 10), 'B'), ((999, 1002), (1000, 1000), 'C'), ((0, 0), (0, 1), 'B'), ((0, 0), (1, 0), 'B') ] for test_case in test_cases: point1, point2, expected = test_case result = solution(point1, point2) assert result == expected, f"Assert Error: Test case {test_case} failed: expected {expected}, got {result}" test()
from typing import Tuple def solution(point1: Tuple[int, int], point2: Tuple[int, int]) -> str: """ Determine the relationship between two points based on their layers. Parameters: point1 (Tuple[int, int]): The coordinates of the first point, where both x and y are non-negative integers. point2 (Tuple[int, int]): The coordinates of the second point, where both x and y are non-negative integers. Returns: str: Return 'A', 'B'. 'C'. """
q11-2
from typing import Tuple def solution(point1: Tuple[int, int], point2: Tuple[int, int]) -> str: """ Determine the relationship between two points based on their layers. Parameters: point1 (Tuple[int, int]): The coordinates of the first point, where both x and y are non-negative integers. point2 (Tuple[int, int]): The coordinates of the second point, where both x and y are non-negative integers. Returns: str: Return 'A', 'B', or 'C'. """ layer1 = point1[0] + point1[1] layer2 = point2[0] + point2[1] if layer1 == layer2: return 'A' elif abs(layer1 - layer2) == 1: return 'B' else: return 'C'
This image shows a coordinate system in which the points are classified into different layers based on a fixed pattern: - Layer 0 is the origin. - Layer 1 is an equilateral right triangle with the origin as the right angle. The two other points are (1, 0) and (0, 1). - Layer 3 is also an equilateral right triangle with the origin as the right angle. The two other points are (2, 0), and (0, 2). - Afterward, the points in the same layer all lie on the same diagonal line. This pattern progressively expands the layers outward, with each layer forming a longer diagonal line.
def test(): test_cases = [ ((2, 0), (2, 1), 'B'), ((1, 1), (0, 2), 'A'), ((0, 3), (1, 2), 'A'), ((0, 0), (4, 0), 'C'), ((1, 0), (2, 0), 'B'), ((0, 0), (0, 0), 'A'), ((3, 10), (4, 4), 'C'), ((5, 6), (7, 4), 'A'), ((9, 9), (9, 10), 'B'), ((999, 1002), (1000, 1000), 'B'), ((0, 0), (0, 1), 'B'), ((0, 0), (1, 0), 'B') ] for test_case in test_cases: point1, point2, expected = test_case result = solution(point1, point2) assert result == expected, f"Assert Error: Test case {test_case} failed: expected {expected}, got {result}" test()
from typing import Tuple def solution(point1: Tuple[int, int], point2: Tuple[int, int]) -> str: """ Determine the relationship between two points based on their layers. Parameters: point1 (Tuple[int, int]): The coordinates of the first point, where both x and y are non-negative integers. point2 (Tuple[int, int]): The coordinates of the second point, where both x and y are non-negative integers. Returns: str: Return 'A', 'B'. 'C'. """
q11-3
from typing import Tuple def layer(x: int, y: int) -> int: """ Determine the layer of a point based on its coordinates. Parameters: x (int): The x-coordinate of the point. y (int): The y-coordinate of the point. Returns: int: The layer of the point. """ return min(x, y) def solution(point1: Tuple[int, int], point2: Tuple[int, int]) -> str: """ Determine the relationship between two points based on their layers. Parameters: point1 (Tuple[int, int]): The coordinates of the first point, where both x and y are non-negative integers. point2 (Tuple[int, int]): The coordinates of the second point, where both x and y are non-negative integers. Returns: str: Return 'A', 'B'. 'C'. """ x1, y1 = point1 x2, y2 = point2 layer1 = layer(x1, y1) layer2 = layer(x2, y2) if layer1 == layer2: return 'A' if abs(layer1 - layer2) == 1: return 'B' return 'C'
This image shows a coordinate system in which the points are classified into different layers based on a fixed pattern: - Layer 0 starts from the origin (0,0) and extends lines from this point to the direct right and direct upward; all points on these lines belong to Layer 0. - Layer 1 starts from the point (1,1) and extends lines from this point to the direct right and direct upward; all points on these lines belong to Layer 1. - Layer 2 starts from the point (2,2) and extends lines from this point to the direct right and direct upward; all points on these lines belong to Layer 2. - Layer 3 starts from the point (3,3) and extends lines from this point to the direct right and direct upward; all points on these lines belong to Layer 3. This pattern progressively expands the layers outward.
def test(): test_cases = [ ((2, 0), (2, 1), 'B'), ((0, 0), (4, 0), 'A'), ((1, 0), (2, 0), 'A'), ((0, 0), (0, 0), 'A'), ((3, 10), (4, 4), 'B'), ((5, 6), (7, 4), 'B'), ((9, 9), (9, 10), 'A'), ((999, 1002), (1000, 1000), 'B'), ((0, 0), (0, 1), 'A'), ((0, 0), (1, 0), 'A'), ((0, 0), (2, 2), 'C'), ((7, 4), (7, 2), 'C'), ((9, 2), (4, 8), 'C') ] for test_case in test_cases: point1, point2, expected = test_case result = solution(point1, point2) assert result == expected, f"Assert Error: Test case {test_case} failed: expected {expected}, got {result}" test()
from typing import Tuple def solution(point1: Tuple[int, int], point2: Tuple[int, int]) -> str: """ Determine the relationship between two points based on their layers. Parameters: point1 (Tuple[int, int]): The coordinates of the first point, where both x and y are non-negative integers. point2 (Tuple[int, int]): The coordinates of the second point, where both x and y are non-negative integers. Returns: str: Return 'A', 'B'. 'C'. """
q12
import numpy as np def solution(input_matrix: np.ndarray) -> np.ndarray: """ Transform the input matrix based on the pattern shown in the figure Parameters: input_matrix (np.ndarray): Input matrix as a numpy ndarray. Returns: output_matrix (np.ndarray): Output matrix as a numpy ndarray. """ new_matrix = np.rot90(input_matrix, 2) return new_matrix
This image presents two different input matrices and their corresponding output matrices, with each pair linked by a rotation transformation process. First Example: - The input matrix is a 4x4 matrix. The first row consists of the letters "A B C D," followed by a row of symbols "+ - * /," then the letters "D C B A," and finally the symbols "/ * - +." - After a rotation transformation, the output matrix has the first row as the symbols "+ - * /," the second row as the letters "A B C D," the third row as "/ * - +," and the last row as "D C B A." Second Example: - The input matrix is also a 4x4 matrix, containing a mix of numbers, symbols, and letters arranged as "4 @ 1 8," "# a Q E," "9 ? 6 &," and "b $ F t." - After a rotation transformation, the output matrix has the first row as "t F $ b," the second row as "& 6 ? 9," the third row as "E Q a #," and the fourth row as "8 1 @ 4."
import numpy as np def test(): test_cases = [ np.array([['1', '2', '3'], ['4', '#', '6'], ['D', '8', 'a']]), np.array([['1', 'a'], ['3', '#']]), np.array([['4', '@', '1', '8'],['#', 'a', 'Q', '&'],['9', '?', '&', '%'],['b', '$', 'F', 't']]), np.array([['6', '@', '2', '1'],['9', '#', 'Q', '1'],['9', '4', '5', '4'],['1', '1', '1', '1']]), np.array([['4', '2'], ['6', '9']]), np.array([['7', '8', '9'], ['+', '#', '_'], [')', '8', '$']]), np.array([['6', '@', '2', '1', '&'],['9', '#', 'Q', '1', '@'],['9', '4', '5', '4', '!'], ['1', '1', '1', '1', '?'], ['(', ')', '#', '%', '5']]), np.array([['6', '@', '2', '1', '&', ']'],['9', '#', 'Q', '1', '@', '['],['9', '4', '5', '4', '!', '='], ['1', '1', '1', '1', '?', '9'], ['(', ')', '#', '%', '5', '4'], ['(', '6', '#', '4', '5', '-']]), np.array([['!', '2', '$'], ['6', '!', '9'], ['+', '!', '-']]), np.array([['1', '1', '1'], ['2', '2', '2'], ['3', '3', '3']]), ] for i, input_matrix in enumerate(test_cases): original_input_matrix = input_matrix.copy() result = solution(input_matrix) expected = np.rot90(original_input_matrix, 2) assert (result == expected).all(), f"Assert Error: Input {original_input_matrix}, Expected {expected}, Got: {result}" test()
import numpy as np def solution(input_matrix: np.ndarray) -> np.ndarray: """ Transform the input matrix based on the pattern shown in the figure Parameters: input_matrix (np.ndarray): Input matrix as a numpy ndarray. Returns: output_matrix (np.ndarray): Output matrix as a numpy ndarray. """
q12-2
import numpy as np def solution(input_matrix: np.ndarray) -> np.ndarray: """ Transform the input matrix based on the pattern shown in the figure Parameters: input_matrix (np.ndarray): Input matrix as a numpy ndarray. Returns: output_matrix (np.ndarray): Output matrix as a numpy ndarray. """ new_matrix = input_matrix[:, ::-1] return new_matrix
This image presents two different input matrices and their corresponding output matrices, with each pair linked by a transformation process. The transformation method seems to be based on rotation around the vertical axis at the center of the matrix. First Example: - The input matrix is a 4x4 matrix. The first row consists of the letters "A B C D," followed by a row of symbols "+ - * /," then the letters "D C B A," and finally the symbols "/ * - +." - After the transformation, the output matrix has the first row as "D C B A," the second row as "/ * - +," the third row as "A B C D," and the last row as "+ - * /." Second Example: - The input matrix is also a 4x4 matrix, containing a mix of numbers, symbols, and letters arranged as "4 @ 1 8," "# a Q E," "9 ? 6 &," and "b $ F t." - After the transformation, the output matrix has the first row as "8 1 @ 4," the second row as "E Q a #," the third row as "& 6 ? 9," and the fourth row as "t F $ b."
import numpy as np def test(): test_cases = [ np.array([['1', '2', '3'], ['4', '#', '6'], ['D', '8', 'a']]), np.array([['1', 'a'], ['3', '#']]), np.array([['4', '@', '1', '8'],['#', 'a', 'Q', '&'],['9', '?', '&', '%'],['b', '$', 'F', 't']]), np.array([['6', '@', '2', '1'],['9', '#', 'Q', '1'],['9', '4', '5', '4'],['1', '1', '1', '1']]), np.array([['4', '2'], ['6', '9']]), np.array([['7', '8', '9'], ['+', '#', '_'], [')', '8', '$']]), np.array([['6', '@', '2', '1', '&'],['9', '#', 'Q', '1', '@'],['9', '4', '5', '4', '!'], ['1', '1', '1', '1', '?'], ['(', ')', '#', '%', '5']]), np.array([['6', '@', '2', '1', '&', ']'],['9', '#', 'Q', '1', '@', '['],['9', '4', '5', '4', '!', '='], ['1', '1', '1', '1', '?', '9'], ['(', ')', '#', '%', '5', '4'], ['(', '6', '#', '4', '5', '-']]), np.array([['!', '2', '$'], ['6', '!', '9'], ['+', '!', '-']]), np.array([['1', '1', '1'], ['2', '2', '2'], ['3', '3', '3']]), ] for i, input_matrix in enumerate(test_cases): original_input_matrix = input_matrix.copy() result = solution(input_matrix) expected = original_input_matrix[:, ::-1] assert (result == expected).all(), f"Assert Error: Input {original_input_matrix}, Expected {expected}, Got: {result}" test()
import numpy as np def solution(input_matrix: np.ndarray) -> np.ndarray: """ Transform the input matrix based on the pattern shown in the figure Parameters: input_matrix (np.ndarray): Input matrix as a numpy ndarray. Returns: output_matrix (np.ndarray): Output matrix as a numpy ndarray. """
q12-3
import numpy as np def solution(input_matrix: np.ndarray) -> np.ndarray: """ Transform the input matrix based on the pattern shown in the figure Parameters: input_matrix (np.ndarray): Input matrix as a numpy ndarray. Returns: output_matrix (np.ndarray): Output matrix as a numpy ndarray. """ new_matrix = input_matrix[::-1, :] return new_matrix
This image presents two different input matrices and their corresponding output matrices, with each pair linked by a transformation process. The transformation method seems to be based on rotation around the horizontal axis at the center of the matrix. First Example: - The input matrix is a 4x4 matrix. The first row consists of the letters "A B C D," followed by a row of symbols "+ - * /," then the letters "D C B A," and finally the symbols "/ * - +." - After the transformation, the output matrix has the first row as "/ * - +," the second row as "D C B A," the third row as "+ - * /," and the last row as "A B C D." Second Example: - The input matrix is also a 4x4 matrix, containing a mix of numbers, symbols, and letters arranged as "4 @ 1 8," "# a Q E," "9 ? 6 &," and "b $ F t." - After the transformation, the output matrix has the first row as "b $ F t," the second row as "9 ? 6 &," the third row as "# a Q E," and the fourth row as "4 @ 1 8."
import numpy as np def test(): test_cases = [ np.array([['1', '2', '3'], ['4', '#', '6'], ['D', '8', 'a']]), np.array([['1', 'a'], ['3', '#']]), np.array([['4', '@', '1', '8'],['#', 'a', 'Q', '&'],['9', '?', '&', '%'],['b', '$', 'F', 't']]), np.array([['6', '@', '2', '1'],['9', '#', 'Q', '1'],['9', '4', '5', '4'],['1', '1', '1', '1']]), np.array([['4', '2'], ['6', '9']]), np.array([['7', '8', '9'], ['+', '#', '_'], [')', '8', '$']]), np.array([['6', '@', '2', '1', '&'],['9', '#', 'Q', '1', '@'],['9', '4', '5', '4', '!'], ['1', '1', '1', '1', '?'], ['(', ')', '#', '%', '5']]), np.array([['6', '@', '2', '1', '&', ']'],['9', '#', 'Q', '1', '@', '['],['9', '4', '5', '4', '!', '='], ['1', '1', '1', '1', '?', '9'], ['(', ')', '#', '%', '5', '4'], ['(', '6', '#', '4', '5', '-']]), np.array([['!', '2', '$'], ['6', '!', '9'], ['+', '!', '-']]), np.array([['1', '1', '1'], ['2', '2', '2'], ['3', '3', '3']]), ] for i, input_matrix in enumerate(test_cases): original_input_matrix = input_matrix.copy() result = solution(input_matrix) expected = original_input_matrix[::-1, :] assert (result == expected).all(), f"Assert Error: Input {original_input_matrix}, Expected {expected}, Got: {result}" test()
import numpy as np def solution(input_matrix: np.ndarray) -> np.ndarray: """ Transform the input matrix based on the pattern shown in the figure Parameters: input_matrix (np.ndarray): Input matrix as a numpy ndarray. Returns: output_matrix (np.ndarray): Output matrix as a numpy ndarray. """
q13
import heapq def solution(nodes: dict, edges: list, start: str, end: str) -> int: """ Given the nodes and edges of a graph, determine the minimum path cost from a given starting node to an ending node. Please observe the example graph in the image to deduce the pattern calculating the path cost between two nodes. Input: - nodes: A dictionary where each key represents a node, and its associated value is the node's value. Example: {'A': 10, 'B': 20} indicates that node A has a value of 10, and node B has a value of 20. - edges: A list of tuples, each containing two nodes that are directly connected. Example: [('A', 'B'), ('B', 'C')] means node A is connected to node B, and node B is connected to node C. - start: The starting node where the path begins. - end: The ending node where the path terminates. Output: - Return the minimum cost required to travel from the start node to the end node. Return -1 if no path exists. """ graph = {node: {} for node in nodes} for node1, node2 in edges: if node1 in graph and node2 in graph: graph[node1][node2] = abs(nodes[node1]) + abs(nodes[node2]) graph[node2][node1] = abs(nodes[node1]) + abs(nodes[node2]) pq = [(0, start)] visited = set() min_cost = {node: float('inf') for node in nodes} min_cost[start] = 0 while pq: current_cost, current_node = heapq.heappop(pq) if current_node in visited: continue visited.add(current_node) if current_node == end: return current_cost for neighbor, weight in graph[current_node].items(): if neighbor not in visited: new_cost = current_cost + weight if new_cost < min_cost[neighbor]: min_cost[neighbor] = new_cost heapq.heappush(pq, (new_cost, neighbor)) return -1
This image shows a weighted undirected graph, where each node contains a value and is connected by edges labeled with weights, representing the "cost" between two nodes. The description is as follows: - Node A has a value of 12 and is connected to node B with an edge labeled cost=15. - Node B has a value of 3 and is connected to node C (with a value of -2) with an edge labeled cost=5. - Node B is also connected to node D (with a value of -8) with an edge labeled cost=11. - Node D is connected to node E (with a value of -6) with an edge labeled cost=14. - Node D is also connected to node F (with a value of 4) with an edge labeled cost=12. The calculation of the cost values seems to follow a certain pattern.
def test(): nodes = {'A': 10, 'B': 3, 'C': -2, 'D': -8, 'E': -6, 'F': 4} connections = [('A', 'B'), ('B', 'C'), ('B', 'D'), ('D', 'E'), ('D', 'F')] pairs = [('A', 'C'), ('B', 'E'), ('A', 'F'), ('A', 'D'), ('A', 'E'), ('B', 'F')] expected_results = [18, 25, 36, 24, 38, 23] for index, (start, end) in enumerate(pairs): results = solution(nodes, connections, start, end) assert results == expected_results[index], f"Assert Error: test case failed, from node {start} to {end} , expected {expected_results[index]} but got {results}" nodes = {'A': 1, 'B': -2, 'C': 3, 'D': -4, 'E': 5, 'F': -6} connections = [('A', 'D'), ('D', 'E'), ('E', 'F'), ('E', 'B'), ('F', 'C'), ('D', 'B')] pairs = [('A', 'C'), ('B', 'E'), ('A', 'F'), ('C', 'D'), ('A', 'B')] expected_results = [34, 7, 25, 29, 11] for index, (start, end) in enumerate(pairs): results = solution(nodes, connections, start, end) assert results == expected_results[index], f"Assert Error: test case failed, from node {start} to {end} , expected {expected_results[index]} but got {results}" test()
def solution(nodes: dict, edges: list, start: str, end: str) -> int: """ Given the nodes and edges of a graph, determine the minimum path cost from a given starting node to an ending node. Please observe the example graph in the image to deduce the pattern calculating the path cost between two nodes. Input: - nodes: A dictionary where each key represents a node, and its associated value is the node's value. Example: {'A': 10, 'B': 20} indicates that node A has a value of 10, and node B has a value of 20. - edges: A list of tuples, each containing two nodes that are directly connected. Example: [('A', 'B'), ('B', 'C')] means node A is connected to node B, and node B is connected to node C. - start: The starting node where the path begins. - end: The ending node where the path terminates. Output: - Return the minimum cost required to travel from the start node to the end node """
q13-2
import heapq def solution(nodes: dict, edges: list, start: str, end: str) -> int: """ Given the nodes and edges of a graph, determine the minimum path cost from a given starting node to an ending node. Please observe the example graph in the image to deduce the pattern calculating the path cost between two nodes. Input: - nodes: A dictionary where each key represents a node, and its associated value is the node's value. Example: {'A': 10, 'B': 20} indicates that node A has a value of 10, and node B has a value of 20. - edges: A list of tuples, each containing two nodes that are directly connected. Example: [('A', 'B'), ('B', 'C')] means node A is connected to node B, and node B is connected to node C. - start: The starting node where the path begins. - end: The ending node where the path terminates. Output: - Return the minimum cost required to travel from the start node to the end node. Return -1 if no path exists. """ graph = {node: {} for node in nodes} for node1, node2 in edges: if node1 in graph and node2 in graph: graph[node1][node2] = abs(nodes[node1]) * abs(nodes[node2]) graph[node2][node1] = abs(nodes[node1]) * abs(nodes[node2]) pq = [(0, start)] visited = set() min_cost = {node: float('inf') for node in nodes} min_cost[start] = 0 while pq: current_cost, current_node = heapq.heappop(pq) if current_node in visited: continue visited.add(current_node) if current_node == end: return current_cost for neighbor, weight in graph[current_node].items(): if neighbor not in visited: new_cost = current_cost + weight if new_cost < min_cost[neighbor]: min_cost[neighbor] = new_cost heapq.heappush(pq, (new_cost, neighbor)) return -1
This image shows a weighted undirected graph, where each node contains a value, and the nodes are connected by edges labeled with weights representing the "cost" between them. The details are as follows: - Node A has a value of 12 and is connected to node B (value 3) with an edge labeled cost=36. - Node B is connected to node C (value -2) with an edge labeled cost=6. - Node B is also connected to node D (value -8) with an edge labeled cost=24. - Node D is connected to node E (value -6) with an edge labeled cost=48. - Node D is also connected to node F (value 4) with an edge labeled cost=32. The calculation of the cost values seems to follow a certain pattern.
def test(): nodes = {'A': 10, 'B': 3, 'C': -2, 'D': -8, 'E': -6, 'F': 4} connections = [('A', 'B'), ('B', 'C'), ('B', 'D'), ('D', 'E'), ('D', 'F')] pairs = [('A', 'C'), ('B', 'E'), ('A', 'F'), ('A', 'D'), ('A', 'E'), ('B', 'F')] expected_results = [36, 72, 86, 54, 102, 56] for index, (start, end) in enumerate(pairs): results = solution(nodes, connections, start, end) assert results == expected_results[index], f"Assert Error: test case failed, from node {start} to {end} , expected {expected_results[index]} but got {results}" nodes = {'A': 1, 'B': -2, 'C': 3, 'D': -4, 'E': 5, 'F': -6} connections = [('A', 'D'), ('D', 'E'), ('E', 'F'), ('E', 'B'), ('F', 'C'), ('D', 'B')] pairs = [('A', 'C'), ('B', 'E'), ('A', 'F'), ('C', 'D'), ('A', 'B')] expected_results = [70, 10, 52, 66, 12] for index, (start, end) in enumerate(pairs): results = solution(nodes, connections, start, end) assert results == expected_results[index], f"Assert Error: test case failed, from node {start} to {end} , expected {expected_results[index]} but got {results}" test()
def solution(nodes: dict, edges: list, start: str, end: str) -> int: """ Given the nodes and edges of a graph, determine the minimum path cost from a given starting node to an ending node. Please observe the example graph in the image to deduce the pattern calculating the path cost between two nodes. Input: - nodes: A dictionary where each key represents a node, and its associated value is the node's value. Example: {'A': 10, 'B': 20} indicates that node A has a value of 10, and node B has a value of 20. - edges: A list of tuples, each containing two nodes that are directly connected. Example: [('A', 'B'), ('B', 'C')] means node A is connected to node B, and node B is connected to node C. - start: The starting node where the path begins. - end: The ending node where the path terminates. Output: - Return the minimum cost required to travel from the start node to the end node """
q13-3
import heapq def solution(nodes: dict, edges: list, start: str, end: str) -> int: """ Given the nodes and edges of a graph, determine the minimum path cost from a given starting node to an ending node. Please observe the example graph in the image to deduce the pattern calculating the path cost between two nodes. Input: - nodes: A dictionary where each key represents a node, and its associated value is the node's value. Example: {'A': 10, 'B': 20} indicates that node A has a value of 10, and node B has a value of 20. - edges: A list of tuples, each containing two nodes that are directly connected. Example: [('A', 'B'), ('B', 'C')] means node A is connected to node B, and node B is connected to node C. - start: The starting node where the path begins. - end: The ending node where the path terminates. Output: - Return the minimum cost required to travel from the start node to the end node. Return -1 if no path exists. """ graph = {node: {} for node in nodes} for node1, node2 in edges: if node1 in graph and node2 in graph: graph[node1][node2] = abs(nodes[node1] - nodes[node2]) graph[node2][node1] = abs(nodes[node1] - nodes[node2]) pq = [(0, start)] visited = set() min_cost = {node: float('inf') for node in nodes} min_cost[start] = 0 while pq: current_cost, current_node = heapq.heappop(pq) if current_node in visited: continue visited.add(current_node) if current_node == end: return current_cost for neighbor, weight in graph[current_node].items(): if neighbor not in visited: new_cost = current_cost + weight if new_cost < min_cost[neighbor]: min_cost[neighbor] = new_cost heapq.heappush(pq, (new_cost, neighbor)) return -1
This image shows a weighted undirected graph, where each node contains a value, and the nodes are connected by edges labeled with weights representing the "cost" between them. The details are as follows: - Node A has a value of 12 and is connected to node B (value 3) with an edge labeled cost=9. - Node B is connected to node C (value -2) with an edge labeled cost=5. - Node B is also connected to node D (value -8) with an edge labeled cost=11. - Node D is connected to node E (value -6) with an edge labeled cost=2. - Node D is also connected to node F (value 4) with an edge labeled cost=12. The calculation of the cost values seems to follow a certain pattern.
def test(): nodes = {'A': 10, 'B': 3, 'C': -2, 'D': -8, 'E': -6, 'F': 4} connections = [('A', 'B'), ('B', 'C'), ('B', 'D'), ('D', 'E'), ('D', 'F')] pairs = [('A', 'C'), ('B', 'E'), ('A', 'F'), ('A', 'D'), ('A', 'E'), ('B', 'F')] expected_results = [12, 13, 30, 18, 20, 23] for index, (start, end) in enumerate(pairs): results = solution(nodes, connections, start, end) assert results == expected_results[index], f"Assert Error: test case failed, from node {start} to {end} , expected {expected_results[index]} but got {results}" nodes = {'A': 1, 'B': -2, 'C': 3, 'D': -4, 'E': 5, 'F': -6} connections = [('A', 'D'), ('D', 'E'), ('E', 'F'), ('E', 'B'), ('F', 'C'), ('D', 'B')] pairs = [('A', 'C'), ('B', 'E'), ('A', 'F'), ('C', 'D'), ('A', 'B')] expected_results = [34, 7, 25, 29, 7] for index, (start, end) in enumerate(pairs): results = solution(nodes, connections, start, end) assert results == expected_results[index], f"Assert Error: test case failed, from node {start} to {end} , expected {expected_results[index]} but got {results}" test()
def solution(nodes: dict, edges: list, start: str, end: str) -> int: """ Given the nodes and edges of a graph, determine the minimum path cost from a given starting node to an ending node. Please observe the example graph in the image to deduce the pattern calculating the path cost between two nodes. Input: - nodes: A dictionary where each key represents a node, and its associated value is the node's value. Example: {'A': 10, 'B': 20} indicates that node A has a value of 10, and node B has a value of 20. - edges: A list of tuples, each containing two nodes that are directly connected. Example: [('A', 'B'), ('B', 'C')] means node A is connected to node B, and node B is connected to node C. - start: The starting node where the path begins. - end: The ending node where the path terminates. Output: - Return the minimum cost required to travel from the start node to the end node """
q14
def solution(start: tuple[int, int], target: tuple[int, int], direction: tuple[int, int]) -> bool: """ Determines whether the ball can reach the target. Parameters: - start: Tuple[int, int], represents the initial position of the ball (x, y). - target: Tuple[int, int], represents the position of the target. - direction: Tuple[int, int], represents the initial direction of the ball (dx, dy). dx and dy are integers that can be either -1, 0, or 1. Returns: - bool: True if the ball can reach the target, False otherwise. """ x, y = start tx, ty = target dx, dy = direction while True: x += dx y += dy if (x, y) == (tx, ty): return True if x == 0 or x == 10: dx = -dx if y == 0 or y == 10: dy = -dy if (x, y) == start and (dx, dy) == direction: return False
This image shows a 10x10 coordinate plane with a start point (start) and a target point (target), as well as a path. It can be observed that when the path hits the boundary, it bounces back with the same angle of incidence. The path continues to bounce off the boundaries until it reaches the target point.
def test(): test_cases = [ [(8, 7), (6, 9), (1, -1), True], [(8, 7), (6, 10), (1, -1), False], [(8, 7), (9, 6), (1, -1), True], [(0, 0), (1, 1), (1, 0), False], [(0, 0), (2, 2), (1, 1), True], [(0, 0), (0, 1), (0, 1), True], [(2, 1), (6, 10), (-1, -1), False], [(2, 1), (1, 0), (-1, -1), True], [(10, 1), (1, 0), (-1, 1), False], [(10, 1), (9, 2), (-1, 1), True], ] for test_case in test_cases: start, target, direction, expected = test_case result = solution(start, target, direction) assert result == expected, f"Assert Error: start={start}, target={target}, direction={direction}, expected={expected}, got={result}" test()
def solution(start: tuple[int, int], target: tuple[int, int], direction: tuple[int, int]) -> bool: """ Determines whether the ball can reach the target. Parameters: - start: Tuple[int, int], represents the initial position of the ball (x, y). - target: Tuple[int, int], represents the position of the target. - direction: Tuple[int, int], represents the initial direction of the ball (dx, dy). dx and dy are integers that can be either -1, 0, or 1. Returns: - bool: True if the ball can reach the target, False otherwise. """
q14-2
def solution(start_1: tuple[int, int], start_2: tuple[int, int], direction_1: tuple[int, int], direction_2: tuple[int, int]) -> bool: """ Determines whether the two balls will collide. Parameters: - start_1: Tuple[int, int], represents the initial position of ball 1 (x, y). - start_2: Tuple[int, int], represents the initial position of ball 2 (x, y). - direction_1: Tuple[int, int], represents the initial direction of ball 1 (dx, dy). dx and dy are integers that can be either -1, 0, or 1. - direction_2: Tuple[int, int], represents the initial direction of ball 2 (dx, dy). dx and dy are integers that can be either -1, 0, or 1. Returns: - bool: True if the balls can collide, False otherwise. """ x_1, y_1 = start_1 x_2, y_2 = start_2 dx_1, dy_1 = direction_1 dx_2, dy_2 = direction_2 while True: x_1 += dx_1 y_1 += dy_1 x_2 += dx_2 y_2 += dy_2 if (x_1, y_1) == (x_2, y_2): return True if (x_1 + 0.5 * dx_1, y_1 + 0.5 * dy_1) == (x_2 + 0.5 * dx_2, y_2 + 0.5 * dy_2): return True if x_1 == 0 or x_1 == 10: dx_1 = -dx_1 if x_2 == 0 or x_2 == 10: dx_2 = -dx_2 if y_1 == 0 or y_1 == 10: dy_1 = -dy_1 if y_2 == 0 or y_2 == 10: dy_2 = -dy_2 if (x_1, y_1) == start_1 and (x_2, y_2) == start_2 and (dx_1, dy_1) == direction_1 and (dx_2, dy_2) == direction_2: return False
This image shows a 10x10 coordinate plane with two balls, Ball 1 and Ball 2, moving along different paths, and they collide at a certain point. It can be observed that when these two balls hits the boundary, they bounces back with the same angle of incidence, and they continue to bounce off the boundaries until they collide with each other.
def test(): test_cases = [ [(8, 7), (6, 9), (1, -1), (1, 1), False], [(8, 7), (6, 9), (1, -1), (-1, 1), True], [(8, 7), (6, 9), (-1, 1), (1, -1), True], [(8, 7), (9, 6), (1, -1), (1, -1), False], [(0, 0), (1, 1), (1, 0), (1, 1), False], [(0, 0), (0, 3), (1, 0), (1, -1), True], [(0, 0), (2, 2), (1, 1), (0, 1), False], [(0, 0), (2, 2), (1, 1), (-1, -1), True], [(0, 0), (0, 1), (0, 1), (1, -1), False], [(2, 1), (1, 0), (-1, -1), (0, 1), False], [(10, 1), (1, 0), (-1, 1), (1, 0), False], [(10, 1), (9, 2), (-1, 1), (-1, 1), False], [(3, 4), (3, 6), (1, 1), (1, -1), True], ] for test_case in test_cases: start1, start2, direction1, direction2, expected = test_case result = solution(start1, start2, direction1, direction2) assert result == expected, f"Assert Error: start1={start1}, start2={start2}, direction1={direction1}, direction2={direction2}, expected={expected}, got={result}" test()
def solution(start_1: tuple[int, int], start_2: tuple[int, int], direction_1: tuple[int, int], direction_2: tuple[int, int]) -> bool: """ Determines whether the two balls will collide. Parameters: - start_1: Tuple[int, int], represents the initial position of ball 1 (x, y). - start_2: Tuple[int, int], represents the initial position of ball 2 (x, y). - direction_1: Tuple[int, int], represents the initial direction of ball 1 (dx, dy). dx and dy are integers that can be either -1, 0, or 1. - direction_2: Tuple[int, int], represents the initial direction of ball 2 (dx, dy). dx and dy are integers that can be either -1, 0, or 1. Returns: - bool: True if the balls can collide, False otherwise. """
q14-3
def solution(start: tuple[int, int], direction: tuple[int, int]) -> bool: """ Determines whether the ball can go into the hole Parameters: - start: Tuple[int, int], represents the initial position of the ball (x, y). - direction: Tuple[int, int], represents the initial direction of the ball (dx, dy). dx and dy are integers that can be either -1, 0, or 1. Returns: - bool: True if the ball can go into the hole, False otherwise. """ x, y = start tx1, ty1 = (2, 2) tx2, ty2 = (2, 8) dx, dy = direction while True: x += dx y += dy if (x, y) == (tx1, ty1) or (x, y) == (tx2, ty2): return True if x == 0 or x == 10: dx = -dx if y == 0 or y == 10: dy = -dy if (x, y) == start and (dx, dy) == direction: return False
This image shows a 10x10 coordinate plane with a start point (start) and two black holes. The first hole is located at (2,2), and the second hole is at (2,8). It can be observed that the ball starts from the start point. When the ball hits the boundary, it bounces back with the same angle of incidence, until it enters the first hole.
def test(): test_cases = [ [(8, 7), (1, -1), False], [(8, 7), (-1, -1), False], [(8, 8), (1, -1), True], [(0, 0), (1, 0), False], [(0, 0), (1, 1), True], [(0, 0), (0, 1), False], [(2, 1), (-1, -1), False], [(2, 1), (0, 1), True], [(10, 1), (-1, 1), False], [(7, 1), (1, 1), True], ] for test_case in test_cases: start, direction, expected = test_case result = solution(start, direction) assert result == expected, f"Assert Error: start={start}, direction={direction}, expected={expected}, got={result}" test()
def solution(start: tuple[int, int], direction: tuple[int, int]) -> bool: """ Determines whether the ball can go into the hole Parameters: - start: Tuple[int, int], represents the initial position of the ball (x, y). - direction: Tuple[int, int], represents the initial direction of the ball (dx, dy). dx and dy are integers that can be either -1, 0, or 1. Returns: - bool: True if the ball can go into the hole, False otherwise. """
q15
def solution(layer: int, end_time: int)->int: """ Calculate how many cups have been full-filled by the given end time. Input: - layer: the number of layers in the pyramid structure. - end_time: the given end time. Output: - the total numbers of full-filled cups. """ end_time /= 8.0 if layer < 1 or end_time < 1: return 0 bowls = {} for l in range(1, layer + 1): for i in range(1, l + 1): bowls[(l, i)] = 0.0 bowls[(1, 1)] = float(end_time) for l in range(1, layer): for i in range(1, l + 1): if bowls[(l, i)] > 1: overflow = bowls[(l, i)] - 1 bowls[(l, i)] = 1 if (l + 1, i) in bowls: bowls[(l + 1, i)] += overflow / 2.0 if (l + 1, i + 1) in bowls: bowls[(l + 1, i + 1)] += overflow / 2.0 full_bowls = sum(1 for water in bowls.values() if water >= 1) return full_bowls
This image illustrates a water-filling process, where water gradually flows from the top cup to the cups arranged below. The details are as follows: - t=0, the top cup begins to receive water, but no cups have been fully filled yet. - t=8, the top cup is completely filled, and water flows to the cups below. - t=24, the top cup and two cups on the second level are fully filled, making a total of 3 full cups. The water continues to flow to the lower cups. - t=40, the top cup, the two cups on the second level, and the middle cup on the third level are fully filled, making a total of 4 full cups. While the other two cups on the third level are half-filled.
def test(): test_cases = [ (1, 1*8, 1), (1, 2*8, 1), (2, 1*8, 1), (2, 2*8, 1), (2, 3*8, 3), (3, 1*8, 1), (3, 3*8, 3), (3, 5*8, 4), (3, 7*8, 6), (3, 4*8, 3), (4, 9*8, 8), (4, 25*8, 10), ] for i, (layer, end_time, expected) in enumerate(test_cases): result = solution(layer, end_time) assert result == expected, f"Assert Error: layer={layer}, end_time={end_time}, expected={expected}, result={result}" test()
def solution(layer: int, end_time: int) -> int: """ Calculate how many cups have been full-filled by the given end time. Input: - layer: the number of layers in the pyramid structure. - end_time: the given end time. Output: - the total numbers of full-filled cups. """
q16
def solution(grid: list[int]) -> int: """ Calculate the number of communities according to the image. Input: - grid: A list representing the initial grid, each str element is a row of the grid. The 'x' indicates a black square and '.' indicates a white square. Output: - An integer representing the number of communities. """ if not grid or not grid[0]: return 0 def dfs(i, j): # Stack for DFS stack = [(i, j)] while stack: x, y = stack.pop() if (x, y) in visited: continue visited.add((x, y)) # Check all 8 possible directions (including diagonals) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)]: nx, ny = x + dx, y + dy if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and grid[nx][ny] == '.' and (nx, ny) not in visited: stack.append((nx, ny)) visited = set() communities = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == '.' and (i, j) not in visited: dfs(i, j) communities += 1 return communities
The image shows a grid composed of gray and white squares. There are three "communities" outlined in orange, each containing several connected white squares, labeled with numbers: - The left community: Consists of two vertically connected white squares, labeled "1." - The middle community: Consists of six white squares, labeled "2," with three directly connected and two connected at the corners. - The right community: Consists of one white square, labeled "3."
def test(): test_cases = [ ([".x.x", "xxxx"], 2), (["....", "..xx"], 1), ([".xxxx....", "..xxx.xxx"], 2), (["xxx..", "...x."], 1), (["xxx..xx", "...xx.."], 1), (["x.x..x", ".x...x", "..x.xx", "x.x..."], 1), (["....x..", "xx.x.x.", ".xx..x.", "x.xxxx."], 2) ] for grid, expected in test_cases: result = solution(grid) assert result == expected, f"Assert Error: grid\n {grid}\n expected {expected}, but got {result}" test()
def solution(grid: list[int]) -> int: """ Calculate the number of communities according to the image. Input: - grid: A list representing the initial grid, each str element is a row of the grid. The 'x' indicates a black square and '.' indicates a white square. Output: - An integer representing the number of communities. """
q17
def solution(matrix: list[list[int]]) -> list[list[int]]: """ Refer to the example cases illustrated in the figure, identify and implement the pooling operation on the matrix. Input: - matrix: A 2d list representing the initial matrix. For example, [[1,3,4,2], [2,1,1,3], [1,2,2,4], [3,2,1,0]] Output: - A 2d list representing the resulting matrix after the pooling operation. """ rows = len(matrix) cols = len(matrix[0]) pooled_matrix = [] for i in range(0, rows, 2): pooled_row = [] for j in range(0, cols, 2): block = [ matrix[i][j], matrix[i][j + 1] if j + 1 < cols else float('inf'), matrix[i + 1][j] if i + 1 < rows else float('inf'), matrix[i + 1][j + 1] if i + 1 < rows and j + 1 < cols else float('inf') ] min_value = min(block) pooled_row.append(min_value) pooled_matrix.append(pooled_row) return pooled_matrix
This image shows three different examples of matrix pooling, where each example starts with a larger matrix and results in a smaller matrix. The pooling process involves selecting elements from the larger matrix to form the smaller one. The details are as follows: Example Case 1: In the first example, the original matrix is a 2x2 matrix with the numbers [[1, 2], [3, 4]]. After pooling, the resulting 1x1 matrix contains the value 1. Example Case 2: In the second example, the original matrix is a 4x4 matrix. By reducing each 2x2 region into a single value, the resulting 2x2 matrix contains the values [[1, 4], [2, 0]]. Example Case 3: In the third example, the original matrix is a 6x6 matrix. Each 2x2 region is reduced to a single value, and the final 3x3 matrix contains the values [[1, 2, 0], [2, 3, 0], [2, 4, 2]].
def test(): test_cases = [ { "input": [ [1, 3, 4, 2], [2, 1, 1, 3], [1, 2, 2, 4], [3, 2, 1, 0] ], "expected": [ [1, 1], [1, 0] ] }, { "input": [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ], "expected": [ [1, 3], [9, 11] ] }, { "input": [ [1, 1], [1, 10] ], "expected": [ [1] ] }, { "input": [ [1, 2, 3, 4, 5, 6], [12, 11, 10, 9, 8, 7], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24], [30, 29, 28, 27, 26, 25], [31, 32, 33, 34, 35, 36] ], "expected": [ [1, 3, 5], [13, 15, 17], [29, 27, 25] ] } ] for i, test_case in enumerate(test_cases): x_in = test_case["input"] expected = test_case["expected"] got = solution(x_in) assert got == expected, f"Assert Error: Test case {i} failed: input({x_in}) => output({got}), expected({expected})" test()
def solution(matrix: list[list[int]]) -> list[list[int]]: """ Refer to the example cases illustrated in the figure, identify and implement the pooling operation on the matrix. Input: - matrix: A 2d list representing the initial matrix. For example, [[1,3,4,2], [2,1,1,3], [1,2,2,4], [3,2,1,0]] Output: - A 2d list representing the resulting matrix after the pooling operation. """
q17-2
def solution(matrix: list[list[int]]) -> list[list[int]]: """ Refer to the example cases illustrated in the figure, identify and implement the pooling operation on the matrix. Input: - matrix: A 2d list representing the initial matrix. For example, [[1,3,4,2], [2,1,1,3], [1,2,2,4], [3,2,1,0]] Output: - A 2d list representing the resulting matrix after the pooling operation. """ rows = len(matrix) cols = len(matrix[0]) pooled_matrix = [] for i in range(0, rows, 2): pooled_row = [] for j in range(0, cols, 2): block = [ matrix[i][j], matrix[i][j + 1] if j + 1 < cols else 0, matrix[i + 1][j] if i + 1 < rows else 0, matrix[i + 1][j + 1] if i + 1 < rows and j + 1 < cols else 0 ] max_value = max(abs(num) for num in block) pooled_row.append(max_value if max_value in block else -max_value) pooled_matrix.append(pooled_row) return pooled_matrix
This image shows three examples of matrix pooling, where each example begins with a larger matrix and is reduced to a smaller matrix. The pooling process involves selecting elements from the larger matrix to form the smaller one, with each 2x2 region being reduced to a single value. The details are as follows: Example Case 1: The original matrix is a 2x2 matrix with the numbers [[1, -2], [3, 4]]. After pooling, the resulting 1x1 matrix contains the value 4. Example Case 2: The original matrix is a 4x4 matrix. By reducing each 2x2 region into a single value, the resulting 2x2 matrix contains the values [[-5, 8], [-8, 9]]. To be more specific: - The 2x2 region from the top-left, containing the numbers [[1, 3], [-5, 3]], is turned into -5. - The 2x2 region from the top-right, containing the numbers [[4, -6], [8, -7]] is turned into 8. - The 2x2 region from the bottom-left, containing the numbers [[6, 2], [-8, 2]], is turned into -8. - The 2x2 region from the bottom-right, containing the numbers [[9, 0], [-5, 1]], is turned into 9. Example Case 3: The original matrix is a 6x6 matrix. After reducing each 2x2 region, the resulting 3x3 matrix contains the values [[-4, 9, -9], [7, 7, -8], [5, -6, 9]]. To be more specific: - The 2x2 region from the top-left, containing the numbers [[2, -4], [-1, 2]], is turned into -4. - The 2x2 region from the top-middle, containing the numbers [[2, -7], [9, 7]] is turned into 9. - The 2x2 region from the top-right, containing the numbers [[-9, 0], [5, -3]] is turned into -9. - The 2x2 region from the middle-left, containing the numbers [[-4, 6], [7, -2]] is turned into 7. - The 2x2 region from the middle-middle, containing the numbers [[7, 3], [-6, 3]], is turned into 7. - The 2x2 region from the middle-right, containing the numbers [[7, 2], [-8, 0]], is turned into -8. - The 2x2 region from the bottom-left, containing the numbers [[5, 2], [3, 4]] is turned into 5. - The 2x2 region from the bottom-middle, containing the numbers [[5, 4], [-6, 2]], is turned into -6. - The 2x2 region from the bottom-right, containing the numbers [[8, 5], [9, 2]] is turned into 9. In each case, every 2x2 region in the larger matrix is turned into a single value following a specific rule, forming the smaller matrix.
def test(): test_cases = [ { "input": [ [1, 3, 4, 2], [2, 1, 1, 3], [1, 2, 2, 4], [3, 2, 1, 0] ], "expected": [ [3, 4], [3, 4] ] }, { "input": [ [1, 2, 3, 4], [5, -6, 7, -8], [-9, -10, -11, 12], [13, 14, 15, -16] ], "expected": [ [-6, -8], [14, -16] ] }, { "input": [ [1, 1], [1, 10] ], "expected": [ [10] ] }, { "input": [ [1, -2, 3, 4, 5, -6], [12, 11, -10, 9, 8, 7], [13, 14, 15, 16, -17, 18], [-19, 20, 21, 22, 23, 24], [-30, -29, 28, 27, 26, 25], [31, 32, 33, -34, 35, -36] ], "expected": [ [12, -10, 8], [20, 22, 24], [32, -34, -36] ] } ] for i, test_case in enumerate(test_cases): x_in = test_case["input"] expected = test_case["expected"] got = solution(x_in) assert got == expected, f"Assert Error: Test case {i} failed: input({x_in}) => output({got}), expected({expected})" test()
def solution(matrix: list[list[int]]) -> list[list[int]]: """ Refer to the example cases illustrated in the figure, identify and implement the pooling operation on the matrix. Input: - matrix: A 2d list representing the initial matrix. For example, [[1,3,4,2], [2,1,1,3], [1,2,2,4], [3,2,1,0]] Output: - A 2d list representing the resulting matrix after the pooling operation. """
q17-3
def solution(matrix: list[list[int]]) -> list[list[int]]: """ Refer to the example cases illustrated in the figure, identify and implement the pooling operation on the matrix. Input: - matrix: A 2d list representing the initial matrix. For example, [[1,3,4], [2,1,1], [1,2,2]] Output: - A 2d list representing the resulting matrix after the pooling operation. """ rows = len(matrix) cols = len(matrix[0]) pooled_matrix = [] for i in range(0, rows, 3): pooled_row = [] for j in range(0, cols, 3): block = [ matrix[i][j], matrix[i][j + 1] if j + 1 < cols else float('inf'), matrix[i][j + 2] if j + 2 < cols else float('inf'), matrix[i + 1][j] if i + 1 < rows else float('inf'), matrix[i + 2][j] if i + 2 < rows else float('inf'), matrix[i + 1][j + 1] if i + 1 < rows and j + 1 < cols else float('inf'), matrix[i + 2][j + 2] if i + 2 < rows and j + 2 < cols else float('inf'), matrix[i + 1][j + 2] if i + 1 < rows and j + 2 < cols else float('inf'), matrix[i + 2][j + 1] if i + 2 < rows and j + 1 < cols else float('inf'), ] min_value = min(block) pooled_row.append(min_value) pooled_matrix.append(pooled_row) return pooled_matrix
This image shows three different examples of matrix pooling, where each example starts with a larger matrix and results in a smaller matrix. The pooling process involves selecting elements from the larger matrix to form the smaller one. The details are as follows: Example Case 1: In the first example, the original matrix is a 3x3 matrix with the numbers [[1, 2, 6], [3, 4, 3], [8, 7, 9]]. After pooling, the resulting 1x1 matrix contains the value 1. Example Case 2: In the second example, the original matrix is a 6x6 matrix. By reducing each 3x3 region into a single value, the resulting 2x2 matrix contains the values [[1, 0], [2, 3]]. Example Case 3: In the third example, the original matrix is a 9x9 matrix. Each 3x3 region is reduced to a single value, and the final 3x3 matrix contains the values [[1, 3, 4], [0, 0, 5], [2, 2, 3]]. In each case, every 3x3 region in the larger matrix is eventually reduced to a single value, forming the smaller matrix.
def test(): test_cases = [ { "input": [ [1, 3, 4, 2, 0, 3], [2, 1, 1, 3, 2, 6], [1, 2, 2, 4, 4, 7], [3, 2, 1, 0, 1, 0], [1, 7, 5, 2, 2, 0], [2, 9, 1, 2, 3, 1], ], "expected": [ [1, 0], [1, 0] ] }, { "input": [ [1, 2, 3, 4, 3, 4], [5, 6, 7, 8, 1, 0], [9, 10, 11, 12, 2, 9], [13, 14, 15, 16, 0, 1], [1, 6, 3, 8, 9, 7], [0, 4, 3, 3, 0, 2], ], "expected": [ [1, 0], [0, 0] ] }, { "input": [ [1, 1, 4], [1, 10, 3], [2, 1, 2], ], "expected": [ [1] ] }, { "input": [ [1, 2, 3, 4, 5, 6, 4, 5, 1], [12, 11, 10, 9, 8, 7, 0, 3, 4], [13, 14, 15, 16, 17, 18, 2, 9, 7], [19, 20, 21, 22, 23, 24, 4, 8, 6], [30, 29, 28, 27, 26, 25, 2, 2, 4], [31, 32, 33, 34, 35, 36, 7, 7, 8], [43, 44, 12, 22, 45, 46, 65, 23, 25], [56, 45, 23, 27, 32, 35, 36, 57, 64], [54, 34, 43, 34, 23, 33, 45, 43, 54], ], "expected": [ [1, 4, 0], [19, 22, 2], [12, 22, 23] ] } ] for i, test_case in enumerate(test_cases): x_in = test_case["input"] expected = test_case["expected"] got = solution(x_in) assert got == expected, f"Assert Error: Test case {i} failed: input({x_in}) => output({got}), expected({expected})" test()
def solution(matrix: list[list[int]]) -> list[list[int]]: """ Refer to the example cases illustrated in the figure, identify and implement the pooling operation on the matrix. Input: - matrix: A 2d list representing the initial matrix. For example, [[1,3,4], [2,1,1], [1,2,2]] Output: - A 2d list representing the resulting matrix after the pooling operation. """
q18
from typing import List def solution(matrix: List[List[int]]) -> List[int]: """ Given an M x N 2D matrix, traverse the matrix according to the spiral pattern shown in the figure Parameters: matrix (List[List[int]]): A 2D list of integers representing the matrix. Returns: List[int]: A list of integers representing the elements of the matrix in the order as shown in the picture. """ result = [] top, bottom = 0, len(matrix) - 1 left, right = 0, len(matrix[0]) - 1 while top <= bottom and left <= right: # Traverse from right to left for i in range(right, left - 1, -1): result.append(matrix[top][i]) top += 1 # Traverse from top to bottom for i in range(top, bottom + 1): result.append(matrix[i][left]) left += 1 if top <= bottom: # Traverse from left to right for i in range(left, right + 1): result.append(matrix[bottom][i]) bottom -= 1 if left <= right: # Traverse from bottom to top for i in range(bottom, top - 1, -1): result.append(matrix[i][right]) right -= 1 return result
This image describes the traversal process of a two-dimensional matrix in a specific pattern: Top-right matrix (4x1 matrix): - Traversal starts from the right side at 4 and moves to the left side, ending at 1. Top-left matrix (4x2 matrix): - Traversal starts from the top-right corner, moves left to 1, then moves down to 5, and finally moves right to 8. Bottom-left matrix (4x3 matrix): - Traversal starts from the top-right corner, moves left to 1, then down to 9, right to 12, up to 8, and finally left to 6. Bottom-right matrix: - Traversal starts from the top-right corner, moves left to 1, down to 13, right to 16, up to 8, left to 6, down to 10, and finally right to 11. The traversal pattern is consistent across all four matrices, seems to be a spiral tranversal starting from the top-right corner and moving counter-clockwise.
def test(): test_cases = [ ([[1, 2]], [2, 1]), ([[1, 2], [3, 4]], [2, 1, 3, 4]), ([[1, 2, 3], [4, 5, 6], [7, 8 , 9]], [3, 2, 1, 4, 7, 8, 9, 6, 5]), ([[1,2,3,4], [5,6,7,8], [9,10,11,12]], [4, 3, 2, 1, 5, 9, 10, 11, 12, 8, 7, 6]), ([[1, 3, 5, 6, 2], [43, 23, 19, 22, 33], [12, 11, 6, 8, 4]], [2, 6, 5, 3, 1, 43, 12, 11, 6, 8, 4, 33, 22, 19, 23]), ([[1, 2], [3, 4], [5, 6], [7, 8]], [2, 1, 3, 5, 7, 8, 6, 4]), ([[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]], [7, 6, 5, 4, 3, 2, 1, 8, 9, 10, 11, 12, 13, 14]), ([[1, 2, 3, 4, 5, 6, 7, 8], [13, 24, 32, 41, 54, 65, 76, 87], [43, 2, 87, 5, 4, 66, 13, 94], [0, 12, 87, 43, 56, 36, 92, 44], [32, 33, 34, 55, 56, 72, 73, 77]], [8, 7, 6, 5, 4, 3, 2, 1, 13, 43, 0, 32, 33, 34, 55, 56, 72, 73, 77, 44, 94, 87, 76, 65, 54, 41, 32, 24, 2, 12, 87, 43, 56, 36, 92, 13, 66, 4, 5, 87]), ([[1, 3, 5], [7, 9, 11], [2, 4, 6], [8, 10, 14]], [5, 3, 1, 7, 2, 8, 10, 14, 6, 11, 9, 4]), ([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 17], [13, 15, 16, 19, 20, 91]], [6, 5, 4, 3, 2, 1, 7, 13, 15, 16, 19, 20, 91, 17, 11, 10, 9, 8]), ] for i, (matrix, expected) in enumerate(test_cases): result = solution(matrix) assert result == expected, f"Assert Error: Input {matrix}, Expected {expected}, Got: {result}" test()
from typing import List def solution(matrix: List[List[int]]) -> List[int]: """ Given an M x N 2D matrix, traverse the matrix according to the spiral pattern shown in the figure Parameters: matrix (List[List[int]]): A 2D list of integers representing the matrix. Returns: List[int]: A list of integers representing the elements of the matrix in the order as shown in the picture. """
q18-2
from typing import List def solution(matrix: List[List[int]]) -> List[int]: """ Given an M x N 2D matrix, traverse the matrix according to the spiral pattern shown in the figure Parameters: matrix (List[List[int]]): A 2D list of integers representing the matrix. Returns: List[int]: A list of integers representing the elements of the matrix in the order as shown in the picture. """ result = [] top, bottom = 0, len(matrix) - 1 left, right = 0, len(matrix[0]) - 1 while bottom >= top and left <= right: # Traverse from right to left for i in range(right, left - 1, -1): result.append(matrix[bottom][i]) bottom -= 1 # Traverse from bottom to top for i in range(bottom, top - 1, -1): result.append(matrix[i][left]) left += 1 if bottom >= top: # Traverse from left to right for i in range(left, right + 1): result.append(matrix[top][i]) top += 1 if left <= right: # Traverse from top to bottom for i in range(top, bottom + 1): result.append(matrix[i][right]) right -= 1 return result
This image describes the traversal process of a two-dimensional matrix in a specific pattern: CASE 1: Top-right matrix (4x1 matrix): - The traversal starts from 4 and moves left to 1. CASE 2: Top-left matrix (4x2 matrix): - Starting from the bottom-right corner, it traverses leftward to 5, then moves up to 1, and finally traverses rightward to 4. CASE 3: Bottom-left matrix (4x3 matrix): - Starting from the bottom-right corner, it moves left to 9, then up to 1, continues rightward to 4, and moves down to 8, ending by moving leftward to 6. CASE 4: Bottom-right matrix (4x4 matrix): - The traversal begins at the bottom-right corner, moving left to 13, then up to 1, followed by a rightward traversal to 4, then moves down to 12, left to 10, up to 6, and finishes by moving rightward to 7. The traversal pattern is consistent across all four matrices, following a spiral pattern starting from the bottom-right corner and moving clockwise.
def test(): test_cases = [ ([[1, 2]], [2, 1]), ([[1, 2], [3, 4]], [4, 3, 1, 2]), ([[1, 2, 3], [4, 5, 6], [7, 8 , 9]], [9, 8, 7, 4, 1, 2, 3, 6, 5]), ([[1,2,3,4], [5,6,7,8], [9,10,11,12]], [12, 11, 10, 9, 5, 1, 2, 3, 4, 8, 7, 6]), ([[1, 3, 5, 6, 2], [43, 23, 19, 22, 33], [12, 11, 6, 8, 4]], [4, 8, 6, 11, 12, 43, 1, 3, 5, 6, 2, 33, 22, 19, 23]), ([[1, 2], [3, 4], [5, 6], [7, 8]], [8, 7, 5, 3, 1, 2, 4, 6]), ([[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]], [14, 13, 12, 11, 10, 9, 8, 1, 2, 3, 4, 5, 6, 7]), ([[1, 2, 3, 4, 5, 6, 7, 8], [13, 24, 32, 41, 54, 65, 76, 87], [43, 2, 87, 5, 4, 66, 13, 94], [0, 12, 87, 43, 56, 36, 92, 44], [32, 33, 34, 55, 56, 72, 73, 77]], [77, 73, 72, 56, 55, 34, 33, 32, 0, 43, 13, 1, 2, 3, 4, 5, 6, 7, 8, 87, 94, 44, 92, 36, 56, 43, 87, 12, 2, 24, 32, 41, 54, 65, 76, 13, 66, 4, 5, 87]), ([[1, 3, 5], [7, 9, 11], [2, 4, 6], [8, 10, 14]], [14, 10, 8, 2, 7, 1, 3, 5, 11, 6, 4, 9]), ([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 17], [13, 15, 16, 19, 20, 91]], [91, 20, 19, 16, 15, 13, 7, 1, 2, 3, 4, 5, 6, 17, 11, 10, 9, 8]), ] for i, (matrix, expected) in enumerate(test_cases): result = solution(matrix) assert result == expected, f"Assert Error: Input {matrix}, Expected {expected}, Got: {result}" test()
from typing import List def solution(matrix: List[List[int]]) -> List[int]: """ Given an M x N 2D matrix, traverse the matrix according to the spiral pattern shown in the figure Parameters: matrix (List[List[int]]): A 2D list of integers representing the matrix. Returns: List[int]: A list of integers representing the elements of the matrix in the order as shown in the picture. """
q18-3
from typing import List def solution(matrix: List[List[int]]) -> List[int]: """ Given an M x N 2D matrix, traverse the matrix according to the spiral pattern shown in the figure Parameters: matrix (List[List[int]]): A 2D list of integers representing the matrix. Returns: List[int]: A list of integers representing the elements of the matrix in the order as shown in the picture. """ result = [] top, bottom = 0, len(matrix) - 1 left, right = 0, len(matrix[0]) - 1 while top <= bottom and left <= right: # Traverse from left to right for i in range(left, right + 1): result.append(matrix[bottom][i]) bottom -= 1 # Traverse from bottom to top for i in range(bottom, top - 1, -1): result.append(matrix[i][right]) right -= 1 if top <= bottom: # Traverse from right to left for i in range(right, left - 1, -1): result.append(matrix[top][i]) top += 1 if left <= right: # Traverse from top to bottom for i in range(top, bottom + 1): result.append(matrix[i][left]) left += 1 return result
This image describes the traversal process of a two-dimensional matrix in a specific pattern: Here are some examples given in the image: CASE 1: Top-right matrix (4x1 matrix): - The traversal starts from 1 and moves right to 4. CASE 2: Top-left matrix (4x2 matrix): - Starting from 5 in the bottom left, move right to 8, then up to 4, and finally left to 1. CASE 3: Bottom-left matrix (4x3 matrix): - Starting from 9 in the bottom left, move right to 12, up to 4, then left to 1, down to 5, and right to 7. CASE 4: Bottom-right matrix (4x4 matrix): - Starting from the bottom left, move right to 16, up to 4, left to 1, down to 9, right to 11, up to 7, and finally left to 6. The traversal pattern is consistent across all four matrices, following a spiral pattern starting from the bottom left corner and moving counter-clockwise.
def test(): test_cases = [ ([[1, 2]], [1, 2]), ([[1, 2], [3, 4]], [3, 4, 2, 1]), ([[1, 2, 3], [4, 5, 6], [7, 8 , 9]], [7, 8, 9, 6, 3, 2, 1, 4, 5]), ([[1,2,3,4], [5,6,7,8], [9,10,11,12]], [9, 10, 11, 12, 8, 4, 3, 2, 1, 5, 6, 7]), ([[1, 3, 5, 6, 2], [43, 23, 19, 22, 33], [12, 11, 6, 8, 4]], [12, 11, 6, 8, 4, 33, 2, 6, 5, 3, 1, 43, 23, 19, 22]), ([[1, 2], [3, 4], [5, 6], [7, 8]], [7, 8, 6, 4, 2, 1, 3, 5]), ([[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]], [8, 9, 10, 11, 12, 13, 14, 7, 6, 5, 4, 3, 2, 1]), ([[1, 2, 3, 4, 5, 6, 7, 8], [13, 24, 32, 41, 54, 65, 76, 87], [43, 2, 87, 5, 4, 66, 13, 94], [0, 12, 87, 43, 56, 36, 92, 44], [32, 33, 34, 55, 56, 72, 73, 77]], [32, 33, 34, 55, 56, 72, 73, 77, 44, 94, 87, 8, 7, 6, 5, 4, 3, 2, 1, 13, 43, 0, 12, 87, 43, 56, 36, 92, 13, 76, 65, 54, 41, 32, 24, 2, 87, 5, 4, 66]), ([[1, 3, 5], [7, 9, 11], [2, 4, 6], [8, 10, 14]], [8, 10, 14, 6, 11, 5, 3, 1, 7, 2, 4, 9]), ([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 17], [13, 15, 16, 19, 20, 91]], [13, 15, 16, 19, 20, 91, 17, 6, 5, 4, 3, 2, 1, 7, 8, 9, 10, 11]), ] for i, (matrix, expected) in enumerate(test_cases): result = solution(matrix) assert result == expected, f"Assert Error: Input {matrix}, Expected {expected}, Got: {result}" test()
from typing import List def solution(matrix: List[List[int]]) -> List[int]: """ Given an M x N 2D matrix, traverse the matrix according to the spiral pattern shown in the figure Parameters: matrix (List[List[int]]): A 2D list of integers representing the matrix. Returns: List[int]: A list of integers representing the elements of the matrix in the order as shown in the picture. """
q19
def solution(dragon_life: float, player_life: float, dragon_attack_point: float, player_attack_point: float) -> int: """ Build the dragon slaying game as shown in the diagram, and calculate how many life points the winner has left. Parameters: dragon_life (float): The life points of the dragon. player_life (float): The life points of the player. dragon_attack_point (float): The base attack points of the dragon. player_attack_point (float): The base attack points of the player. Returns: int: The life points of the winner (rounded down). """ status = 1 while True: dragon_life -= player_attack_point if dragon_life <= 0: return int(player_life) if dragon_life < 60 and status == 1: status = 2 player_attack_point *= 1.2 dragon_attack_point *= 0.8 player_life -= dragon_attack_point if player_life <= 0: return int(dragon_life)
This image is a flowchart describing the battle process between a player and a dragon, divided into two statuses. Status 1: - Player attacks the dragon with 100% attack power. - Check dragon's life: - If life > 0, continue. - If life ≤ 0, game over. - If dragon's life < 60, shift to Status 2. - Otherwise, Dragon attacks the player with 100% attack power. - Check player's life: - If life > 0, return to player's attack. - If life ≤ 0, game over. Status 2: - Dragon attacks the player with 80% attack power. - Check player's life: - If life > 0, continue. - If life ≤ 0, game over. - Player attacks the dragon with 120% attack power. - Check dragon's life: - If life > 0, continue. - If life ≤ 0, game over.
def test(): test_cases = [ (100, 90, 10, 5, 49), (59.9, 78, 60, 26.6, 1), (1000.1, 100.79, 8.54, 50.3, 396), (63, 100, 100, 1, 62), (1000.34, 10, 11, 1001, 10), (150.33, 176.24, 23.5, 26.8, 68), (92.3, 11.1, 1, 32.3, 9), (12384.4, 13323.9, 10.1, 11.1, 2080), (11111111.223, 11847382.68, 3.3, 4.4, 3514065), (1321137281.11, 837272819.23, 55.9, 666, 726384604), ] for i, (dragon_life, player_life, dragon_attack_point, player_attack_point, expected) in enumerate(test_cases): result = solution(dragon_life, player_life, dragon_attack_point, player_attack_point) assert result == expected, f"Assert Error: Input {(dragon_life, player_life, dragon_attack_point, player_attack_point)}, Expected {expected}, Got: {result}" test()
def solution(dragon_life: float, player_life: float, dragon_attack_point: float, player_attack_point: float) -> int: """ Build the dragon slaying game as shown in the diagram, and calculate how many life points the winner has left. Parameters: dragon_life (float): The life points of the dragon. player_life (float): The life points of the player. dragon_attack_point (float): The base attack points of the dragon. player_attack_point (float): The base attack points of the player. Returns: int: The life points of the winner (rounded down). """
q19-2
def solution(dragon_life: float, player_life: float, dragon_attack_point: float, player_attack_point: float) -> int: """ Build the dragon slaying game as shown in the diagram, and calculate how many life points the winner has left. Parameters: dragon_life (float): The life points of the dragon. player_life (float): The life points of the player. dragon_attack_point (float): The base attack points of the dragon. player_attack_point (float): The base attack points of the player. Returns: int: The life points of the winner (rounded down). """ status = 1 while True: dragon_life -= player_attack_point if dragon_life <= 0: return int(player_life) if dragon_life < 40 and status == 1: status = 2 player_attack_point *= 1.35 dragon_attack_point *= 0.65 player_life -= dragon_attack_point if player_life <= 0: return int(dragon_life)
This image is a flowchart describing the battle process between a player and a dragon, divided into two statuses. Status 1: - Player attacks the dragon with 100% attack power. - Check dragon's life: - If life > 0, continue. - If life ≤ 0, game over. - If dragon's life < 40, shift to Status 2. - Otherwise, Dragon attacks the player with 100% attack power. - Check player's life: - If life > 0, return to player's attack. - If life ≤ 0, game over. Status 2: - Dragon attacks the player with 65% attack power. - Check player's life: - If life > 0, continue. - If life ≤ 0, game over. - Player attacks the dragon with 135% attack power. - Check dragon's life: - If life > 0, continue. - If life ≤ 0, game over.
def test(): test_cases = [ (100, 90, 10, 5, 55), (59.9, 78, 60, 26.6, 39), (1000.1, 100.79, 8.54, 50.3, 396), (63, 100, 100, 1, 62), (1000.34, 10, 11, 1001, 10), (150.33, 176.24, 23.5, 26.8, 66), (92.3, 11.1, 1, 32.3, 9), (12384.4, 13323.9, 10.1, 11.1, 2073), (11111111.223, 11847382.68, 3.3, 4.4, 3514065), (1321137281.11, 837272819.23, 55.9, 666, 726384604), ] for i, (dragon_life, player_life, dragon_attack_point, player_attack_point, expected) in enumerate(test_cases): result = solution(dragon_life, player_life, dragon_attack_point, player_attack_point) assert result == expected, f"Assert Error: Input {(dragon_life, player_life, dragon_attack_point, player_attack_point)}, Expected {expected}, Got: {result}" test()
def solution(dragon_life: float, player_life: float, dragon_attack_point: float, player_attack_point: float) -> int: """ Build the dragon slaying game as shown in the diagram, and calculate how many life points the winner has left. Parameters: dragon_life (float): The life points of the dragon. player_life (float): The life points of the player. dragon_attack_point (float): The base attack points of the dragon. player_attack_point (float): The base attack points of the player. Returns: int: The life points of the winner (rounded down). """
q19-3
def solution(dragon_life: float, player_life: float, dragon_attack_point: float, player_attack_point: float) -> int: """ Build the dragon slaying game as shown in the diagram, and calculate how many life points the winner has left. Parameters: dragon_life (float): The life points of the dragon. player_life (float): The life points of the player. dragon_attack_point (float): The base attack points of the dragon. player_attack_point (float): The base attack points of the player. Returns: int: The life points of the winner (rounded down). """ status = 1 while True: player_life -= dragon_attack_point if player_life <= 0: return int(dragon_life) if player_life < 60 and status == 1: status = 2 dragon_attack_point *= 1.2 player_attack_point *= 0.8 dragon_life -= player_attack_point if dragon_life <= 0: return int(player_life)
This image is a flowchart describing the battle process between a dragon and a player, divided into two statuses. Status 1: - Dragon attacks the player with 100% attack point. - Check player's life: - If life > 0, continue. - If life ≤ 0, game over. - If player's life < 60, shift to Status 2. - Otherwise, Player attacks the dragon with 100% attack point. - Check dragon's life: - If life > 0, continue. - If life ≤ 0, game over. Status 2: - Player attacks the dragon with 80% attack point. - Check dragon's life: - If life > 0, continue. - If life ≤ 0, game over. - Dragon attacks the player with 120% attack point. - Check player's life: - If life > 0, continue. - If life ≤ 0, game over.
def test(): test_cases = [ (90, 100, 5, 10, 49), (78, 59.9, 26.6, 60, 1), (100.79, 1000.1, 50.3, 8.54, 396), (100, 63, 1, 100, 62), (10, 1000.34, 1001, 11, 10), (176.24, 150.33, 26.8, 23.5, 68), (11.1, 92.3, 32.3, 1, 9), (13323.9, 12384.4, 11.1, 10.1, 2080), (11847382.68, 11111111.223, 4.4, 3.3, 3514065), (837272819.23, 1321137281.11, 666, 55.9, 726384604), ] for i, (dragon_life, player_life, dragon_attack_point, player_attack_point, expected) in enumerate(test_cases): result = solution(dragon_life, player_life, dragon_attack_point, player_attack_point) assert result == expected, f"Assert Error: Input {(dragon_life, player_life, dragon_attack_point, player_attack_point)}, Expected {expected}, Got: {result}" test()
def solution(dragon_life: float, player_life: float, dragon_attack_point: float, player_attack_point: float) -> int: """ Build the dragon slaying game as shown in the diagram, and calculate how many life points the winner has left. Parameters: dragon_life (float): The life points of the dragon. player_life (float): The life points of the player. dragon_attack_point (float): The base attack points of the dragon. player_attack_point (float): The base attack points of the player. Returns: int: The life points of the winner (rounded down). """
q2
import numpy as np def solution() -> np.ndarray: """ generate a set of 1000 data points that match the distribution shown in the figure Returns: np.ndarray: A 2D array of shape (1000, 2), where each row contains the x and y coordinates of a point. """ num_points = 1000 points = np.zeros((num_points, 2)) # Initialize array to hold points center_x, center_y = 0.5, 0.5 radius = 0.25 count = 0 while count < num_points: x, y = np.random.rand(2) # Generate random x, y coordinates # Check if the point is outside the circle if (x - center_x)**2 + (y - center_y)**2 >= radius**2: points[count] = [x, y] count += 1 return points
The image shows many blue dots within a 1 x 1 square area. Except for a circular region centered at (0.5, 0.5) with a radius of 0.25, these blue dots are randomly distributed throughout the square area.
import numpy as np def quartile_test(points): x_quartiles = np.percentile(points[:, 0], [25, 50, 75]) y_quartiles = np.percentile(points[:, 1], [25, 50, 75]) theoretical_quartiles = [0.2, 0.5, 0.8] x_check = np.allclose(x_quartiles, theoretical_quartiles, atol=0.1) y_check = np.allclose(y_quartiles, theoretical_quartiles, atol=0.1) return x_check and y_check def test(): points = solution() assert points.shape == (1000, 2), "Assert Error: The number of points generated is not 1000." center_x, center_y = 0.5, 0.5 radius = 0.25 distances = np.sqrt((points[:, 0] - center_x)**2 + (points[:, 1] - center_y)**2) assert np.all(distances >= radius), "Assert Error: Some points are inside the exclusion zone." assert quartile_test(points), "Assert Error: Quartile test suggests points are not uniformly distributed." test()
import numpy as np def solution() -> np.ndarray: """ generate a set of 1000 data points that match the distribution shown in the figure Returns: np.ndarray: A 2D array of shape (1000, 2), where each row contains the x and y coordinates of a point. """
q2-2
import numpy as np def solution() -> np.ndarray: """ generate a set of 1000 data points that match the distribution shown in the figure Returns: np.ndarray: A 2D array of shape (1000, 2), where each row contains the x and y coordinates of a point. """ num_points = 1000 points = np.zeros((num_points, 2)) # Initialize array to hold points center_x, center_y = 0.5, 0.5 radius = 0.25 count = 0 while count < num_points: x, y = np.random.rand(2) # Generate random x, y coordinates # Check if the point is inside the circle if (x - center_x)**2 + (y - center_y)**2 <= radius**2: points[count] = [x, y] count += 1 return points
The image shows many blue dots within a 1 x 1 square area. These blue dots are randomly distributed throughout a circular region centered at (0.5, 0.5) with a radius of 0.25.
import numpy as np def quartile_test(points): x_quartiles = np.percentile(points[:, 0], [25, 50, 75]) y_quartiles = np.percentile(points[:, 1], [25, 50, 75]) theoretical_quartiles = [0.4, 0.5, 0.6] x_check = np.allclose(x_quartiles, theoretical_quartiles, atol=0.1) y_check = np.allclose(y_quartiles, theoretical_quartiles, atol=0.1) return x_check and y_check def test(): points = solution() assert points.shape == (1000, 2), "Assert Error: The number of points generated is not 1000." center_x, center_y = 0.5, 0.5 radius = 0.25 distances = np.sqrt((points[:, 0] - center_x)**2 + (points[:, 1] - center_y)**2) assert np.all(distances <= radius), "Assert Error: Some points are inside the exclusion zone." assert quartile_test(points), "Assert Error: Quartile test suggests points are not uniformly distributed." test()
import numpy as np def solution() -> np.ndarray: """ generate a set of 1000 data points that match the distribution shown in the figure Returns: np.ndarray: A 2D array of shape (1000, 2), where each row contains the x and y coordinates of a point. """
q2-3
import numpy as np def solution() -> np.ndarray: """ generate a set of 1000 data points that match the distribution shown in the figure Returns: np.ndarray: A 2D array of shape (1000, 2), where each row contains the x and y coordinates of a point. """ num_points = 1000 points = np.zeros((num_points, 2)) # Initialize array to hold points center_x, center_y = 0.5, 0.5 width = 0.5 # Width of the ellipse height = 0.25 # Height of the ellipse count = 0 while count < num_points: x, y = np.random.rand(2) # Generate random x, y coordinates # Check if the point is outside the ellipse if ((x - center_x)**2 / (width / 2)**2 + (y - center_y)**2 / (height / 2)**2) >= 1: points[count] = [x, y] count += 1 return points
The image shows many blue dots within a 1 x 1 square area. These blue dots are randomly distributed throughout an elliptical region. The ellipse is centered at (0.5, 0.5) and has a major axis of 0.25 and a minor axis of 0.125.
import numpy as np def quartile_test(points): x_quartiles = np.percentile(points[:, 0], [25, 50, 75]) y_quartiles = np.percentile(points[:, 1], [25, 50, 75]) theoretical_x_quartiles = [0.2, 0.5, 0.8] theoretical_y_quartiles = [0.2, 0.5, 0.8] x_check = np.allclose(x_quartiles, theoretical_x_quartiles, atol=0.1) y_check = np.allclose(y_quartiles, theoretical_y_quartiles, atol=0.1) return x_check and y_check def test(): points = solution() assert points.shape == (1000, 2), "Assert Error: The number of points generated is not 1000." center_x, center_y = 0.5, 0.5 width = 0.5 # Width of the ellipse height = 0.25 # Height of the ellipse assert np.all(((points[:, 0] - center_x)**2 / (width / 2)**2 + (points[:, 1] - center_y)**2 / (height / 2)**2) >= 1), "Assert Error: Some points are inside the exclusion zone." assert quartile_test(points), "Assert Error: Quartile test suggests points are not uniformly distributed." test()
import numpy as np def solution() -> np.ndarray: """ generate a set of 1000 data points that match the distribution shown in the figure Returns: np.ndarray: A 2D array of shape (1000, 2), where each row contains the x and y coordinates of a point. """
q20
from typing import List def solution(swaps: List[str], initial_position: int) -> int: """ Determine the final position of the ball after a series of swaps. Parameters: swaps (List[str]): A list of operation ids ('A', 'B', 'C', 'D', 'E', or 'F') representing the sequence of cup swap operations. initial_position (int): The number of the cup where the ball is initially placed. Returns: int: The number of the cup where the ball is finally located. """ swap_operations = { 'A': (1, 2), 'B': (1, 3), 'C': (2, 3), 'D': (2, 4), 'E': (3, 4), 'F': (1, 4) } position = initial_position for swap in swaps: if swap in swap_operations: cup1, cup2 = swap_operations[swap] if position == cup1: position = cup2 elif position == cup2: position = cup1 return position
This image illustrates a sequence of swaps involving four cups and a red ball. Each cup is labeled from 1 to 4, and the position of the red ball changes in different steps: - A: Cup 1 and 2 swap positions. - B: Cup 1 and 3 swap positions. - C: Cup 2 and 3 swap positions. - D: Cup 2 and 4 swap positions. - E: Cup 3 and 4 swap positions. - F: Cup 1 and 4 swap positions. Arrows indicate the direction of each swap.
def test(): test_cases = [ (['A'], 1, 2), (['A'], 3, 3), (['B'], 3, 1), (['A', 'B', 'C'], 2, 2), (['D', 'E', 'A', 'C', 'B'], 4, 3), (['E', 'C', 'A', 'B', 'C', 'E', 'D'], 3, 3), (['A', 'C', 'E', 'D'], 1, 2), (['A', 'E', 'D', 'A', 'C', 'A', 'D', 'E', 'B'], 2, 4), (['B', 'E', 'A', 'C', 'D', 'A', 'C'], 4, 4), (['A', 'B', 'C', 'D', 'E', 'C', 'A'], 1, 4), (['B', 'E', 'A', 'C', 'D', 'A', 'C', 'A', 'C', 'E', 'B', 'A', 'D'], 4, 4), ] for i, (swaps, initial_position, expected) in enumerate(test_cases): original_swaps = swaps[:] result = solution(swaps, initial_position) assert result == expected, f"Assert Error: Input {(original_swaps, initial_position)}, Expected {expected}, Got: {result}" test()
from typing import List def solution(swaps: List[str], initial_position: int) -> int: """ Determine the final position of the ball after a series of swaps. Parameters: swaps (List[str]): A list of operation ids ('A', 'B', 'C', 'D', 'E', or 'F') representing the sequence of cup swap operations. initial_position (int): The number of the cup where the ball is initially placed. Returns: int: The number of the cup where the ball is finally located. """
q20-2
from typing import List def solution(swaps: List[str], initial_position: int) -> int: """ Determine the final position of the ball after a series of swaps. Parameters: swaps (List[str]): A list of operation ids ('A', 'B', 'C') representing the sequence of cup swap operations. initial_position (int): The number of the cup where the ball is initially placed. Returns: int: The number of the cup where the ball is finally located. """ swap_operations = { 'A': (1, 2), 'B': (3, 4), 'C': (2, 3), } position = initial_position for swap in swaps: if swap in swap_operations: cup1, cup2 = swap_operations[swap] if position == cup1: position = cup2 elif position == cup2: position = cup1 return position
This image illustrates a sequence of swaps involving four cups and a red ball. Each cup is labeled from 1 to 4, and the position of the red ball changes in different steps: - A: Cup 1 and 2 swap positions. - B: Cup 3 and 4 swap positions. - C: Cup 2 and 3 swap positions. Arrows indicate the direction of each swap.
def test(): test_cases = [ (['A'], 1, 2), (['A'], 3, 3), (['B'], 3, 4), (['A', 'B', 'C'], 2, 1), (['C', 'A', 'A', 'C', 'B'], 4, 3), (['B', 'C', 'A', 'B', 'C', 'B', 'A'], 3, 1), (['A', 'C', 'B', 'C'], 1, 4), (['A', 'B', 'B', 'C', 'C', 'B', 'A', 'C', 'B'], 2, 4), (['B', 'A', 'A', 'C', 'B', 'C', 'A'], 4, 3), (['A', 'B', 'C', 'B', 'A', 'C', 'B'], 1, 3), (['B', 'A', 'B', 'C', 'A', 'C', 'B', 'A', 'C', 'A', 'B', 'A', 'C'], 4, 3), ] for i, (swaps, initial_position, expected) in enumerate(test_cases): original_swaps = swaps[:] result = solution(swaps, initial_position) assert result == expected, f"Assert Error: Input {(original_swaps, initial_position)}, Expected {expected}, Got: {result}" test()
from typing import List def solution(swaps: List[str], initial_position: int) -> int: """ Determine the final position of the ball after a series of swaps. Parameters: swaps (List[str]): A list of operation ids ('A', 'B', 'C') representing the sequence of cup swap operations. initial_position (int): The number of the cup where the ball is initially placed. Returns: int: The number of the cup where the ball is finally located. """
q20-3
from typing import List def solution(swaps: List[str], initial_position: int) -> int: """ Determine the final position of the ball after a series of swaps. Parameters: swaps (List[str]): A list of operation ids ('A', 'B', 'C') representing the sequence of cup swap operations. initial_position (int): The number of the cup where the ball is initially placed. Returns: int: The number of the cup where the ball is finally located. """ swap_operations = { 'A': (1, 2), 'B': (1, 3), 'C': (2, 3), } position = initial_position for swap in swaps: if swap in swap_operations: cup1, cup2 = swap_operations[swap] if position == cup1: position = cup2 elif position == cup2: position = cup1 return position
This image illustrates a sequence of swaps involving four cups and a red ball. Each cup is labeled from 1 to 3, and the position of the red ball changes in different steps: - A: Cup 1 and 2 swap positions. - B: Cup 1 and 3 swap positions. - C: Cup 2 and 3 swap positions. Arrows indicate the direction of each swap.
def test(): test_cases = [ (['A'], 1, 2), (['A'], 3, 3), (['B'], 3, 1), (['A', 'B', 'C'], 2, 2), (['C', 'A', 'A', 'C', 'B'], 1, 3), (['B', 'C', 'A', 'B', 'C', 'B', 'A'], 3, 2), (['A', 'C', 'B', 'C'], 1, 1), (['A', 'B', 'B', 'C', 'C', 'B', 'A', 'C', 'B'], 2, 2), (['B', 'A', 'A', 'C', 'B', 'C', 'A'], 3, 1), (['A', 'B', 'C', 'B', 'A', 'C', 'B'], 1, 1), (['B', 'A', 'B', 'C', 'A', 'C', 'B', 'A', 'C', 'A', 'B', 'A', 'C'], 2, 2), ] for i, (swaps, initial_position, expected) in enumerate(test_cases): original_swaps = swaps[:] result = solution(swaps, initial_position) assert result == expected, f"Assert Error: Input {(original_swaps, initial_position)}, Expected {expected}, Got: {result}" test()
from typing import List def solution(swaps: List[str], initial_position: int) -> int: """ Determine the final position of the ball after a series of swaps. Parameters: swaps (List[str]): A list of operation ids ('A', 'B', 'C') representing the sequence of cup swap operations. initial_position (int): The number of the cup where the ball is initially placed. Returns: int: The number of the cup where the ball is finally located. """
q21
from math import gcd def solution(x: int, y: int) -> str: """ Determine the first laser receiver encountered by the laser in the square area Parameters: x (int): The length of x. y (int): The length of y. Returns: str: The identifier of the first laser receiver encountered by the laser. ('A', 'B', or, 'C') """ g = gcd(x, y) x = (x / g) % 2 y = (y / g) % 2 return 'B' if x and y else 'A' if x else 'C'
The image shows a square setup with laser components at each corner. In the bottom left corner, there is a green triangle labeled "Laser emitter," and the other three corners have purple triangles labeled "Laser receiver A" (bottom right), "Laser receiver B" (top right), and "Laser receiver C" (top left). The edges of the rectangle have diagonal black lines representing reflective boundaries. A green laser path starts from the Laser emitter, bouncing off the boundaries in a "Z" shape before ending at Laser receiver B in the top right corner. The length of the square's sides is labeled as "x" units. Suppose the angle formed by the emitted laser and the bottom edge is θ, tan(θ) is given by y/x. The overall image visualizes the laser's reflective path between the emitter and receivers.
def test(): test_cases = [ (2, 1, 'C'), (3, 1, 'B'), (3, 2, 'A'), (3, 3, 'B'), (4, 1, 'C'), (4, 2, 'C'), (4, 3, 'C'), (4, 4, 'B'), (5, 1, 'B'), (5, 2, 'A'), ] for i, (x, y, expected) in enumerate(test_cases): result = solution(x, y) assert result == expected, f"Assert Error: Input {(x, y)}, Expected {expected}, Got: {result}" test()
def solution(x: int, y: int) -> str: """ Determine the first laser receiver encountered by the laser in the square area Parameters: x (int): The length of x. y (int): The length of y. Returns: str: The identifier of the first laser receiver encountered by the laser. ('A', 'B', or, 'C') """
q21-2
from math import gcd def solution(x: int, y: int) -> str: """ Determine the first laser receiver encountered by the laser in the square area Parameters: x (int): The length of x. y (int): The length of y. Returns: str: The identifier of the first laser receiver encountered by the laser. ('A', 'B', or, 'C') """ g = gcd(x, y) x = (x / g) % 2 y = (y / g) % 2 return 'A' if x and y else 'B' if x else 'C'
The image displays a rectangular layout with labeled laser components at each corner. In the top left corner, there is a green triangle labeled "Laser emitter," while the other three corners feature purple triangles labeled "Laser receiver B" (top right), "Laser receiver A" (bottom right), and "Laser receiver C" (bottom left). The rectangle's edges are bordered with diagonal black lines indicating reflective boundaries. A green laser path begins from the Laser emitter in the top left, bounces across the reflective surfaces in a "Z" pattern, and ends at Laser receiver A in the bottom right corner. The length of the square's sides is labeled as "x" units. Suppose the angle formed by the emitted laser and the top edge is θ, tan(θ) is given by y/x. This image visualizes the reflective path of a laser between the emitter and the receivers.
def test(): test_cases = [ (2, 1, 'C'), (3, 1, 'A'), (3, 2, 'B'), (3, 3, 'A'), (4, 1, 'C'), (4, 2, 'C'), (4, 3, 'C'), (4, 4, 'A'), (5, 1, 'A'), (5, 2, 'B'), ] for i, (x, y, expected) in enumerate(test_cases): result = solution(x, y) assert result == expected, f"Assert Error: Input {(x, y)}, Expected {expected}, Got: {result}" test()
def solution(x: int, y: int) -> str: """ Determine the first laser receiver encountered by the laser in the square area Parameters: x (int): The length of x. y (int): The length of y. Returns: str: The identifier of the first laser receiver encountered by the laser. ('A', 'B', or, 'C') """
q22
def solution(cards: list[int]) -> int: """ Based on the visual examples provided, calculate the total distance required to sequentially stack the given cards. Input: - cards: A list of integers representing a sequence of cards. (len(cards) >= 1) Output: - An integer representing the total distance required to fully stack the cards in descending order. """ steps = 0 current_position = cards.index(min(cards)) for num in range(1, len(cards) + 1): index = cards.index(num) steps += abs(index - current_position) current_position = index return steps
The image consists of two examples titled "First Example" and "Second Example," showing step-by-step processes with numbered blocks. These steps are accompanied by corresponding "Distance" calculations. ### **First Example (left side)** - **START:** Four blocks numbered 2, 3, 1, and 4 are arranged horizontally. The initial distance is 0. - **STEP 1:** The block with "1" is moved to the position of the blocks with "2", and fits behind it to form a whole, causing the distance to increase by 2. - **STEP 2:** The block with "2" and "1" is moved to the position of the blocks with "3" and stack together behind it, increasing the distance by 1. - **STEP 3:** The block stack with "3", "2" and "1" is moved next to "4" and stack together, increasing the distance by 2. - **RESULT:** The blocks are stacked vertically as 4, 3, 2, 1, with a total distance of 5. ### **Second Example (right side)** - **START:** Four blocks numbered 4, 3, 2, and 1 are arranged horizontally. The initial distance is 0. - **STEP 1:** The block with "1" is moved to the position of the block with "2" and stack together, causing the distance to increase by 1. - **STEP 2:** The block stack with "2" and "1" is moved to the position of the block with "3" and stack together, so the distance increases by 1. - **STEP 3:** The block stack with "3", "2" and "1" is moved next to "4" and stack together, increasing the distance by 1. - **RESULT:** The blocks are stacked vertically as 4, 3, 2, 1, with a total distance of 3. In both examples, blocks move from small numbers to large numbers and calculate the distance each time they move.
def test(): test_cases = [ ([2, 3, 1, 4], 5), ([1, 2, 3, 4], 3), ([4, 3, 2, 1], 3), ([3, 1, 4, 2], 7), ([1], 0), ([2, 1], 1), ([15, 2, 9, 5, 13, 6, 7, 12, 1, 4, 3, 10, 11, 14, 8], 86), ([5, 3, 2, 1, 4, 6], 14), ([15, 2, 9, 5, 4, 6, 7, 12, 1, 13, 3, 10, 11, 14, 8], 80), ] for test_case in test_cases: seq, expected = test_case original_seq = seq[:] result = solution(seq) assert result == expected, f"Assert Error: input: {original_seq}, expected: {expected}, but got: {result}" test()
def solution(cards: list[int]) -> int: """ Based on the visual examples provided, calculate the total distance required to sequentially stack the given cards. Input: - cards: A list of integers representing a sequence of cards. (len(cards) >= 1) Output: - An integer representing the total distance required to fully stack the cards in descending order. """
q22-2
def solution(cards: list[int]) -> int: """ Based on the visual examples provided, calculate the total effort required to sequentially stack the given cards. Input: - cards: A list of integers representing a sequence of cards. (len(cards) >= 1) Output: - An integer representing the total effort required to fully stack the cards in descending order. """ effort = 0 current_position = cards.index(min(cards)) for num in range(1, len(cards) + 1): index = cards.index(num) s = abs(index - current_position) effort += s*(num-1) current_position = index return effort
The image consists of two examples titled "First Example" and "Second Example," showing step-by-step processes with numbered blocks. These steps are accompanied by corresponding "Distance" and "Effort" calculations. ### **First Example (left side)** - **START:** Four blocks numbered 2, 3, 1, and 4 are arranged horizontally. The initial distance, weight and effort are 0. - **STEP 1:** The block with "1" is moved to the position of the blocks with "2", and fits behind it to form a whole, causing the distance to increase by 2. The weight is 1 now and effort increases by an equation "1x2". - **STEP 2:** The block with "2" and "1" is moved to the position of the blocks with "3" and stack together behind it, increasing the distance by 1. The weight is 2 now and effort increases by an equation "2x1". - **STEP 3:** The block stack with "3", "2" and "1" is moved next to "4" and stack together, increasing the distance by 2. The weight is 3 now and effort increases by an equation "3x2". - **RESULT:** The blocks are stacked vertically as 4, 3, 2, 1, with a total distance of 5 and the total effort of 10. ### **Second Example (right side)** - **START:** Four blocks numbered 4, 3, 2, and 1 are arranged horizontally. The initial distance, weight and effort are 0. - **STEP 1:** The block with "1" is moved to the position of the block with "2" and stack together, causing the distance to increase by 1. The weight is 1 now and effort increases by an equation "1x1". - **STEP 2:** The block stack with "2" and "1" is moved to the position of the block with "3" and stack together, so the distance increases by 1. The weight is 2 now and effort increases by an equation "2x1". - **STEP 3:** The block stack with "3", "2" and "1" is moved next to "4" and stack together, increasing the distance by 1. The weight is 3 now and effort increases by an equation "3x1". - **RESULT:** The blocks are stacked vertically as 4, 3, 2, 1, with a total distance of 3 and the total effort of 6. In both examples, blocks move from small numbers to large numbers and calculate the distance and corresponding effort each time they move.
def test(): test_cases = [ ([2, 3, 1, 4], 10), ([1, 2, 3, 4], 6), ([4, 3, 2, 1], 6), ([3, 1, 4, 2], 14), ([1], 0), ([2, 1], 1), ([15, 2, 9, 5, 13, 6, 7, 12, 1, 4, 3, 10, 11, 14, 8], 701), ([5, 3, 2, 1, 4, 6], 53), ([15, 2, 9, 5, 4, 6, 7, 12, 1, 13, 3, 10, 11, 14, 8], 619), ] for test_case in test_cases: seq, expected = test_case original_seq = seq[:] result = solution(seq) assert result == expected, f"Assert Error: input: {original_seq}, expected: {expected}, but got: {result}" test()
def solution(cards: list[int]) -> int: """ Based on the visual examples provided, calculate the total effort required to sequentially stack the given cards. Input: - cards: A list of integers representing a sequence of cards. (len(cards) >= 1) Output: - An integer representing the total effort required to fully stack the cards in descending order. """
q22-3
def solution(cards: list[int]) -> int: """ Based on the visual examples provided, calculate the total distance required to sequentially stack the given cards. Input: - cards: A list of integers representing a sequence of cards. (len(cards) >= 1) Output: - An integer representing the total distance required to fully stack the cards in descending order. """ steps = 0 position = cards.index(min(cards)) for num in range(len(cards), 0, -1): index = cards.index(num) steps += abs(index - position) return steps
The image consists of two examples titled "First Example" and "Second Example," showing step-by-step processes with numbered blocks. These steps are accompanied by corresponding "Distance" calculations. ### **First Example (left side)** - **START:** Four blocks numbered 2, 3, 1, and 4 are arranged horizontally. The initial distance is 0. - **STEP 1:** The block with "2" is moved to the position of the blocks with "1", and fits behind it to form a whole, causing the distance to increase by 2. - **STEP 2:** The block with "3" is moved to the position of the block stack with "2" and "1" and stack together behind it, increasing the distance by 1. - **STEP 3:** The block with "4" is moved next to the block stack "1", "2" and "3" and stack together, increasing the distance by 1. - **RESULT:** The blocks are stacked vertically as 1, 2, 3, 4, with a total distance of 4. ### **Second Example (right side)** - **START:** Four blocks numbered 4, 3, 2, and 1 are arranged horizontally. The initial distance is 0. - **STEP 1:** The block with "2" is moved to the position of the block with "1" and stack together, causing the distance to increase by 1. - **STEP 2:** The block with "3" is moved to the position of the block stack "2" and "1" and stack together, so the distance increases by 2. - **STEP 3:** The block with "4" is moved next to block stack "1", "2" and "3" and stack together, increasing the distance by 3. - **RESULT:** The blocks are stacked vertically as 1, 2, 3, 4, with a total distance of 6. In both examples blocks move from large numbers to small numbers and calculate the distance each time they move.
def test(): test_cases = [ ([2, 3, 1, 4], 4), ([1, 2, 3, 4], 6), ([4, 3, 2, 1], 6), ([3, 1, 4, 2], 4), ([1], 0), ([2, 1], 1), ([15, 2, 9, 5, 13, 6, 7, 12, 1, 4, 3, 10, 11, 14, 8], 57), ([5, 3, 2, 1, 4, 6], 9), ([15, 2, 9, 5, 4, 6, 7, 12, 1, 13, 3, 10, 11, 14, 8], 57), ] for test_case in test_cases: seq, expected = test_case original_seq = seq[:] result = solution(seq) assert result == expected, f"Assert Error: input: {original_seq}, expected: {expected}, but got: {result}" test()
def solution(cards: list[int]) -> int: """ Based on the visual examples provided, calculate the total distance required to sequentially stack the given cards. Input: - cards: A list of integers representing a sequence of cards. (len(cards) >= 1) Output: - An integer representing the total distance required to fully stack the cards in descending order. """
q23
from typing import List def solution(commands: List[str]) -> List[List[int]]: """ Given a series of commands, transform the color of a matrix according to the rules shown in the image. Input: - command: A list of strings, where each string is a command that modifies the matrix. For example: ['A', 'B', 'E']. Output: - A 3x3 matrix of integers, where each integer represents the color of the cell in the matrix. 1 represents white, 0 represents black. """ matrix = [[1] * 3 for _ in range(3)] for command in commands: if command == 'A': for i in range(3): matrix[i][0] = 1 - matrix[i][0] elif command == 'B': for i in range(3): matrix[i][1] = 1 - matrix[i][1] elif command == 'C': for i in range(3): matrix[i][2] = 1 - matrix[i][2] elif command == 'D': for j in range(3): matrix[0][j] = 1 - matrix[0][j] elif command == 'E': for j in range(3): matrix[1][j] = 1 - matrix[1][j] elif command == 'F': for j in range(3): matrix[2][j] = 1 - matrix[2][j] return matrix
The image shows a 3x3 grid, with columns labeled A, B, C and rows labeled D, E, F. The sequence of changes in the grid follows inputs, and the color of the cells changes after each input. 1. **Initial Grid**: - All cells are white. 2. **Input: "B"**: - Result: White, Black, White White, Black, White White, Black, White 3. **Input: "E"**: - Result: White, Black, White Black, White, Black White, Black, White 4. **Input: "C"**: - Result: White, Black, Black Black, White, White White, Black, Black 5. **Input: "D"**: - Result: Black, White, White Black, White, White White, Black, Black 6. **Input: "B"**: - Result: Black, Black, White Black, Black, White White, White, Black
def test(): test_cases = [ { 'input': ['B'], 'expected': [[1, 0, 1], [1, 0, 1], [1, 0, 1]] }, { 'input': ['E'], 'expected': [[1, 1, 1], [0, 0, 0], [1, 1, 1]] }, { 'input': ['A'], 'expected': [[0, 1, 1], [0, 1, 1], [0, 1, 1]] }, { 'input': ['C'], 'expected': [[1, 1, 0], [1, 1, 0], [1, 1, 0]] }, { 'input': ['B', 'E'], 'expected': [[1, 0, 1], [0, 1, 0], [1, 0, 1]] }, { 'input': ['A', 'C', 'F'], 'expected': [[0, 1, 0], [0, 1, 0], [1, 0, 1]] }, { 'input': ['A', 'B', 'C', 'D', 'E', 'F'], 'expected': [[1, 1, 1], [1, 1, 1], [1, 1, 1]] }, { 'input': ['A', 'A'], 'expected': [[1, 1, 1], [1, 1, 1], [1, 1, 1]] }, { 'input': ['A', 'B', 'E', 'C', 'F'], 'expected': [[0, 0, 0], [1, 1, 1], [1, 1, 1]] }, { 'input': ['A', 'B', 'E', 'F'], 'expected': [[0, 0, 1], [1, 1, 0], [1, 1, 0]] } ] for test_case in test_cases: result = solution(test_case['input']) assert result == test_case['expected'], f"Assert Error: input={test_case['input']}, expected={test_case['expected']}, result={result}" test()
from typing import List def solution(commands: List[str]) -> List[List[int]]: """ Given a series of commands, transform the color of a matrix according to the rules shown in the image. Input: - command: A list of strings, where each string is a command that modifies the matrix. For example: ['A', 'B', 'E']. Output: - A 3x3 matrix of integers, where each integer represents the color of the cell in the matrix. 1 represents white, 0 represents black. """
q23-2
from typing import List def solution(commands: List[str], matrix: List[List[int]]) -> List[List[int]]: """ Given a series of commands, transform the numbers of a matrix according to the rules shown in the image. Input: - command: A list of strings, where each string is a command that modifies the matrix. For example: ['A', 'B', 'E']. Output: - A 2d list of integers. """ # Iterate through each command for command in commands: if command == "A": # Sort the first column in ascending order col = sorted([matrix[i][0] for i in range(3)]) for i in range(3): matrix[i][0] = col[i] elif command == "B": # Sort the second column in ascending order col = sorted([matrix[i][1] for i in range(3)]) for i in range(3): matrix[i][1] = col[i] elif command == "C": # Sort the third column in ascending order col = sorted([matrix[i][2] for i in range(3)]) for i in range(3): matrix[i][2] = col[i] elif command == "D": # Sort the first row in ascending order matrix[0] = sorted(matrix[0]) elif command == "E": # Sort the second row in ascending order matrix[1] = sorted(matrix[1]) elif command == "F": # Sort the third row in ascending order matrix[2] = sorted(matrix[2]) return matrix
The image shows a sequence of transformations applied to a 3x3 grid labeled with columns A, B, C and rows D, E, F. Each input changes specific rows or columns, and the numbers in the affected cells are highlighted in green to indicate changes. ### Top Row (Left to Right): 1. **Initial Grid**: - The grid shows the following numbers: A B C D 8, 6, 1 E 3, 5, 4 F 9, 7, 2 2. **Input: "B"**: - The values in column B are highlighted. - Result: A B C D 8, 5, 1 E 3, 6, 4 F 9, 7, 2 3. **Input: "E"**: - The values in row E are highlighted. - Result: A B C D 8, 5, 1 E 3, 4, 6 F 9, 7, 2 4. **Input: "C"**: - The values in column C are highlighted. - Result: A B C D 8, 5, 1 E 3, 4, 2 F 9, 7, 6 5. **Input: "D"**: - The values in row D are highlighted. - Result: A B C D 1, 5, 8 E 3, 4, 2 F 9, 7, 6 6. **Input: "B"**: - The values in column B are highlighted. - Result: A B C D 1, 4, 8 E 3, 5, 2 F 9, 7, 6
def test(): test_cases = [ { 'commands': ['B'], 'matrix': [[7, 1, 8],[1, 1, 3],[7, 5, 9]], 'expected': [[7, 1, 8], [1, 1, 3], [7, 5, 9]] }, { 'commands': ['E'], 'matrix': [[3, 7, 2],[6, 9, 7],[4, 7, 8]], 'expected': [[3, 7, 2], [6, 7, 9], [4, 7, 8]] }, { 'commands': ['A'], 'matrix': [[4, 9, 6],[8, 3, 1],[3, 6, 7]], 'expected': [[3, 9, 6], [4, 3, 1], [8, 6, 7]] }, { 'commands': ['C'], 'matrix': [[4, 5, 6],[8, 1, 2],[3, 9, 7]], 'expected': [[4, 5, 2], [8, 1, 6], [3, 9, 7]] }, { 'commands': ['B', 'E'], 'matrix': [[1, 2, 3],[4, 5, 6],[7, 8, 9]], 'expected': [[1, 2, 3], [4, 5, 6], [7, 8, 9]] }, { 'commands': ['A', 'C', 'F'], 'matrix': [[4, 5, 6], [8, 1, 2], [3, 9, 7]], 'expected': [[3, 5, 2], [4, 1, 6], [7, 8, 9]] }, { 'commands': ['A', 'B', 'C', 'D', 'E', 'F'], 'matrix': [[4, 5, 6], [8, 1, 2], [3, 9, 7]], 'expected': [[1, 2, 3], [4, 5, 6], [7, 8, 9]] }, { 'commands': ['A', 'A'], 'matrix': [[4, 5, 6], [8, 1, 2], [3, 9, 7]], 'expected': [[3, 5, 6], [4, 1, 2], [8, 9, 7]] }, { 'commands': ['A', 'B', 'E', 'C', 'F'], 'matrix': [[2, 3, 5], [7, 9, 1], [4, 6, 8]], 'expected': [[2, 3, 5], [1, 4, 6], [7, 8, 9]] }, { 'commands': ['A', 'B', 'E', 'F'], 'matrix': [[2, 3, 5], [7, 9, 1], [4, 6, 8]], 'expected': [[2, 3, 5], [1, 4, 6], [7, 8, 9]] } ] for test_case in test_cases: result = solution(test_case['commands'], test_case['matrix']) assert result == test_case['expected'], f"Assert Error: commands={test_case['commands']}, expected={test_case['expected']}, result={result}" test()
from typing import List def solution(commands: List[str], matrix: List[List[int]]) -> List[List[int]]: """ Given a series of commands, transform the numbers of a matrix according to the rules shown in the image. Input: - command: A list of strings, where each string is a command that modifies the matrix. For example: ['A', 'B', 'E']. Output: - A 2d list of integers. """
q23-3
from typing import List def solution(commands: List[str], matrix: List[List[int]]) -> List[List[int]]: """ Given a series of commands, transform the numbers of a matrix according to the rules shown in the image. Input: - command: A list of strings, where each string is a command that modifies the matrix. For example: ['A', 'B', 'E']. Output: - A 2d list of integers. """ # Iterate through each command for command in commands: if command == "A": # Convert the first column numbers to their opposites for i in range(3): matrix[i][0] = -matrix[i][0] elif command == "B": # Convert the second column numbers to their opposites for i in range(3): matrix[i][1] = -matrix[i][1] elif command == "C": # Convert the third column numbers to their opposites for i in range(3): matrix[i][2] = -matrix[i][2] elif command == "D": # Convert the first row numbers to their opposites matrix[0] = [-x for x in matrix[0]] elif command == "E": # Convert the second row numbers to their opposites matrix[1] = [-x for x in matrix[1]] elif command == "F": # Convert the third row numbers to their opposites matrix[2] = [-x for x in matrix[2]] return matrix
The image shows a sequence of transformations applied to a 3x3 grid labeled with columns A, B, C and rows D, E, F. Each input changes specific rows or columns, and the numbers in the affected cells are highlighted in green to indicate changes. ### Top Row (Left to Right): 1. **Initial Grid**: - The grid shows the following numbers: A B C D 8, 6, 1 E 3, 5, 4 F 9, 7, 2 2. **Input: "B"**: - The values in column B are highlighted. - Result: A B C D 8, -6, 1 E 3, -5, 4 F 9, -7, 2 3. **Input: "E"**: - The values in row E are highlighted. - Result: A B C D 8, -6, 1 E -3, 5, -4 F 9, -7, 2 4. **Input: "C"**: - The values in column C are highlighted. - Result: A B C D 8, -6, -1 E -3, 5, 4 F 9, -7, -2 5. **Input: "D"**: - The values in row D are highlighted. - Result: A B C D -8, 6, 1 E -3, 5, 4 F 9, -7, -2 6. **Input: "B"**: - The values in column B are highlighted. - Result: A B C D -8, -6, 1 E -3, -5, 4 F 9, 7, -2
def test(): test_cases = [ { 'commands': ['B'], 'matrix': [[7, 1, 8],[1, 1, 3],[7, 5, 9]], 'expected': [[7, -1, 8], [1, -1, 3], [7, -5, 9]] }, { 'commands': ['E'], 'matrix': [[3, 7, 2],[6, 9, 7],[4, 7, 8]], 'expected': [[3, 7, 2], [-6, -9, -7], [4, 7, 8]] }, { 'commands': ['A'], 'matrix': [[4, 9, 6],[8, 3, 1],[3, 6, 7]], 'expected': [[-4, 9, 6], [-8, 3, 1], [-3, 6, 7]] }, { 'commands': ['C'], 'matrix': [[4, 5, 6],[8, 1, 2],[3, 9, 7]], 'expected': [[4, 5, -6], [8, 1, -2], [3, 9, -7]] }, { 'commands': ['B', 'E'], 'matrix': [[1, 2, 3],[4, 5, 6],[7, 8, 9]], 'expected': [[1, -2, 3], [-4, 5, -6], [7, -8, 9]] }, { 'commands': ['A', 'C', 'F'], 'matrix': [[4, 5, 6], [8, 1, 2], [3, 9, 7]], 'expected': [[-4, 5, -6], [-8, 1, -2], [3, -9, 7]] }, { 'commands': ['A', 'B', 'C', 'D', 'E', 'F'], 'matrix': [[4, 5, 6], [8, 1, 2], [3, 9, 7]], 'expected': [[4, 5, 6], [8, 1, 2], [3, 9, 7]] }, { 'commands': ['A', 'A'], 'matrix': [[4, 5, 6], [8, 1, 2], [3, 9, 7]], 'expected': [[4, 5, 6], [8, 1, 2], [3, 9, 7]] }, { 'commands': ['A', 'B', 'E', 'C', 'F'], 'matrix': [[2, 3, 5], [7, 9, 1], [4, 6, 8]], 'expected': [[-2, -3, -5], [7, 9, 1], [4, 6, 8]] }, { 'commands': ['A', 'B', 'E', 'F'], 'matrix': [[2, 3, 5], [7, 9, 1], [4, 6, 8]], 'expected': [[-2, -3, 5], [7, 9, -1], [4, 6, -8]] } ] for test_case in test_cases: result = solution(test_case['commands'], test_case['matrix']) assert result == test_case['expected'], f"Assert Error: commands={test_case['commands']}, expected={test_case['expected']}, result={result}" test()
from typing import List def solution(commands: List[str], matrix: List[List[int]]) -> List[List[int]]: """ Given a series of commands, transform the numbers of a matrix according to the rules shown in the image. Input: - command: A list of strings, where each string is a command that modifies the matrix. For example: ['A', 'B', 'E']. Output: - A 2d list of integers. """
q24
from typing import List def solution(arrangement: List[List[int]]) -> bool: """ Determine whether the arrangement of the given puzzle pieces is valid. Input: - arrangement: A 2D list of integers, where each element represents the rotation angle for the corresponding puzzle piece. Possible angles are 0, 90, 180, or -90. Output: - A boolean value, where True indicates that the arrangement is valid and False indicates that the arrangement is invalid. """ def get_edges(angle): """ Returns the edges as a tuple (T, R, B, L) after rotating the piece by a given angle. """ edges = { 0: { 'T': 1, 'R': 1, 'B': 0, 'L': 1 }, 90: { 'T': 1, 'R': 1, 'B': 1, 'L': 0 }, 180: { 'T': 0, 'R': 1, 'B': 1, 'L': 1 }, -90: { 'T': 1, 'R': 0, 'B': 1, 'L': 1 } } return edges[angle] rows = len(arrangement) cols = len(arrangement[0]) for i in range(rows): for j in range(cols): if j < cols - 1: current_piece_edges = get_edges(arrangement[i][j]) right_piece_edges = get_edges(arrangement[i][j + 1]) if current_piece_edges['R'] == right_piece_edges['L']: return False if i < rows - 1: current_piece_edges = get_edges(arrangement[i][j]) bottom_piece_edges = get_edges(arrangement[i + 1][j]) if current_piece_edges['B'] == bottom_piece_edges['T']: return False return True
The image illustrates a series of rotations and puzzle arrangements involving puzzle pieces with numbers labeled on them. The process involves rotating and positioning puzzle pieces based on the numbers they represent. ### **Top Section**: - A single puzzle piece is shown with the number **0**. It is then rotated by **90°**, resulting in a new puzzle piece labeled **90** after the rotation. ### **Middle Section (1x2 Puzzle)**: - Two puzzle pieces are placed next to each other horizontally to form a 1x2 puzzle: - The first piece is labeled **0** (on the left). - The second piece is labeled **90** (on the right). ### **Bottom Section (2x2 Puzzle)**: - Four puzzle pieces are arranged in a 2x2 grid to form a complete puzzle: - The top-left piece is labeled **-90**. - The top-right piece is labeled **0**. - The bottom-left piece is labeled **180**. - The bottom-right piece is labeled **90**. The image showcases puzzle pieces with numerical labels and specific orientations. In addition to the rotations, each puzzle piece has either **indents (concave)** or **protrusions (convex)** on its four sides. Below is a description of the orientation of the indents and protrusions for each puzzle piece based on the labeled angle. - **Initial Piece (labeled 0)**: - **Top**: Protrusion - **Bottom**: Indent - **Left**: Protrusion - **Right**: Protrusion - **labeled 90: - **Top**: Protrusion - **Bottom**: Protrusion - **Left**: Indent - **Right**: Protrusion - **labeled -90**: - **Top**: Protrusion - **Bottom**: Protrusion - **Left**: Protrusion - **Right**: Indent - **labeled 180**: - **Top**: Indent - **Bottom**: Protrusion - **Left**: Protrusion - **Right**: Protrusion
def test(): test_cases = [ ([[-90, 0], [180, 90]], True), ([[0, 90, 90]], True), ([[90,90,90]], True), ([[180, 90, 90]], True), ([[0, 90, 90, 90, 90]], True), ([[90, 90, 90, 90, 90]], True), ([[180, 90, 90, 90, 90]], True), ([[0], [90], [180]], True), ([[90],[180],[180]], True), ([[-90],[180],[180]], True), ([[0], [-90], [180]], True), ([[180], [180], [180]], True), ([[0], [180], [180]], False), ([[0], [0]], True), ([[0, 0]], False) ] for i, (input, expected) in enumerate(test_cases): result = solution(input) assert result == expected, f"Assert Error: input {input}, expected {expected}, got {result}" test()
from typing import List def solution(arrangement: List[List[int]]) -> bool: """ Determine whether the arrangement of the given puzzle pieces is valid. Input: - arrangement: A 2D list of integers, where each element represents the rotation angle for the corresponding puzzle piece. Possible angles are 0, 90, 180, or -90. Output: - A boolean value, where True indicates that the arrangement is valid and False indicates that the arrangement is invalid. """
q24-2
from typing import List def solution(arrangement: List[List[int]]) -> bool: """ Determine whether the arrangement of the given puzzle pieces is valid. Input: - arrangement: A 2D list of integers, where each element represents the rotation angle for the corresponding puzzle piece. Possible angles are 0, 90, 180, or -90. Output: - A boolean value, where True indicates that the arrangement is valid and False indicates that the arrangement is invalid. """ def get_edges(angle): """ Returns the edges as a tuple (T, R, B, L) after rotating the piece by a given angle. """ edges = { 0: { 'T': 1, 'R': 0, 'B': 1, 'L': 1 }, 90: { 'T': 1, 'R': 1, 'B': 0, 'L': 1 }, 180: { 'T': 1, 'R': 1, 'B': 1, 'L': 0 }, -90: { 'T': 0, 'R': 1, 'B': 1, 'L': 1 } } return edges[angle] rows = len(arrangement) cols = len(arrangement[0]) for i in range(rows): for j in range(cols): if j < cols - 1: current_piece_edges = get_edges(arrangement[i][j]) right_piece_edges = get_edges(arrangement[i][j + 1]) if current_piece_edges['R'] == right_piece_edges['L']: return False if i < rows - 1: current_piece_edges = get_edges(arrangement[i][j]) bottom_piece_edges = get_edges(arrangement[i + 1][j]) if current_piece_edges['B'] == bottom_piece_edges['T']: return False return True
The image illustrates a series of rotations and puzzle arrangements involving puzzle pieces with numbers labeled on them. The process involves rotating and positioning puzzle pieces based on the numbers they represent. ### **Top Section**: - A single puzzle piece is shown with the number **0**. It is then rotated by **90°**, resulting in a new puzzle piece labeled **90** after the rotation. ### **Middle Section (1x2 Puzzle)**: - Two puzzle pieces are placed next to each other horizontally to form a 1x2 puzzle: - The first piece is labeled **90** (on the left). - The second piece is labeled **180** (on the right). ### **Bottom Section (2x2 Puzzle)**: - Four puzzle pieces are arranged in a 2x2 grid to form a complete puzzle: - The top-left piece is labeled **0**. - The top-right piece is labeled **90**. - The bottom-left piece is labeled **-90**. - The bottom-right piece is labeled **180**. The image showcases puzzle pieces with numerical labels and specific orientations. In addition to the rotations, each puzzle piece has either **indents (concave)** or **protrusions (convex)** on its four sides. Below is a description of the orientation of the indents and protrusions for each puzzle piece based on the labeled angle. - **Initial Piece (labeled 0)**: - **Top**: Protrusion - **Bottom**: Protrusion - **Left**: Protrusion - **Right**: Indent - **labeled 90** - **Top**: Protrusion - **Bottom**: Indent - **Left**: Protrusion - **Right**: Protrusion - **labeled -90**: - **Top**: Indent - **Bottom**: Protrusion - **Left**: Protrusion - **Right**: Protrusion - **labeled 180**: - **Top**: Protrusion - **Bottom**: Protrusion - **Left**: Indent - **Right**: Protrusion
def test(): test_cases = [ ([[-90, 0], [180, 90]], False), ([[0, 90], [-90, 180]], True), ([[90, 180, 180]], True), ([[180, 180, 180]], True), ([[-90, 180, 180]], True), ([[90, 180, 180, 180, 180]], True), ([[180, 180, 180, 180]], True), ([[-90, 180, 180, 180, 180]], True), ([[90], [180], [-90]], True), ([[180],[-90],[-90]], True), ([[0],[-90],[-90]], True), ([[0], [-90], [180]], False), ([[-90], [-90], [-90]], True), ([[90], [-90], [-90]], False), ([[90], [90]], True), ([[90, 90]], False) ] for i, (input, expected) in enumerate(test_cases): result = solution(input) assert result == expected, f"Assert Error: input {input}, expected {expected}, got {result}" test()
from typing import List def solution(arrangement: List[List[int]]) -> bool: """ Determine whether the arrangement of the given puzzle pieces is valid. Input: - arrangement: A 2D list of integers, where each element represents the rotation angle for the corresponding puzzle piece. Possible angles are 0, 90, 180, or -90. Output: - A boolean value, where True indicates that the arrangement is valid and False indicates that the arrangement is invalid. """
q24-3
from typing import List def solution(arrangement: List[List[int]]) -> bool: """ Determine whether the arrangement of the given puzzle pieces is valid. Input: - arrangement: A 2D list of integers, where each element represents the rotation angle for the corresponding puzzle piece. Possible angles are 0, 90, 180, or -90. Output: - A boolean value, where True indicates that the arrangement is valid and False indicates that the arrangement is invalid. """ def get_edges(angle): """ Returns the edges as a tuple (T, R, B, L) after rotating the piece by a given angle. """ edges = { 0: { 'T': 1, 'R': 0, 'B': 0, 'L': 1 }, 90: { 'T': 1, 'R': 1, 'B': 0, 'L': 0 }, 180: { 'T': 0, 'R': 1, 'B': 1, 'L': 0 }, -90: { 'T': 0, 'R': 0, 'B': 1, 'L': 1 } } return edges[angle] rows = len(arrangement) cols = len(arrangement[0]) for i in range(rows): for j in range(cols): if j < cols - 1: current_piece_edges = get_edges(arrangement[i][j]) right_piece_edges = get_edges(arrangement[i][j + 1]) if current_piece_edges['R'] == right_piece_edges['L']: return False if i < rows - 1: current_piece_edges = get_edges(arrangement[i][j]) bottom_piece_edges = get_edges(arrangement[i + 1][j]) if current_piece_edges['B'] == bottom_piece_edges['T']: return False return True
The image illustrates a series of rotations and puzzle arrangements involving puzzle pieces with numbers labeled on them. The process involves rotating and positioning puzzle pieces based on the numbers they represent. ### **Top Section**: - A single puzzle piece is shown with the number **0**. It is then rotated by **90°**, resulting in a new puzzle piece labeled **90** after the rotation. ### **Middle Section (1x2 Puzzle)**: - Two puzzle pieces are placed next to each other horizontally to form a 1x2 puzzle: - The first piece is labeled **0** (on the left). - The second piece is labeled **0** (on the right). ### **Bottom Section (2x2 Puzzle)**: - Four puzzle pieces are arranged in a 2x2 grid to form a complete puzzle: - The top-left piece is labeled **0**. - The top-right piece is labeled **0**. - The bottom-left piece is labeled **90**. - The bottom-right piece is labeled **90**. The image showcases puzzle pieces with numerical labels and specific orientations. In addition to the rotations, each puzzle piece has either **indents (concave)** or **protrusions (convex)** on its four sides. Below is a description of the orientation of the indents and protrusions for each puzzle piece based on the labeled angle. - **Initial Piece (labeled 0)**: - **Top**: Protrusion - **Bottom**: Indent - **Left**: Protrusion - **Right**: Indent - **labeled 90** - **Top**: Protrusion - **Bottom**: Indent - **Left**: Indent - **Right**: Protrusion - **labeled -90**: - **Top**: Indent - **Bottom**: Protrusion - **Left**: Protrusion - **Right**: Indent - **labeled 180**: - **Top**: Indent - **Bottom**: Protrusion - **Left**: Indent - **Right**: Protrusion
def test(): test_cases = [ ([[0, 0], [90, 90]], True), ([[0, 0], [0, 0]], True), ([[0, 0, 0]], True), ([[0, -90, -90]], True), ([[0, -90, 0, -90, 0]], True), ([[-90, -90, -90, -90, -90]], True), ([[180, 90, 90, 90, 90]], True), ([[0], [90], [0]], True), ([[90],[0],[90]], True), ([[-90],[180],[180]], True), ([[180], [-90], [180]], True), ([[180], [180], [180]], True), ([[0], [180], [180]], False), ([[0], [0]], True), ([[0, 180]], False) ] for i, (input, expected) in enumerate(test_cases): result = solution(input) assert result == expected, f"Assert Error: input {input}, expected {expected}, got {result}" test()
from typing import List def solution(arrangement: List[List[int]]) -> bool: """ Determine whether the arrangement of the given puzzle pieces is valid. Input: - arrangement: A 2D list of integers, where each element represents the rotation angle for the corresponding puzzle piece. Possible angles are 0, 90, 180, or -90. Output: - A boolean value, where True indicates that the arrangement is valid and False indicates that the arrangement is invalid. """
q25
from typing import Dict, List, Tuple, Optional def solution(rectangles: Dict[int, List[Tuple[int, int]]], rectangle_id: int) -> Optional[List[Tuple[int, int]]]: """ You are given a collection of rectangles, each associated with an ID. Your task is to return the trimed rectangle with a specified id. Input: - rectangles: A dictionary where the keys are integers representing the ids of the rectangles, and the values are lists of two tuples. Each tuple contains two integers representing the coordinates of the bottom-left and top-right corners of the rectangle. For example: {1: [(0, 0), (2, 2)], 2: [(2, 0), (4, 2)]} - rectangle_id: An integer representing the id of the rectangle you want to retrieve. Output: - A list of two tuples representing the coordinates of the bottom-left and top-right corners of the rectangle with the specified id. If no valid rectangle can be formed, return None. """ ordered_rectangles = sorted(rectangles.items()) grid = [[None for _ in range(1000)] for _ in range(1000)] for priority, ((bottom_left_x, bottom_left_y), (top_right_x, top_right_y)) in ordered_rectangles: for x in range(bottom_left_x, top_right_x): for y in range(bottom_left_y, top_right_y): if grid[x][y] is None: grid[x][y] = priority min_x, min_y, max_x, max_y = (1000, 1000, 0, 0) found = False for x in range(1000): for y in range(1000): if grid[x][y] == rectangle_id: found = True min_x = min(min_x, x) min_y = min(min_y, y) max_x = max(max_x, x + 1) max_y = max(max_y, y + 1) if found: return [(min_x, min_y), (max_x, max_y)] else: return None
The title of the image is "trim based on priority", with two examples labeled "Example 1" and "Example 2." Each example consists of two stages: the initial grid with overlapping colored blocks and the result after trimming. The grid is divided into rows (0 to 3) and columns (0 to 7), and blocks are labeled with numbers. ### **Example 1**: 1. **Initial State**: - There are two overlapping rectangular blocks: - Block "1" (blue) spans from column 0 to column 3 and from row 0 to row 2. - Block "2" (orange) spans from column 2 to column 5 and from row 0 to row 2. 2. **After Trimming**: - The overlap is removed. The block 1 retains still. The previous overlap in block 2 is cut. - The result shows Block "1" spanning columns 0 to 3 and Block "2" starting from column 3 to column 5, eliminating any overlap. ### **Example 2**: 1. **Initial State**: - There are three overlapping rectangular blocks: - Block "1" (blue) spans from column 0 to column 3 and from row 0 to row 3. - Block "2" (orange) spans from column 2 to column 5 and from row 0 to row 2. - Block "3" (purple) spans from column 3 to column 5 and from row 1 to row 3. 2. **After Trimming**: - The overlap is removed. The block 1 retains still.The previous overlap part with block 1 in block 2 is cut. The overlap part in block 3 is also cut. - The result shows Block "1" spanning columns 0 to 3 and from row 0 to 3, Block "2" spanning only column 3 to 4 and from row 0 to 2, and Block "3" spanning column 3 to 5 and and from row 2 to 3.
def test(): rectangles = { 1: [(0,0),(2,2)], 2: [(2,0),(4,2)] } result = solution(rectangles, 1) expected = [(0,0),(2,2)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 2) expected = [(2,0),(4,2)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" rectangles = { 1: [(0, 0), (3, 2)], 2: [(3, 0), (5, 2)] } result = solution(rectangles, 1) expected = [(0, 0), (3, 2)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 2) expected = [(3, 0), (5, 2)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" rectangles = { 1: [(0, 0), (3, 3)], 2: [(3, 0), (5, 2)], 3: [(3, 1), (5, 3)], 4: [(0, 0), (1, 1)] } result = solution(rectangles, 1) expected = [(0, 0), (3, 3)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 2) expected = [(3, 0), (5, 2)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 3) expected = [(3, 2), (5, 3)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 4) expected = None assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" rectangles = { 1: [(0, 0), (3, 3)], 2: [(3, 0), (5, 2)], 3: [(3, 1), (5, 3)] } result = solution(rectangles, 1) expected = [(0, 0), (3, 3)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 2) expected = [(3, 0), (5, 2)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 3) expected = [(3, 2), (5, 3)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" test()
from typing import Dict, List, Tuple, Optional def solution(rectangles: Dict[int, List[Tuple[int, int]]], rectangle_id: int) -> Optional[List[Tuple[int, int]]]: """ You are given a collection of rectangles, each associated with an ID. Your task is to return the trimed rectangle with a specified id. Input: - rectangles: A dictionary where the keys are integers representing the ids of the rectangles, and the values are lists of two tuples. Each tuple contains two integers representing the coordinates of the bottom-left and top-right corners of the rectangle. For example: {1: [(0, 0), (2, 2)], 2: [(2, 0), (4, 2)]} - rectangle_id: An integer representing the id of the rectangle you want to retrieve. Output: - A list of two tuples representing the coordinates of the bottom-left and top-right corners of the rectangle with the specified id. If no valid rectangle can be formed, return None. """
q25-2
from typing import Dict, List, Tuple, Optional def solution(rectangles: Dict[int, List[Tuple[int, int]]], rectangle_id: int) -> Optional[List[Tuple[int, int]]]: """ You are given a collection of rectangles, each associated with an ID. Your task is to return the trimed rectangle with a specified id. Input: - rectangles: A dictionary where the keys are integers representing the ids of the rectangles, and the values are lists of two tuples. Each tuple contains two integers representing the coordinates of the bottom-left and top-right corners of the rectangle. For example: {1: [(0, 0), (2, 2)], 2: [(2, 0), (4, 2)]} - rectangle_id: An integer representing the id of the rectangle you want to retrieve. Output: - A list of two tuples representing the coordinates of the bottom-left and top-right corners of the rectangle with the specified id. If no valid rectangle can be formed, return None. """ ordered_rectangles = sorted(rectangles.items(), reverse=True) grid = [[None for _ in range(1000)] for _ in range(1000)] for priority, ((bottom_left_x, bottom_left_y), (top_right_x, top_right_y)) in ordered_rectangles: for x in range(bottom_left_x, top_right_x): for y in range(bottom_left_y, top_right_y): if grid[x][y] is None: grid[x][y] = priority min_x, min_y, max_x, max_y = (1000, 1000, 0, 0) found = False for x in range(1000): for y in range(1000): if grid[x][y] == rectangle_id: found = True min_x = min(min_x, x) min_y = min(min_y, y) max_x = max(max_x, x + 1) max_y = max(max_y, y + 1) if found: return [(min_x, min_y), (max_x, max_y)] else: return None
The title of the image is trim based on priority, with two examples labeled "Example 1" and "Example 2." Each example consists of two stages: the initial grid with overlapping colored blocks and the result after trimming. The grid is divided into rows (0 to 3) and columns (0 to 7), and blocks are labeled with numbers. ### **Example 1**: 1. **Initial State**: - There are two overlapping rectangular blocks: - Block "1" (blue) spans from column 0 to column 3 and from row 0 to row 2. - Block "2" (orange) spans from column 2 to column 5 and from row 0 to row 2. 2. **After Trimming**: - The overlap is removed. The block 2 retains still. The previous overlap in block 1 is cut. - The result shows Block "1" spanning columns 0 to 2 and Block "2" starting from column 2 to column 5, eliminating any overlap. ### **Example 2**: 1. **Initial State**: - Block "1" (blue) spans from column 0 to column 3 and from row 0 to row 3. - Block "2" (orange) spans from column 2 to column 5 and from row 0 to row 2. - Block "3" (purple) spans from column 2 to column 5 and from row 1 to row 3. 2. **After Trimming**: - The result shows Block "1" spanning only columns 0 to 2 and from row 0 to 3, Block "2" spanning only column 2 to 5 and from row 0 to 1, and Block "3" covering column 2 to 5 and row 1 to 3.
def test(): rectangles = { 2: [(0, 0), (2, 2)], 1: [(2, 0), (4, 2)] } result = solution(rectangles, 2) expected = [(0, 0), (2, 2)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 1) expected = [(2, 0), (4, 2)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" rectangles = { 2: [(0, 0), (3, 2)], 1: [(3, 0), (5, 2)] } result = solution(rectangles, 2) expected = [(0, 0), (3, 2)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 1) expected = [(3, 0), (5, 2)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" rectangles = { 4: [(1, 0), (4, 2)], 3: [(3, 0), (8, 1)], 2: [(3, 0), (7, 2)], 1: [(1, 1), (2, 2)] } result = solution(rectangles, 4) expected = [(1, 0), (4, 2)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 3) expected = [(4, 0), (8, 1)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 2) expected = [(4, 1), (7, 2)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 1) expected = None assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" rectangles = { 1: [(0, 1), (3, 3)], 2: [(2, 0), (5, 2)], 3: [(2, 1), (5, 3)] } result = solution(rectangles, 1) expected = [(0, 1), (2, 3)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 2) expected = [(2, 0), (5, 1)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" result = solution(rectangles, 3) expected = [(2, 1), (5, 3)] assert result == expected, f"Assert Error: input {rectangles}, expected {expected}, got {result}" test()
from typing import Dict, List, Tuple, Optional def solution(rectangles: Dict[int, List[Tuple[int, int]]], rectangle_id: int) -> Optional[List[Tuple[int, int]]]: """ You are given a collection of rectangles, each associated with an ID. Your task is to return the trimed rectangle with a specified id. Input: - rectangles: A dictionary where the keys are integers representing the ids of the rectangles, and the values are lists of two tuples. Each tuple contains two integers representing the coordinates of the bottom-left and top-right corners of the rectangle. For example: {1: [(0, 0), (2, 2)], 2: [(2, 0), (4, 2)]} - rectangle_id: An integer representing the id of the rectangle you want to retrieve. Output: - A list of two tuples representing the coordinates of the bottom-left and top-right corners of the rectangle with the specified id. If no valid rectangle can be formed, return None. """
q26
from typing import List def solution(rules: List[List[str]], filled_matrix: List[List[int]]) -> bool: """ Determine whether the filled_matrix satisfies the restriction rules. Input: - rules: A 2d list containing 'E' or 'N' that specify the restrictions, as illustrated in the image. for example, [['E'], ['N', 'N'], ['E']] for a 2x2 matrix. - filled_matrix: A 2d list containing integers. Output: - A boolean value indicating whether the filled_matrix satisfies the restriction rules. """ rows = len(filled_matrix) cols = len(filled_matrix[0]) for i in range(rows): for j in range(cols): if i < rows - 1: if rules[2 * i + 1][j] == 'E': if filled_matrix[i][j] != filled_matrix[i + 1][j]: return False elif rules[2 * i + 1][j] == 'N': if filled_matrix[i][j] == filled_matrix[i + 1][j]: return False if j < cols - 1: if rules[2 * i][j] == 'E': if filled_matrix[i][j] != filled_matrix[i][j + 1]: return False elif rules[2 * i][j] == 'N': if filled_matrix[i][j] == filled_matrix[i][j + 1]: return False return True
The image demonstrates how to fill numbers in a matrix based on predefined rules using two examples, labeled "Example 1" and "Example 2." The letters "E" (equal) and "N" (not equal) are used to describe these rules. ### **Example 1**: 1. **Rules**: - The matrix is structured with "E" and "N". - The rules are: [ [E], [N, N], [E] ] - The initial 2x2 matrix looks like: ``` * E * N N * E * ``` '*' indicates the empty cell. 2. **Filled Matrix**: - The result is a filled matrix: ``` 1 E 1 N N 2 E 2 ``` ### **Example 2**: 1. **Rules**: - The rules are: [ [E, N], [N, N, E], [E, N] ] - The initial 2x3 matrix looks like: ``` * E * N * N N E * E * N * ``` '*' indicates the empty cell. 2. **Filled Matrix**: The result is a filled matrix: ``` 1 E 1 N 2 N N E 3 E 3 N 2 ```
def test(): relations = [ ['E'], ['N', 'N'], ['E'] ] filled_matrix = [ [1, 1], [2, 2] ] result = solution(relations, filled_matrix) assert result == True, f"Assert Error: input {relations, filled_matrix}, expected True, got {result}" filled_matrix = [ [1, 1], [1, 2] ] result = solution(relations, filled_matrix) assert result == False, f"Assert Error: input {relations, filled_matrix}, expected False, got {result}" relations = [ ['E'], ['E', 'E'], ['E'] ] filled_matrix = [ [1, 1], [1, 2] ] result = solution(relations, filled_matrix) assert result == False, f"Assert Error: input {relations, filled_matrix}, expected False, got {result}" filled_matrix = [ [1, 1], [1, 1] ] result = solution(relations, filled_matrix) assert result == True, f"Assert Error: input {relations, filled_matrix}, expected True, got {result}" relations = [ ['E', 'N'], ['N', 'N', 'E'], ['E', 'N'] ] filled_matrix = [ [1, 1, 3], [2, 2, 3] ] result = solution(relations, filled_matrix) assert result == True, f"Assert Error: input {relations, filled_matrix}, expected True, got {result}" filled_matrix = [ [1, 1, 3], [2, 2, 2] ] result = solution(relations, filled_matrix) assert result == False, f"Assert Error: input {relations, filled_matrix}, expected False, got {result}" relations = [ ['E', 'N','E'], ['N', 'N', 'E', 'E'], ['N', 'E', 'E'], ['E', 'N', 'E', 'N'], ['E', 'N', 'N'] ] filled_matrix = [ [1, 1, 2, 2], [3, 2, 2, 2], [3, 3, 2, 1], ] result = solution(relations, filled_matrix) assert result == True, f"Assert Error: input {relations, filled_matrix}, expected True, got {result}" filled_matrix = [ [1, 1, 2, 2], [3, 2, 2, 2], [3, 3, 2, 2], ] result = solution(relations, filled_matrix) assert result == False, f"Assert Error: input {relations, filled_matrix}, expected False, got {result}" test()
from typing import List def solution(rules: List[List[str]], filled_matrix: List[List[int]]) -> bool: """ Determine whether the filled_matrix satisfies the restriction rules. Input: - rules: A 2d list containting 'E' or 'N' that specify the restrictions, as illustrated in the image. for example, [['E'], ['N', 'N'], ['E']] for a 2x2 matrix. - filled_matrix: A 2d list containing integers. Output: - A boolean value indicating whether the filled_matrix satisfies the restriction rules. """
q26-2
from typing import List def solution(rules: List[List[str]], filled_matrix: List[List[int]]) -> bool: """ Determine whether the filled_matrix satisfies the restriction rules. Input: - rules: A 2d list containting 'L' or 'G' that specify the restrictions, as illustrated in the image. for example, [['L'], ['G', 'G'], ['L']] for a 2x2 matrix. - filled_matrix: A 2d list containing integers. Output: - A boolean value indicating whether the filled_matrix satisfies the restriction rules. """ rows = len(filled_matrix) cols = len(filled_matrix[0]) for i in range(rows): for j in range(cols): if i < rows - 1: if rules[2 * i + 1][j] == 'L': if filled_matrix[i][j] >= filled_matrix[i + 1][j]: return False elif rules[2 * i + 1][j] == 'G': if filled_matrix[i][j] <= filled_matrix[i + 1][j]: return False if j < cols - 1: if rules[2 * i][j] == 'L': if filled_matrix[i][j] >= filled_matrix[i][j + 1]: return False elif rules[2 * i][j] == 'G': if filled_matrix[i][j] <= filled_matrix[i][j + 1]: return False return True
The image demonstrates how to fill numbers in a matrix based on predefined rules using two examples, labeled "Example 1" and "Example 2." The letters "L" (Less than) and "G" (Greater than) are used to describe these rules. ### **Example 1**: 1. **Rules**: - The matrix is structured with "L" and "G". - The rules are: [ [G], [L, L], [G] ] - The initial 2x2 matrix looks like: ``` * G * L L * G * ``` '*' indicates the empty cell. 2. **Filled Matrix**: - The result is a filled matrix: ``` 2 G 1 L L 3 G 2 ``` ### **Example 2**: 1. **Rules**: - The rules are: [ [G, L], [L, L, G], [G, L] ] - The initial 2x3 matrix looks like: ``` * G * L * L L G * G * L * ``` '*' indicates the empty cell. 2. **Filled Matrix**: The result is a filled matrix: ``` 3 G 2 L 5 L L G 4 G 3 L 4 ```
def test(): relations = [ ['G'], ['L', 'L'], ['G'] ] filled_matrix = [ [2, 1], [3, 2] ] result = solution(relations, filled_matrix) assert result == True, f"Assert Error: input {relations, filled_matrix}, expected True, got {result}" filled_matrix = [ [4, 2], [5, 3] ] result = solution(relations, filled_matrix) assert result == True, f"Assert Error: input {relations, filled_matrix}, expected False, got {result}" filled_matrix = [ [4, 5], [5, 3] ] result = solution(relations, filled_matrix) assert result == False, f"Assert Error: input {relations, filled_matrix}, expected False, got {result}" relations = [ ['L'], ['L', 'L'], ['G'] ] filled_matrix = [ [3, 4], [6, 5] ] result = solution(relations, filled_matrix) assert result == True, f"Assert Error: input {relations, filled_matrix}, expected False, got {result}" filled_matrix = [ [4, 8], [16, 12] ] result = solution(relations, filled_matrix) assert result == True, f"Assert Error: input {relations, filled_matrix}, expected True, got {result}" filled_matrix = [ [4, 8], [1, 12] ] result = solution(relations, filled_matrix) assert result == False, f"Assert Error: input {relations, filled_matrix}, expected True, got {result}" relations = [ ['G', 'L'], ['L', 'L', 'G'], ['G', 'L'] ] filled_matrix = [ [3, 2, 5], [4, 3, 4] ] result = solution(relations, filled_matrix) assert result == True, f"Assert Error: input {relations, filled_matrix}, expected True, got {result}" filled_matrix = [ [4, 3, 6], [5, 4, 5] ] result = solution(relations, filled_matrix) assert result == True, f"Assert Error: input {relations, filled_matrix}, expected False, got {result}" filled_matrix = [ [4, 3, 6], [1, 4, 5] ] result = solution(relations, filled_matrix) assert result == False, f"Assert Error: input {relations, filled_matrix}, expected False, got {result}" relations = [ ['L', 'L', 'L'], ['L', 'L', 'L', 'L'], ['G', 'G', 'G'], ['L', 'L', 'L', 'L'], ['L', 'L', 'L'] ] filled_matrix = [ [3, 4, 5, 6], [10, 9, 8, 7], [11, 12, 13, 14], ] result = solution(relations, filled_matrix) assert result == True, f"Assert Error: input {relations, filled_matrix}, expected True, got {result}" filled_matrix = [ [1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], ] result = solution(relations, filled_matrix) assert result == True, f"Assert Error: input {relations, filled_matrix}, expected False, got {result}" filled_matrix = [ [1, 2, 3, 0], [8, 7, 6, 5], [9, 1, 11, 12], ] result = solution(relations, filled_matrix) assert result == False, f"Assert Error: input {relations, filled_matrix}, expected False, got {result}" test()
from typing import List def solution(rules: List[List[str]], filled_matrix: List[List[int]]) -> bool: """ Determine whether the filled_matrix satisfies the restriction rules. Input: - rules: A 2d list containting 'L' or 'G' that specify the restrictions, as illustrated in the image. for example, [['L'], ['G', 'G'], ['L']] for a 2x2 matrix. - filled_matrix: A 2d list containing integers. Output: - A boolean value indicating whether the filled_matrix satisfies the restriction rules. """
q27
from typing import Tuple def solution(n: int, initial_point: Tuple[int, int], t: int) -> int: """ Calculate the number of infected cells after t days. Input: - n: An integer representing the size of the grid (n x n). - initial_point: A tuple (x, y) representing the coordinates of the initial infection point. - t: An integer representing the elapsed time in days. Output: - An integer representing the total number of infected cells after t days. """ # Initialize the grid grid = [[0] * n for _ in range(n)] # Convert initial_point to 0-indexed x, y = initial_point[0] - 1, initial_point[1] - 1 # Set the initial infection point grid[x][y] = 1 # Directions for up, down, left, right directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # Iterate for each day for day in range(t): new_infections = [] for i in range(n): for j in range(n): if grid[i][j] != 1: continue # Spread the infection to adjacent cells for dx, dy in directions: ni, nj = i + dx, j + dy if 0 <= ni < n and 0 <= nj < n and grid[ni][nj] == 0: new_infections.append((ni, nj)) # Mark new infections for ni, nj in new_infections: grid[ni][nj] = 1 # Count the number of infected cells infected_cells = sum(sum(row) for row in grid) return infected_cells
The image illustrates the spread of an infection over the course of four days in a 6x6 grid. The grid cells are labeled as either healthy (white) or infected (blue), showing how the infection expands from an initial point. Here’s how the infection progresses over the course of 4 days and each cell can be either H for healthy or I for infected.: ### **Day 1**: ``` H H H H H H H H H H H H H H H H I H H H H H H H H H H H H H H H H H H H ``` ### **Day 2**: ``` H H H H H H H H H H I H H H H I I I H H H H I H H H H H H H H H H H H H ``` ### **Day 3**: ``` H H H H I H H H H I I I H H I I I I H H H I I I H H H H I H H H H H H H ``` ### **Day 4**: ``` H H H I I I H H I I I I H I I I I I H H I I I I H H H I I I H H H H I H ```
def test(): test_cases = [ (6, (3, 5), 0, 1), (6, (3, 5), 2, 12), (6, (3, 5), 3, 20), (9, (3, 8), 2, 12), (3, (2, 2), 2, 9), (6, (1, 6), 5, 21), (6, (1, 6), 6, 26), (6, (6, 3), 3, 15), (6, (6, 3), 4, 21), ] for n, initial_point, t, expected_result in test_cases: assert solution(n, initial_point, t) == expected_result, f"Assert Error: Test case failed: {n, initial_point, t, expected_result}" test()
from typing import Tuple def solution(n: int, initial_point: Tuple[int, int], t: int) -> int: """ Calculate the number of infected cells after t days. Input: - n: An integer representing the size of the grid (n x n). - initial_point: A tuple (x, y) representing the coordinates of the initial infection point. - t: An integer representing the elapsed time in days. Output: - An integer representing the total number of infected cells after t days. """
q27-2
from typing import Tuple def solution(n: int, initial_point: Tuple[int, int], t: int) -> int: """ Calculate the number of infected cells after t days. Input: - n: An integer representing the size of the grid (n x n). - initial_point: A tuple (x, y) representing the coordinates of the initial infection point. - t: An integer representing the elapsed time in days. Output: - An integer representing the total number of infected cells after t days. """ # Initialize the grid grid = [[0] * n for _ in range(n)] # Convert initial_point to 0-indexed x, y = initial_point[0] - 1, initial_point[1] - 1 # Set the initial infection point grid[x][y] = 1 # Directions for up, down, left, right directions = [(-1, -1), (-1, 1), (1, -1), (1, 1)] # Iterate for each day for day in range(t): new_infections = [] for i in range(n): for j in range(n): if grid[i][j] != 1: continue # Spread the infection to adjacent cells for dx, dy in directions: ni, nj = i + dx, j + dy if 0 <= ni < n and 0 <= nj < n and grid[ni][nj] == 0: new_infections.append((ni, nj)) # Mark new infections for ni, nj in new_infections: grid[ni][nj] = 1 # Count the number of infected cells infected_cells = sum(sum(row) for row in grid) return infected_cells
The image illustrates the spread of an infection over the course of four days in a 6x6 grid. The grid cells are labeled as either healthy (white) or infected (blue), showing how the infection expands from an initial point. Here’s how the infection progresses over the course of 4 days and each cell can be either H for healthy or I for infected. Every day passed, there will be new infections which is on the four corner of the previous infection blocks, forming a checkerboard pattern over time: ### **Day 1**: ``` H H H H H H H H H H H H H H H H I H H H H H H H H H H H H H H H H H H H ``` ### **Day 2**: ``` H H H H H H H H H I H I H H H H I H H H H I H I H H H H H H H H H H H H ``` ### **Day 3**: ``` H H I H I H H H H I H I H H I H I H H H H I H I H H I H I H H H H H H H ``` ### **Day 4**: ``` H H I H I H H I H I H I H H I H I H H I H I H I H H I H I H H I H I H I ```
def test(): test_cases = [ (6, (3, 5), 0, 1), (6, (3, 5), 2, 10), (6, (3, 5), 3, 15), (9, (3, 8), 2, 10), (3, (2, 2), 2, 5), (6, (1, 6), 5, 18), (6, (1, 6), 6, 18), (6, (6, 3), 3, 12), (6, (6, 3), 4, 15), ] for n, initial_point, t, expected_result in test_cases: assert solution(n, initial_point, t) == expected_result, f"Assert Error: Test case failed: {n, initial_point, t, expected_result}" test()
from typing import Tuple def solution(n: int, initial_point: Tuple[int, int], t: int) -> int: """ Calculate the number of infected cells after t days. Input: - n: An integer representing the size of the grid (n x n). - initial_point: A tuple (x, y) representing the coordinates of the initial infection point. - t: An integer representing the elapsed time in days. Output: - An integer representing the total number of infected cells after t days. """
q27-3
from typing import Tuple def solution(n: int, initial_point: Tuple[int, int], t: int) -> int: """ Calculate the number of infected cells after t days. Input: - n: An integer representing the size of the grid (n x n). - initial_point: A tuple (x, y) representing the coordinates of the initial infection point. - t: An integer representing the elapsed time in days. Output: - An integer representing the total number of infected cells after t days. """ # Initialize the grid grid = [[0] * n for _ in range(n)] # Convert initial_point to 0-indexed x, y = initial_point[0] - 1, initial_point[1] - 1 # Set the initial infection point grid[x][y] = 1 # Directions for up, down, left, right directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] new_latents = [] # Iterate for each day for day in range(t): new_infections = [] if new_latents: for new_latent in new_latents: new_infections.append(new_latent) new_latents = [] else: for i in range(n): for j in range(n): if grid[i][j] != 1: continue # Spread the infection to adjacent cells else: for dx, dy in directions: ni, nj = i + dx, j + dy if 0 <= ni < n and 0 <= nj < n and grid[ni][nj] == 0: new_latents.append((ni, nj)) # Mark new infections for ni, nj in new_infections: grid[ni][nj] = 1 # Count the number of infected cells infected_cells = sum(sum(row) for row in grid) return infected_cells def test(): test_cases = [ (6, (3, 5), 0, 1), (6, (3, 5), 2, 5), (6, (3, 5), 3, 5), (9, (3, 8), 2, 5), (3, (2, 2), 2, 5), (6, (1, 6), 5, 6), (6, (1, 6), 6, 10), (6, (6, 3), 3, 4), (6, (6, 3), 4, 9), ] for n, initial_point, t, expected_result in test_cases: assert solution(n, initial_point, t) == expected_result, f"Assert Error: Test case failed: {n, initial_point, t, expected_result}" test()
The image illustrates the spread of an infection over the course of four days in a 6x6 grid. The grid cells are labeled as either healthy (white), latent period (blue stripes) or infected (blue), showing how the infection expands from an initial point. Here’s how the infection progresses over the course of 4 days and each cell can be H for healthy, L for latent period I for infected.: ### **Day 1**: ``` H H H H H H H H H H H H H H H H I H H H H H H H H H H H H H H H H H H H ``` ### **Day 2**: ``` H H H H H H H H H H L H H H H L I L H H H H L H H H H H H H H H H H H H ``` ### **Day 3**: ``` H H H H H H H H H H I H H H H I I I H H H H I H H H H H H H H H H H H H ``` ### **Day 4**: ``` H H H H L H H H H L I L H H L I I I H H H L I L H H H H L H H H H H H H ```
def test(): test_cases = [ (6, (3, 5), 0, 1), (6, (3, 5), 2, 5), (6, (3, 5), 3, 5), (9, (3, 8), 2, 5), (3, (2, 2), 2, 5), (6, (1, 6), 5, 6), (6, (1, 6), 6, 10), (6, (6, 3), 3, 4), (6, (6, 3), 4, 9), ] for n, initial_point, t, expected_result in test_cases: assert solution(n, initial_point, t) == expected_result, f"Assert Error: Test case failed: {n, initial_point, t, expected_result}" test()
from typing import Tuple def solution(n: int, initial_point: Tuple[int, int], t: int) -> int: """ Calculate the number of infected cells after t days. Input: - n: An integer representing the size of the grid (n x n). - initial_point: A tuple (x, y) representing the coordinates of the initial infection point. - t: An integer representing the elapsed time in days. Output: - An integer representing the total number of infected cells after t days. """
q28
from typing import List def solution(terrain: List[int]) -> int: """ Determine the index of the terrain block where pouring water would result in the most area being covered with water. The water will quickly seep into the terrain block and will not accumulate between the blocks. Input: - terrain: A list of integers representing a series of terrain blocks with differenct heights. Output: - An integer representing the zero-based index of the identified terrain block. """ def calculate_covered_area(index: int) -> int: left = index while left > 0 and terrain[left - 1] <= terrain[left]: left -= 1 right = index while right < len(terrain) - 1 and terrain[right + 1] <= terrain[right]: right += 1 return right - left + 1 max_area = 0 best_index = 0 for i in range(len(terrain)): current_area = calculate_covered_area(i) if current_area > max_area: max_area = current_area best_index = i return best_index
The image compares the scenarios that water flows on the surface of different bars. Both examples illustrate how water can flow between the bars, with the blue color representing the flowing water. Each bar is labeled with a number to indicate its height. Here’s a breakdown of each example: ### **Example 1**: - The bars have the following heights from left to right: **3, 1, 2, 3, 3, 2, 4** and the water tap pours water on the fourth bar(3). - Water flows to the neighbor bars that are lower than or equal to the fourth bar: The water covers the surface from the second bar to the sixth bar (1, 2, 3, 3, 2). ### **Example 2**: - The bars in this example have the following heights from left to right: **3, 1, 4, 3, 3, 2, 4** and the water tap pours water on the fourth bar(3). - Water flows to the neighbor bars that are lower than or equal to the fourth bar: The water covers the surface from the fourth bar to the sixth bar (3, 3, 2).
def test(): terrain = [3, 1, 2, 3, 3, 2, 4] expected_result_1 = 3 expected_result_2 = 4 result = solution(terrain) assert result in [expected_result_1, expected_result_2], f"Assert Error: terrain={terrain}, expected_result={expected_result_1}, result={result}" terrain = [1, 2, 3, 4] expected_result = 3 result = solution(terrain) assert result == expected_result, f"Assert Error: terrain={terrain}, expected_result={expected_result}, result={result}, result={result}" terrain = [3, 2, 1, 1, 1] expected_result = 0 result = solution(terrain) assert result == expected_result, f"Assert Error: terrain={terrain}, expected_result={expected_result}, result={result}, result={result}" terrain = [1, 3, 3, 5, 3, 5, 9, 5, 1, 3, 6, 8, 6, 4, 2, 7, 9, 6, 4, 2, 8, 2, 3, 4, 5, 1, 7, 1] expected_result = 11 result = solution(terrain) assert result == expected_result, f"Assert Error: terrain={terrain}, expected_result={expected_result}, result={result}, result={result}" terrain = [1, 3, 3, 5, 9, 5, 1, 3, 6, 8, 6, 4, 2, 3, 4, 5, 1, 7, 1] expected_result = 4 result = solution(terrain) assert result == expected_result, f"Assert Error: terrain={terrain}, expected_result={expected_result}, result={result}, result={result}" terrain = [2, 5, 3, 6, 4] expected_result = 1 result = solution(terrain) assert result == expected_result, f"Assert Error: terrain={terrain}, expected_result={expected_result}, result={result}, result={result}" terrain = [8, 8, 5, 5, 3, 3, 7, 7, 5, 5, 6, 6, 3, 3, 8, 8, 6, 6, 3, 3, 1, 1, 3, 3, 4, 4, 7, 7, 9, 9] expected_result = 14 result = solution(terrain) assert result == expected_result, f"Assert Error: terrain={terrain}, expected_result={expected_result}, result={result}, result={result}" test()
from typing import List def solution(terrain: List[int]) -> int: """ Determine the index of the terrain block where pouring water would result in the most area being covered with water. The water will quickly seep into the terrain block and will not accumulate between the blocks. Input: - terrain: A list of integers representing a series of terrain blocks with differenct heights. Output: - An integer representing the zero-based index of the identified terrain block. """
q29
from typing import List, Tuple def solution(n: int, chain: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> int: """ Given a chain and a yellow region in an n x n 2D matrix, find the number of red regions that are formed. Parameters: n (int): The size of the matrix. chain (List[Tuple[int, int]]): Coordinates of each node in the chain in order. top_left (Tuple[int, int]): Coordinates of the top-left corner of the yellow region. bottom_right (Tuple[int, int]): Coordinates of the bottom-right corner of the yellow region. Returns: int: The number of red regions. """ def is_inside(x: int, y: int) -> bool: """ Check if a point is inside the yellow region """ return top_left[0] <= x <= bottom_right[0] and top_left[1] <= y <= bottom_right[1] crossings = 0 for i in range(len(chain) - 1): x1, y1 = chain[i] x2, y2 = chain[i + 1] # Check if one point is inside and the other is outside the yellow region if is_inside(x1, y1) != is_inside(x2, y2): crossings += 1 return crossings
The figure shows a 4x4 grid with a blue polyline passing through multiple cells, and a rectangular yellow highlighted area that spans from cell (1,0) to cell (2,2). The polyline moves both vertically and horizontally through the grid, intersecting certain points. When the blue polyline crosses the boundary of the yellow area. The line segments through the yellow area's boundaries are marked in red
def test(): test_cases = [ (2, [(0, 0), (0, 1), (1, 1), (1, 0)], (1, 0), (1, 1), 1), (2, [(0, 0), (0, 1), (1, 1), (1, 0)], (1, 1), (1, 1), 2), (2, [(0, 0), (0, 1), (1, 1), (1, 0)], (1, 1), (1, 1), 2), (2, [(0, 0), (0, 1), (1, 0)], (1, 1), (1, 1), 0), (3, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (2, 2), (1, 2), (1, 1)], (1, 0), (2, 1), 3), (3, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (2, 2), (1, 2), (1, 1)], (1, 0), (2, 2), 1), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3)], (1, 0), (2, 2), 4), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2)], (1, 0), (2, 2), 5), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2)], (1, 0), (2, 2), 6), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2)], (0, 0), (2, 2), 4), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2)], (0, 0), (3, 3), 0), ] for i, (n, chain, top_left, bottom_right, expected) in enumerate(test_cases): result = solution(n, chain, top_left, bottom_right) assert result == expected, f"Assert Error: Input {(n, chain, top_left, bottom_right)}, Expected {expected}, Got: {result}" test()
from typing import List, Tuple def solution(n: int, chain: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> int: """ Given a chain and a yellow region in an n x n 2D matrix, find the number of red regions that are formed. Parameters: n (int): The size of the matrix. chain (List[Tuple[int, int]]): Coordinates of each node in the chain in order. top_left (Tuple[int, int]): Coordinates of the top-left corner of the yellow region. bottom_right (Tuple[int, int]): Coordinates of the bottom-right corner of the yellow region. Returns: int: The number of red regions. """
q29-2
from typing import List, Tuple def solution(n: int, chain: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> Tuple[int, int]: """ Given a chain and a yellow region in an n x n 2D matrix, find the number of red regions and green regions that are formed. Parameters: n (int): The size of the matrix. chain (List[Tuple[int, int]]): Coordinates of each node in the chain in order. top_left (Tuple[int, int]): Coordinates of the top-left corner of the yellow region. bottom_right (Tuple[int, int]): Coordinates of the bottom-right corner of the yellow region. Returns: Tuple[int,int]: The number of red regions and green regions respectively. """ def is_inside(x: int, y: int) -> bool: """ Check if a point is inside the yellow region """ return top_left[0] <= x <= bottom_right[0] and top_left[1] <= y <= bottom_right[1] v_crossings = 0 h_crossings = 0 for i in range(len(chain) - 1): x1, y1 = chain[i] x2, y2 = chain[i + 1] # Check if one point is inside and the other is outside the yellow region if is_inside(x1, y1) != is_inside(x2, y2): if x1 == x2: v_crossings += 1 else: h_crossings += 1 return (v_crossings, h_crossings)
The figure shows a 4x4 grid with a blue polyline passing through multiple cells, and a rectangular yellow highlighted area that spans from cell (1,0) to cell (2,2). The polyline moves both vertically and horizontally through the grid, intersecting certain points. When the blue polyline crosses the boundary of the yellow area. The line segments through the yellow area's boundaries are marked in red or green. Red marks intersections where the polyline crosses the boundary vertically. Green marks intersections where the polyline crosses the boundary horizontally.
def test(): test_cases = [ (2, [(0, 0), (0, 1), (1, 1), (1, 0)], (1, 0), (1, 1), (0, 1)), (2, [(0, 0), (0, 1), (1, 1), (1, 0)], (1, 1), (1, 1), (1, 1)), (2, [(0, 0), (0, 1), (1, 0)], (1, 1), (1, 1), (0, 0)), (3, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (2, 2), (1, 2), (1, 1)], (1, 0), (2, 1), (2,1)), (3, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (2, 2), (1, 2), (1, 1)], (1, 0), (2, 2), (0, 1)), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2)], (1, 0),(2, 2),(2,3)), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3)], (1, 0), (2, 2), (1, 3)), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2)], (1, 0), (2, 2), (2,3)), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2)], (1, 0), (2, 2), (2, 4)), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2)], (0, 0), (2, 2), (2, 2)), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2)], (0, 0), (3, 3), (0, 0)), ] for i, (n, chain, top_left, bottom_right, expected) in enumerate(test_cases): result = solution(n, chain, top_left, bottom_right) assert result == expected, f"Assert Error: Input {(n, chain, top_left, bottom_right)}, Expected {expected}, Got: {result}" test()
from typing import List, Tuple def solution(n: int, chain: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> Tuple[int, int]: """ Given a chain and a yellow region in an n x n 2D matrix, find the number of red regions and green regions that are formed. Parameters: n (int): The size of the matrix. chain (List[Tuple[int, int]]): Coordinates of each node in the chain in order. top_left (Tuple[int, int]): Coordinates of the top-left corner of the yellow region. bottom_right (Tuple[int, int]): Coordinates of the bottom-right corner of the yellow region. Returns: Tuple[int,int]: The number of red regions and green regions respectively. """
q3
def solution(start: str, end: str) -> list[str]: """ Find the shortest path from one point to another Parameters: start (str): The starting node of the path. end (str): The ending node of the path. Returns: Optional[List[str]]: A list of nodes representing the path from start to end, if such a path exists. Returns None if no path exists. Example: path = solution('C', 'B') # Output might be ['C', 'A', 'B'] """ graph = { 'A': ['B'], 'B': ['D', 'E'], 'C': ['A', 'D'], 'D': ['A'], 'E': [] # No outgoing edges from E } if start not in graph or end not in graph: return None queue = [[start]] # Initialize the queue with the starting node in a path list visited = set() # To keep track of visited nodes while queue: path = queue.pop(0) # Get the first path from the queue (FIFO) node = path[-1] # Get the last node in the path if node in visited: continue visited.add(node) # Check if we've reached the end node if node == end: return path # Explore adjacent nodes for neighbor in graph[node]: new_path = path + [neighbor] # Create a new path including the neighbor queue.append(new_path) # If the loop ends, no path was found return None
The image shows a directed graph with five nodes, where C can reach A and D, D can reach A, A can reach B, and B can reach both D and E.
def test(): test_cases = [ ('A', 'B', ['A', 'B']), ('C', 'E', ['C', 'A', 'B', 'E']), ('A', 'E', ['A', 'B', 'E']), ('B', 'D', ['B', 'D']), ('C', 'B', ['C', 'A', 'B']), ('C', 'D', ['C', 'D']), ('B', 'E', ['B', 'E']) ] for start, end, expected in test_cases: result = solution(start, end) assert result == expected, f"Assert Error: Test failed for nodes {start, end}. Expected {expected}, got {result}" none_cases = [ ['E', 'C'], ['E', 'B'] ] for start, end, in none_cases: result = solution(start, end) assert not result, f"Assert Error: Test failed for nodes {start, end}. Expected None, got {result}" test()
def solution(start: str, end: str) -> list[str]: """ Find the shortest path from one point to another Parameters: start (str): The starting node of the path. end (str): The ending node of the path. Returns: Optional[List[str]]: A list of nodes representing the path from start to end, if such a path exists. Returns None if no path exists. Example: path = solution('C', 'B') # Output might be ['C', 'A', 'B'] """ graph = {}
q3-2
def solution(start: str, end: str) -> list[str]: """ Find the shortest path from one point to another Parameters: start (str): The starting node of the path. end (str): The ending node of the path. Returns: Optional[List[str]]: A list of nodes representing the path from start to end, if such a path exists. Returns None if no path exists. Example: path = solution('A', 'E') # Output might be ['A', 'B', 'E'] """ graph = { 'A': ['B', 'C', 'D'], 'B': ['A', 'E', 'D'], 'C': ['A', 'D'], 'D': ['C', 'A', 'B'], 'E': ['B'] } if start not in graph or end not in graph: return None queue = [[start]] # Initialize the queue with the starting node in a path list visited = set() # To keep track of visited nodes while queue: path = queue.pop(0) # Get the first path from the queue (FIFO) node = path[-1] # Get the last node in the path if node in visited: continue visited.add(node) # Check if we've reached the end node if node == end: return path # Explore adjacent nodes for neighbor in graph[node]: new_path = path + [neighbor] # Create a new path including the neighbor queue.append(new_path) # If the loop ends, no path was found return None
The image shows an undirected graph with five nodes, where A is connected to B, D, and C; B is connected to A, D, and E; D is connected to A, B, and C; C is connected to A and D; and E is connected to B.
def test(): test_cases = [ ('A', 'B', ['A', 'B']), ('A', 'E', ['A', 'B', 'E']), ('B', 'D', ['B', 'D']), ('C', 'D', ['C', 'D']), ('B', 'E', ['B', 'E']) ] for start, end, expected in test_cases: result = solution(start, end) assert result == expected, f"Assert Error: Test failed for nodes {start, end}. Expected {expected}, got {result}" multi_cases = [ ('C', 'E', ['C', 'A', 'B', 'E'], ['C', 'D', 'B', 'A']), ('C', 'B', ['C', 'A', 'B'], ['C', 'D', 'B']), ] for start, end, expected_1, expected_2 in multi_cases: result = solution(start, end) assert result == expected_1 or result == expected_2, f"Assert Error: Test failed for nodes {start, end}. Expected {expected_1} or {expected_2}, got {result}" test()
def solution(start: str, end: str) -> list[str]: """ Find the shortest path from one point to another Parameters: start (str): The starting node of the path. end (str): The ending node of the path. Returns: Optional[List[str]]: A list of nodes representing the path from start to end, if such a path exists. Returns None if no path exists. Example: path = solution('A', 'E') # Output might be ['A', 'B', 'E'] """ graph = {}
q3-3
def solution(start: str, end: str) -> list[str]: """ Find the shortest path from one point to another Parameters: start (str): The starting node of the path. end (str): The ending node of the path. Returns: Optional[List[str]]: A list of nodes representing the path from start to end, if such a path exists. Returns None if no path exists. Example: path = solution('A', 'E') # Output might be ['A', 'B', 'E'] """ graph = { 'A': ['B'], 'B': ['D'], 'C': ['A'], 'D': ['C'], 'E': ['B', 'D'] } if start not in graph or end not in graph: return None queue = [[start]] # Initialize the queue with the starting node in a path list visited = set() # To keep track of visited nodes while queue: path = queue.pop(0) # Get the first path from the queue (FIFO) node = path[-1] # Get the last node in the path if node in visited: continue visited.add(node) # Check if we've reached the end node if node == end: return path # Explore adjacent nodes for neighbor in graph[node]: new_path = path + [neighbor] # Create a new path including the neighbor queue.append(new_path) # If the loop ends, no path was found return None
The image shows a directed graph with five nodes, where A can reach B, C can reach A, D can reach C, B can reach D, and E can reach both B and D.
def test(): test_cases = [ ('A', 'B', ['A', 'B']), ('E', 'C', ['E', 'D', 'C']), ('E', 'A', ['E', 'D', 'C', 'A']), ('B', 'D', ['B', 'D']), ('C', 'B', ['C', 'A', 'B']), ('C', 'D', ['C', 'A', 'B', 'D']), ('E', 'B', ['E', 'B']) ] for start, end, expected in test_cases: result = solution(start, end) assert result == expected, f"Assert Error: Test failed for nodes {start, end}. Expected {expected}, got {result}" none_cases = [ ['C', 'E'], ['A', 'E'] ] for start, end, in none_cases: result = solution(start, end) assert not result, f"Assert Error: Test failed for nodes {start, end}. Expected None, got {result}" test()
def solution(start: str, end: str) -> list[str]: """ Find the shortest path from one point to another Parameters: start (str): The starting node of the path. end (str): The ending node of the path. Returns: Optional[List[str]]: A list of nodes representing the path from start to end, if such a path exists. Returns None if no path exists. Example: path = solution('A', 'E') # Output might be ['A', 'B', 'E'] """ graph = {}
q30
class TreeNode: """ This class represents a node in a tree. Each node contains a value and a list of children. """ def __init__(self, value, children=[]): self.value = value self.children = children def is_symmetric(left: TreeNode, right: TreeNode) -> bool: if not left and (not right): return True if not left or not right: return False if left.value != right.value: return False if len(left.children) != len(right.children): return False for l_child, r_child in zip(left.children, reversed(right.children)): if not is_symmetric(l_child, r_child): return False return True def solution(root: TreeNode) -> int: """ Determine which type the tree belongs to Parameters: root (TreeNode): The root node of the tree. Returns: int: Type 1 or 2. """ if not root: return 1 if is_symmetric(root, root): return 1 else: return 2
The image shows two different types of binary trees, labeled Tree Type 1 and Tree Type 2. Each type contains four examples of binary trees. There are dashed vertical lines passing through the root node of each tree to indicate symmetry relations. ### **Tree Type 1** : These trees are marked with a green dashed line through the root. #### Example 1: ``` 3 / \ 4 4 ``` #### Example 2: ``` 3 / \ 4 4 / \ 1 1 ``` #### Example 3: ``` 7 / \ 1 1 /|\ /|\ 7 1 6 6 1 7 ``` #### Example 4: ``` 8 / \ 3 3 / \ / \ 5 2 2 5 ``` --- ### **Tree Type 2** : In these examples, a red "X" appears on a red dashed line. #### Example 1 : ``` 3 / \ 4 5 ``` #### Example 2 : ``` 3 / \ 4 4 / 1 ``` #### Example 3 : ``` 7 / \ 1 1 /|\ \ 7 1 6 7 ``` #### Example 4 : ``` 8 / \ 3 3 / \ / \ 2 4 2 4 ``` ### Key Symbols: - **/ \**: Represents left and right children.
def test(): Tree0 = TreeNode(0) # 1 Tree1 = TreeNode(1, [TreeNode(1), TreeNode(2)]) # 2 Tree2 = TreeNode(3, [TreeNode(3)]) # 1 Tree3 = TreeNode(2, [TreeNode(2), TreeNode(2, [TreeNode(2)])]) # 2 Tree4 = TreeNode(2, [TreeNode(1, [TreeNode(2)]), TreeNode(2, [TreeNode(3)])]) # 2 Tree5 = TreeNode(5, [TreeNode(5, [TreeNode(5, [TreeNode(5)]), TreeNode(5)]), TreeNode(5, [TreeNode(5), TreeNode(5)])]) # 2 Tree6 = TreeNode(8, [TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)]), TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)])]) # 2 Tree7 = TreeNode(2, [TreeNode(2, [TreeNode(2, [TreeNode(1)]), TreeNode(2)]), TreeNode(2, [TreeNode(2), TreeNode(1, [TreeNode(2)])])]) # 2 Tree8 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3)]), TreeNode(3, [TreeNode(3), TreeNode(3, [TreeNode(3)])])]) # 1 Tree9 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3, [TreeNode(3)])]), TreeNode(3, [TreeNode(3), TreeNode(3, [TreeNode(3)])])]) # 2 Tree10 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3, [TreeNode(3)])]), TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3, [TreeNode(3)])])]) # 1 test_cases = [ (Tree0, 1), (Tree1, 2), (Tree2, 1), (Tree3, 2), (Tree4, 2), (Tree5, 2), (Tree6, 2), (Tree7, 2), (Tree8, 1), (Tree9, 2), (Tree10, 1), ] for i, (root, expected) in enumerate(test_cases): result = solution(root) assert result == expected, f"Assert Error: Input Tree {i}, Expected {expected}, Got: {result}" test()
class TreeNode: """ This class represents a node in a tree. Each node contains a value and a list of children. """ def __init__(self, value, children=[]): self.value = value self.children = children def solution(root: TreeNode) -> int: """ Determine which type the tree belongs to Parameters: root (TreeNode): The root node of the tree. Returns: int: Type 1 or 2. """
q30-2
class TreeNode: """ This class represents a node in a tree. Each node contains a value and a list of children. """ def __init__(self, value, children=[]): self.value = value self.children = children def are_identical(left: TreeNode, right: TreeNode) -> bool: """ Helper function to check if two subtrees are identical. Parameters: left (TreeNode): The root of the left subtree. right (TreeNode): The root of the right subtree. Returns: bool: True if the subtrees are identical, False otherwise. """ # If both subtrees are None, they are identical if not left and not right: return True # If one subtree is None and the other is not, they are not identical if not left or not right: return False # If root values are different, they are not identical if left.value != right.value: return False # Check if both subtrees have the same number of children if len(left.children) != len(right.children): return False # Recursively check if each pair of corresponding children are identical for i in range(len(left.children)): if not are_identical(left.children[i], right.children[i]): return False return True def solution(root: TreeNode) -> int: """ Determine which type the tree belongs to. Parameters: root (TreeNode): The root node of the tree. Returns: int: 1 if the tree's left and right subtrees are identical, otherwise 2. """ if len(root.children) < 2: return 1 left_subtree = root.children[0] right_subtree = root.children[1] # Check if the left and right subtrees are identical if are_identical(left_subtree, right_subtree): return 1 else: return 2
The image shows two different types of binary trees, labeled Tree Type 1 and Tree Type 2. Each type contains four examples of binary trees. There are dashed vertical lines passing through the root node of each tree. There are dashed vertical lines passing through the root node of each tree to indicate symmetry relations. ### **Tree Type 1** : These trees are marked with a green dashed line through the root. #### Example 1: ``` 3 / \ 4 4 ``` #### Example 2: ``` 3 / \ 4 4 / \ 1 1 ``` #### Example 3: ``` 7 / \ 1 1 /|\ /|\ 7 1 6 7 1 6 ``` #### Example 4: ``` 8 / \ 3 3 / \ / \ 5 2 5 2 ``` --- ### **Tree Type 2** : In these examples, a red "X" appears on a red dashed line. #### Example 1 : ``` 3 / \ 4 5 ``` #### Example 2 : ``` 3 / \ 4 4 / 1 ``` #### Example 3 : ``` 7 / \ 1 1 /|\ \ 7 1 6 7 ``` #### Example 4 : ``` 8 / \ 3 3 / \ / \ 2 4 4 2 ``` ### Key Symbols: - **/ \**: Represents left and right children.
def test(): Tree0 = TreeNode(0) # 1 Tree1 = TreeNode(1, [TreeNode(1), TreeNode(2)]) # 2 Tree2 = TreeNode(3, [TreeNode(3)]) # 1 Tree3 = TreeNode(2, [TreeNode(2), TreeNode(2, [TreeNode(2)])]) # 2 Tree4 = TreeNode(2, [TreeNode(1, [TreeNode(2)]), TreeNode(2, [TreeNode(3)])]) # 2 Tree5 = TreeNode(5, [TreeNode(5, [TreeNode(5, [TreeNode(5)]), TreeNode(5)]), TreeNode(5, [TreeNode(5, [TreeNode(5)]), TreeNode(5)])]) # 1 Tree6 = TreeNode(8, [TreeNode(2, [TreeNode(3, [TreeNode(4)]), TreeNode(5)]), TreeNode(2, [TreeNode(3, [TreeNode(4)]), TreeNode(5)])]) # 1 Tree7 = TreeNode(2, [TreeNode(2, [TreeNode(2, [TreeNode(1)]), TreeNode(2)]), TreeNode(2, [TreeNode(2), TreeNode(1, [TreeNode(2)])])]) # 2 Tree8 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3)]), TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3)])]) # 1 Tree9 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3, [TreeNode(3)])]), TreeNode(3, [TreeNode(3), TreeNode(3, [TreeNode(3)])])]) # 2 Tree10 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3, [TreeNode(3)])]), TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3, [TreeNode(3)])])]) # 1 Tree11 = TreeNode(1, [TreeNode(2, [TreeNode(3),TreeNode(2)]), TreeNode(2,[TreeNode(2), TreeNode(3)])]) test_cases = [ (Tree0, 1), (Tree1, 2), (Tree2, 1), (Tree3, 2), (Tree4, 2), (Tree5, 1), (Tree6, 1), (Tree7, 2), (Tree8, 1), (Tree9, 2), (Tree10, 1), (Tree11, 2), ] for i, (root, expected) in enumerate(test_cases): result = solution(root) assert result == expected, f"Assert Error: Input Tree {i}, Expected {expected}, Got: {result}" test()
class TreeNode: """ This class represents a node in a tree. Each node contains a value and a list of children. """ def __init__(self, value, children=[]): self.value = value self.children = children def solution(root: TreeNode) -> int: """ Determine which type the tree belongs to Parameters: root (TreeNode): The root node of the tree. Returns: int: Type 1 or 2. """
q31
from typing import List def solution(cubes: List[List[int]]) -> int: """ Count the red squares from a specified view of the stacked cubes. Parameters: cubes (List[List[int]]): A 2D list where cubes[i][j] represents the number of cubes stacked at row i, column j. Returns: int: The number of red squares from the given view. """ max_z = max(max(row) for row in cubes) return sum(1 for row in cubes for cell in row if cell >= max_z)
The image contains four examples, each demonstrating a 3D cube structure and its corresponding top view in a grid. The grid represents rows and columns, with **red cubes** highlighted to indicate **peak cubes**. Here’s a markdown-style breakdown of the examples.: ### **Example 1**: - **3D Cube Structure**: - The following is the matrix form of the structure, with numbers representing the number of blocks stacked there: [ [2,1,3], [1,0,1] ] - **Top View Representation**: - **Grid**: ``` [ [Y,Y,R], [Y,0,Y] ] ``` ### **Example 2**: - **3D Cube Structure**: [ [2,1,1] [1,0,1] ] - **Top View Representation**: - **Grid**: ``` [ [R,Y,Y], [Y,0,Y] ] ``` ### **Example 3**: - **3D Cube Structure**: [ [2,1,2], [1,0,1], [0,0,1] ] - **Top View Representation**: - **Grid**: ``` [R,Y,R], [Y,0,Y], [0,0,Y] ``` ### **Example 4**: - **3D Cube Structure**: [ [1,1,1], [0,0,1], [0,0,1] ] - **Top View Representation**: - **Grid**: ``` [ [R,R,R], [0,0,R], [0,0,R] ] ``` ### Key: - **R**: Red cube (Peak Cube). - **Y**: Yellow cube (non-peak, lower layer). - **0**: No cube exists at this position.
def test(): cubes1 = [[2, 1, 3], [1, 2, 1]] cubes2 = [[2, 1, 3], [1, 0, 1]] cubes3 = [[2, 1, 3], [1, 1, 1]] cubes4 = [[1, 2], [3, 4]] cubes5 = [[1, 2], [3, 0], [5, 6]] cubes6 = [[1, 2], [3, 0], [5, 6], [0, 8]] cubes7 = [[1, 2], [3, 4], [5, 6], [7, 9], [9, 9]] cubes8 = [[0, 0], [0, 0], [0, 0], [0, 1], [0, 0]] test_cases = [ (cubes1, 1), (cubes2, 1), (cubes3, 1), (cubes4, 1), (cubes5, 1), (cubes6, 1), (cubes7, 3), (cubes8, 1) ] for i, (cubes, expected) in enumerate(test_cases): result = solution(cubes) assert result == expected, f"Assert Error: Input {(cubes)}, Expected {expected}, Got: {result}" test()
from typing import List def solution(cubes: List[List[int]]) -> int: """ Count the red squares from a specified view of the stacked cubes. Parameters: cubes (List[List[int]]): A 2D list where cubes[i][j] represents the number of cubes stacked at row i, column j. Returns: int: The number of red squares from the given view. """
q31-2
from typing import List def solution(cubes: List[List[int]]) -> int: """ Count the red squares from a specified view of the stacked cubes. Parameters: cubes (List[List[int]]): A 2D list where cubes[i][j] represents the number of cubes stacked at row i, column j. Returns: int: The number of red squares from the given view. """ # for each column, find the first non-zero element in the last row last_none_zero_row = 0 for j in range(len(cubes[0])): for i in range(len(cubes)-1, -1, -1): if cubes[i][j] != 0: last_none_zero_row = max(last_none_zero_row, i) break red_squares = sum(cubes[last_none_zero_row]) return red_squares
The image contains four examples, each demonstrating a 3D cube structure and its corresponding main view in a grid. The 2D grid represents rows and columns, with **red cubes** highlighted to indicate **Front Cubes**. Here’s a markdown-style breakdown of the examples.: ### **Example 1**: - **3D Cube Structure**: - The following is the matrix form of the structure, with numbers representing the number of blocks stacked there: [ [2,1,3], [1,0,1] ] - **Main View Representation**: - **Grid**: ``` [ [0,0,Y], [Y,0,Y], [R,Y,R] ] ``` ### **Example 2**: - **3D Cube Structure**: [ [2,1,1] [1,0,1] ] - **Main View Representation**: - **Grid**: ``` [ [Y,0,0], [R,Y,R] ] ``` ### **Example 3**: - **3D Cube Structure**: [ [2,1,2], [1,0,1], [0,0,1] ] - **Main View Representation**: - **Grid**: ``` [Y,0,Y], [Y,Y,R] ``` ### **Example 4**: - **3D Cube Structure**: [ [1,1,1], [0,0,1], [0,0,1] ] - **Main View Representation**: - **Grid**: ``` [ [Y,Y,R] ] ``` ### Key: - **R**: Red cube (Peak Cube). - **Y**: Yellow cube (non-peak, lower layer). - **0**: No cube exists at this position.
def test(): cubes1 = [[2, 1, 3], [1, 2, 1]] cubes2 = [[2, 1, 3], [1, 0, 1]] cubes3 = [[2, 1, 3], [1, 1, 1]] cubes4 = [[1, 2], [3, 4]] cubes5 = [[1, 2], [3, 0], [5, 6]] cubes6 = [[1, 2], [3, 0], [5, 6], [0, 8]] cubes7 = [[1, 2], [3, 4], [5, 6], [7, 9], [9, 9]] cubes8 = [[0, 0], [0, 0], [0, 0], [0, 1], [0, 0]] test_cases = [ (cubes1, 4), (cubes2, 2), (cubes3, 3), (cubes4, 7), (cubes5, 11), (cubes6, 8), (cubes7, 18), (cubes8, 1) ] for i, (cubes, expected) in enumerate(test_cases): result = solution(cubes) assert result == expected, f"Assert Error: Input {(cubes)}, Expected {expected}, Got: {result}" test()
from typing import List def solution(cubes: List[List[int]]) -> int: """ Count the red squares from a specified view of the stacked cubes. Parameters: cubes (List[List[int]]): A 2D list where cubes[i][j] represents the number of cubes stacked at row i, column j. Returns: int: The number of red squares from the given view. """
q31-3
from typing import List def solution(cubes: List[List[int]]) -> int: """ Count the red squares from a specified view of the stacked cubes. Parameters: cubes (List[List[int]]): A 2D list where cubes[i][j] represents the number of cubes stacked at row i, column j. Returns: int: The number of red squares from the given view. """ # for each row, find the first non-zero element in the first column first_none_zero_column = len(cubes[0]) for i in range(len(cubes)): for j in range(0, len(cubes[0])): if cubes[i][j] != 0: first_none_zero_column = min(first_none_zero_column, j) break red_squares = sum(cubes[i][first_none_zero_column] for i in range(len(cubes))) return red_squares
The image contains four examples, each demonstrating a 3D cube structure and its corresponding left view in a grid. The 2D grid represents rows and columns, with **red cubes** highlighted to indicate **Front Cubes**. Here’s a markdown-style breakdown of the examples.: ### **Example 1**: - **3D Cube Structure**: - The following is the matrix form of the structure, with numbers representing the number of blocks stacked there: [ [2,1,3], [1,0,1] ] - **Left View Representation**: - **Grid**: ``` [ [R,R,Y], [R,0,0] ] ``` ### **Example 2**: - **3D Cube Structure**: [ [2,1,1] [0,0,1] ] - **Left View Representation**: - **Grid**: ``` [ [R,R], [Y,0] ] ``` ### **Example 3**: - **3D Cube Structure**: [ [2,1,2], [1,0,1], [0,0,1] ] - **Left View Representation**: - **Grid**: ``` [ [R,R], [R,0], [Y,0] ] ``` ### **Example 4**: - **3D Cube Structure**: [ [0,1,1], [0,0,1], [0,0,1] ] - **Left View Representation**: - The 2D grid is a 3x3 representation of the L-shape structure, showing peak cubes highlighted in red. - **Grid**: ``` [ [R], [Y], [Y] ] ``` ### Key: - **R**: Red cube (Peak Cube). - **Y**: Yellow cube (non-peak, lower layer). - **0**: No cube exists at this position.
def test(): cubes1 = [[2, 1, 3], [1, 2, 1]] cubes2 = [[2, 1, 3], [1, 0, 1]] cubes3 = [[2, 1, 3], [1, 1, 1]] cubes4 = [[0, 2], [0, 4]] cubes5 = [[1, 2], [3, 0], [5, 6]] cubes6 = [[1, 2], [3, 0], [5, 6], [0, 8]] cubes7 = [[1, 2], [3, 4], [5, 6], [7, 9], [9, 9]] cubes8 = [[3, 1], [3], [2, 2], [1]] test_cases = [ (cubes1, 3), (cubes2, 3), (cubes3, 3), (cubes4, 6), (cubes5, 9), (cubes6, 9), (cubes7, 25), (cubes8, 9) ] for i, (cubes, expected) in enumerate(test_cases): result = solution(cubes) assert result == expected, f"Assert Error: Input {(cubes)}, Expected {expected}, Got: {result}" test()
from typing import List def solution(cubes: List[List[int]]) -> int: """ Count the red squares from a specified view of the stacked cubes. Parameters: cubes (List[List[int]]): A 2D list where cubes[i][j] represents the number of cubes stacked at row i, column j. Returns: int: The number of red squares from the given view. """
q32
def solution(n: int) -> int: """ Refer to the pattern in the figure, calculate the number of cells with the specified n. Args: n: integer in [1, 1000] Returns: int: The number of cells """ return n*(n+3)+1
The image shows three hexagonal grid patterns, each labeled with different values of **n** (n = 1, 2, 3), and the grids grow in size as **n** increases. These patterns represent a symmetric arrangement of hexagons, where the size and number of hexagons increase progressively with each value of **n**. ### **Grid Patterns**: 1. **n = 1**: - The layout forms a horizontal "hourglass" shape, with 1 hexagons in the center column, flanked by 2 hexagons on the left column and 2 hexagons on the right column. - The number of hexagons are 2+1+2 = 5 2. **n = 2**: - The grid expands symmetrically, forming a wider "hourglass" shape. - The previous three columns in the middle are the same, with 3 more hexagons in the left most column and 3 more hexagons in the right most column. - The number of hexagons are 3+5+3=11 3. **n = 3**: - The previous five columns in the middle are the same, with 4 more hexagons in the left most column and 4 more hexagons in the right most column. - The number of hexagons are 4+11+4=19
def test(): x = lambda x: x*(x+3)+1 test_cases = [ (1, x(1)), (2, x(2)), (3, x(3)), (8, x(8)), (10, x(10)), (20, x(20)), (21, x(21)), (50, x(50)), (100, x(100)), (1000, x(1000)) ] for input, expected in test_cases: result = solution(input) assert result == expected, f"Assert Error: input={input}, expected={expected}, result={result}" test()
def solution(n: int) -> int: """ Refer to the pattern in the figure, calculate the number of cells with the specified n. Args: n: integer in [1, 1000] Returns: int: The number of cells """
q32-2
def solution(n: int) -> int: """ Refer to the pattern in the figure, calculate the number of cells with the specified n. Args: n: integer in [1, 1000] Returns: int: The number of cells """ return n*(n+3)+1
The image shows three hexagonal grid patterns, each labeled with different values of **n** (n = 1, 2, 3), and the grids grow in size as **n** increases. These patterns represent a symmetric arrangement of hexagons, where the size and number of hexagons increase progressively with each value of **n**. ### **Grid Patterns**: 1. **n = 1**: - A small hexagonal grid pattern consisting of 5 hexagons arranged in a compact, symmetric shape. - The layout forms a "hourglass" shape, with 1 hexagons in the center row, flanked by 2 hexagons on the top row and 2 hexagons on the bottom row. - The number of hexagons are 2+1+2 = 5 2. **n = 2**: - A larger hexagonal grid pattern consisting of 11 hexagons. - The grid expands symmetrically, forming a wider "hourglass" shape. - The previous three rows in the middle are the same, with 3 more hexagons on the top row and 3 more hexagons on the bottom row. - The number of hexagons are 3+5+3=11 3. **n = 3**: - The grid grows further, consisting of 19 hexagons. - The previous five rows in the middle are the same, with 4 more hexagons on the top row and 4 more hexagons on the bottom row. - The number of hexagons are 4+11+4=19
def test(): x = lambda x: x*(x+3)+1 test_cases = [ (1, x(1)), (2, x(2)), (3, x(3)), (8, x(8)), (10, x(10)), (20, x(20)), (21, x(21)), (50, x(50)), (100, x(100)), (1000, x(1000)) ] for input, expected in test_cases: result = solution(input) assert result == expected, f"Assert Error: input={input}, expected={expected}, result={result}" test()
def solution(n: int) -> int: """ Refer to the pattern in the figure, calculate the number of cells with the specified n. Args: n: integer in [1, 1000] Returns: int: The number of cells """
q32-3
def solution(n: int) -> int: """ Refer to the pattern in the figure, calculate the number of cells with the specified n. Args: n: integer in [1, 1000] Returns: int: The number of cells """ return n*(n+3)+1
The image shows three hexagonal grid patterns, each labeled with a different **n** value (n = 1,2,3), with the size of the grid increasing as **n** increases. These patterns represent a symmetrical arrangement of hexagons, where the size and number of hexagons gradually increase with the value of each **n**. ### ** Grid Mode **: 1. **n = 1**: A small hexagonal grid pattern consisting of five compact symmetrical hexagons. - The layout forms a slightly slanted "hourglass" shape, with three rows of hexagons in the slanted row, one hexagon in the middle row, two hexons in the top row, and two hexons in the bottom row. - The number of hexagons are 2+1+2 = 5 2. **n = 2**: - A larger hexagonal grid pattern made up of 11 hexagons. - The grid expands symmetrically to form a wider, slightly slanted "hourglass" shape. There are five rows of hexagons slanted - The first three rows in the middle are the same, with 3 more hexes in the top row and 3 more hexes in the bottom row. - The number of hexagons are 3+5+3=11 3. **n = 3**: - The grid grows further and consists of 19 hexagons. There are seven rows of hexagons slanted - The first five rows in the middle are the same, with four more hexes in the top row and four more hexes in the bottom row. - The number of hexagons are 4+11+4=19
def test(): x = lambda x: x*(x+3)+1 test_cases = [ (1, x(1)), (2, x(2)), (3, x(3)), (8, x(8)), (10, x(10)), (20, x(20)), (21, x(21)), (50, x(50)), (100, x(100)), (1000, x(1000)) ] for input, expected in test_cases: result = solution(input) assert result == expected, f"Assert Error: input={input}, expected={expected}, result={result}" test()
def solution(n: int) -> int: """ Refer to the pattern in the figure, calculate the number of cells with the specified n. Args: n: integer in [1, 1000] Returns: int: The number of cells """
q33
from collections import deque class TreeNode: """ Represents a node in a tree. Each node contains an integer value and a list of child TreeNodes. Attributes: value (int): The integer value of the node. children (list): A list of child nodes (TreeNode objects). """ def __init__(self, value: int, children: list=[]): self.value = value self.children = children def solution(root: TreeNode) -> list[int]: """ Computes the output sequence based on the given tree structure. Parameters: root (TreeNode): The root node of the tree. Returns: list[int]: A list of integers representing the output sequence as illustrated in the figure. """ if not root: return [] queue = deque([root]) result = [] while queue: level_size = len(queue) for i in range(level_size): node = queue.popleft() if i == level_size - 1: result.append(node.value) for child in node.children: queue.append(child) return result
The image displays three examples of binary trees with nodes labeled with numbers. Nodes with parentheses are highlighted in orange in the image. ### **Example 1**: - **Tree Structure**: ``` (1) / \ 2 (3) / \ / \ 4 5 6 (7) \ (8) ``` - **Output**: ``` 1 3 7 8 ``` ### **Example 2**: - **Tree Structure**: ``` (1) / \ 2 (3) / \ \ 4 5 (6) \ (7) ``` - **Output**: ``` 1 3 6 7 ``` ### **Example 3**: - **Tree Structure**: ``` (1) / (2) / \ 3 (4) \ (5) ``` - **Output**: ``` 1 2 4 5 ``` Overall, the nodes that are highlighted in orange in the image seems to be the rightmost nodes in the tree. The output is the values of these nodes in the order they appear in the tree.
def test(): Tree0 = TreeNode(0) Tree1 = TreeNode(1, [TreeNode(1), TreeNode(2)]) Tree2 = TreeNode(3, [TreeNode(3)]) Tree3 = TreeNode(2, [TreeNode(2), TreeNode(2, [TreeNode(2)])]) Tree4 = TreeNode(2, [TreeNode(1, [TreeNode(2)]), TreeNode(2, [TreeNode(3)])]) Tree5 = TreeNode(5, [TreeNode(5, [TreeNode(5, [TreeNode(5)]), TreeNode(5)]), TreeNode(5, [TreeNode(5), TreeNode(5)])]) Tree6 = TreeNode(8, [TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)]), TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)])]) Tree7 = TreeNode(2, [TreeNode(2, [TreeNode(2, [TreeNode(1)]), TreeNode(2)]), TreeNode(2, [TreeNode(2), TreeNode(1, [TreeNode(2)])])]) Tree8 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3)]), TreeNode(3, [TreeNode(3), TreeNode(3, [TreeNode(3)])])]) Tree9 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(8, [TreeNode(3)])]), TreeNode(3, [TreeNode(8), TreeNode(8, [TreeNode(3)])])]) Tree10 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(1, [TreeNode(1)])]), TreeNode(3, [TreeNode(3, [TreeNode(1)]), TreeNode(3, [TreeNode(3)])])]) test_cases = [ (Tree0, [0]), (Tree1, [1, 2]), (Tree2, [3, 3]), (Tree3, [2, 2, 2]), (Tree4, [2, 2, 3]), (Tree5, [5, 5, 5, 5]), (Tree6, [8, 8, 8, 8]), (Tree7, [2, 2, 1, 2]), (Tree8, [3, 3, 3, 3]), (Tree9, [3, 3, 8, 3]), (Tree10, [3, 3, 3, 3]), ] for i, (root, expected) in enumerate(test_cases): result = solution(root) assert result == expected, f"Assert Error: Input Tree {i}, Expected {expected}, Got: {result}" test()
class TreeNode: """ Represents a node in a tree. Each node contains an integer value and a list of child TreeNodes. Attributes: value (int): The integer value of the node. children (list): A list of child nodes (TreeNode objects). """ def __init__(self, value: int, children: list=[]): self.value = value self.children = children def solution(root: TreeNode) -> list[int]: """ Computes the output sequence based on the given tree structure. Parameters: root (TreeNode): The root node of the tree. Returns: list[int]: A list of integers representing the output sequence as illustrated in the figure. """
q33-2
from collections import deque class TreeNode: """ Represents a node in a tree. Each node contains an integer value and a list of child TreeNodes. Attributes: value (int): The integer value of the node. children (list): A list of child nodes (TreeNode objects). """ def __init__(self, value: int, children: list=[]): self.value = value self.children = children def solution(root: TreeNode) -> list[int]: """ Computes the output sequence based on the given tree structure. Parameters: root (TreeNode): The root node of the tree. Returns: list[int]: A list of integers representing the output sequence as illustrated in the figure. """ if not root: return [] queue = deque([root]) result = [] while queue: level_size = len(queue) for i in range(level_size): node = queue.popleft() if i == 0: result.append(node.value) for child in node.children: queue.append(child) return result
The image displays three examples of binary trees with nodes labeled with numbers. Nodes with parentheses are highlighted in orange in the image. ### **Example 1**: - **Tree Structure**: ``` (1) / \ (2) 3 / \ / \ (4) 5 6 7 \ (8) ``` - **Output**: ``` 1 2 4 8 ``` ### **Example 2**: - **Tree Structure**: ``` (1) / \ (2) 3 / \ \ (4) 5 6 \ (7) ``` - **Output**: ``` 1 2 4 7 ``` ### **Example 3**: - **Tree Structure**: ``` (1) / (2) / \ (3) 4 \ (5) ``` - **Output**: ``` 1 2 3 5 ``` Overall, the nodes that are highlighted in orange in the image seems to be the leftmost nodes in the tree. The output is the values of these nodes in the order they appear in the tree.
def test(): Tree0 = TreeNode(0) Tree1 = TreeNode(1, [TreeNode(1), TreeNode(2)]) Tree2 = TreeNode(3, [TreeNode(3)]) Tree3 = TreeNode(2, [TreeNode(2), TreeNode(2, [TreeNode(2)])]) Tree4 = TreeNode(2, [TreeNode(1, [TreeNode(2)]), TreeNode(2, [TreeNode(3)])]) Tree5 = TreeNode(5, [TreeNode(5, [TreeNode(5, [TreeNode(5)]), TreeNode(5)]), TreeNode(5, [TreeNode(5), TreeNode(5)])]) Tree6 = TreeNode(8, [TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)]), TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)])]) Tree7 = TreeNode(2, [TreeNode(2, [TreeNode(2, [TreeNode(1)]), TreeNode(2)]), TreeNode(2, [TreeNode(2), TreeNode(1, [TreeNode(2)])])]) Tree8 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3)]), TreeNode(3, [TreeNode(3), TreeNode(3, [TreeNode(3)])])]) Tree9 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(8, [TreeNode(3)])]), TreeNode(3, [TreeNode(8), TreeNode(8, [TreeNode(3)])])]) Tree10 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(1, [TreeNode(1)])]), TreeNode(3, [TreeNode(3, [TreeNode(1)]), TreeNode(3, [TreeNode(3)])])]) test_cases = [ (Tree0, [0]), (Tree1, [1, 1]), (Tree2, [3, 3]), (Tree3, [2, 2, 2]), (Tree4, [2, 1, 2]), (Tree5, [5, 5, 5, 5]), (Tree6, [8, 8, 8, 8]), (Tree7, [2, 2, 2, 1]), (Tree8, [3, 3, 3, 3]), (Tree9, [3, 3, 3, 3]), (Tree10, [3, 3, 3, 3]), ] for i, (root, expected) in enumerate(test_cases): result = solution(root) assert result == expected, f"Assert Error: Input Tree {i}, Expected {expected}, Got: {result}" test()
class TreeNode: """ Represents a node in a tree. Each node contains an integer value and a list of child TreeNodes. Attributes: value (int): The integer value of the node. children (list): A list of child nodes (TreeNode objects). """ def __init__(self, value: int, children: list=[]): self.value = value self.children = children def solution(root: TreeNode) -> list[int]: """ Computes the output sequence based on the given tree structure. Parameters: root (TreeNode): The root node of the tree. Returns: list[int]: A list of integers representing the output sequence as illustrated in the figure. """
q33-3
class TreeNode: """ Represents a node in a tree. Each node contains an integer value and a list of child TreeNodes. Attributes: value (int): The integer value of the node. children (list): A list of child nodes (TreeNode objects). """ def __init__(self, value: int, children: list=[]): self.value = value self.children = children def solution(root: TreeNode) -> list[int]: """ Computes the output sequence based on the given tree structure. Parameters: root (TreeNode): The root node of the tree. Returns: list[int]: A list of integers representing the output sequence as illustrated in the figure. """ def dfs(node: TreeNode) -> list[int]: # Base case: if the node has no children, it's a leaf node if not node.children: return [node.value] # Recursively visit all children and collect their leaf nodes leaves = [] for child in node.children: leaves.extend(dfs(child)) # Collect leaf nodes from all children return leaves if not root: return [] return dfs(root)
The image displays three examples of binary trees with nodes labeled with numbers. Nodes with parentheses are highlighted in orange in the image. ### **Example 1**: - **Tree Structure**: ``` 1 / \ 2 3 / \ / \ (4)(5) 6 (7) \ (8) ``` - **Output**: ``` 4 5 8 7 ``` ### **Example 2**: - **Tree Structure**: ``` 1 / \ 2 3 / \ \ 4 (5) (6) \ (7) ``` - **Output**: ``` 7 5 6 ``` ### **Example 3**: - **Tree Structure**: ``` 1 / 2 / \ (3) 4 \ (5) ``` - **Output**: ``` 3 5 ``` Overall, the nodes that are highlighted in orange in the image seems to be the leftmost nodes in the tree. The output is the values of these nodes in the order they appear in the tree.
def test(): Tree0 = TreeNode(0) Tree1 = TreeNode(1, [TreeNode(1), TreeNode(2)]) Tree2 = TreeNode(3, [TreeNode(3)]) Tree3 = TreeNode(2, [TreeNode(2), TreeNode(2, [TreeNode(2)])]) Tree4 = TreeNode(2, [TreeNode(1, [TreeNode(2)]), TreeNode(2, [TreeNode(3)])]) Tree5 = TreeNode(5, [TreeNode(5, [TreeNode(5, [TreeNode(5)]), TreeNode(5)]), TreeNode(5, [TreeNode(5), TreeNode(5)])]) Tree6 = TreeNode(8, [TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)]), TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)])]) Tree7 = TreeNode(2, [TreeNode(2, [TreeNode(2, [TreeNode(1)]), TreeNode(2)]), TreeNode(2, [TreeNode(2), TreeNode(1, [TreeNode(2)])])]) Tree8 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3)]), TreeNode(3, [TreeNode(3), TreeNode(3, [TreeNode(3)])])]) Tree9 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(8, [TreeNode(3)])]), TreeNode(3, [TreeNode(6), TreeNode(8, [TreeNode(3)])])]) Tree10 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(1, [TreeNode(1)])]), TreeNode(3, [TreeNode(3, [TreeNode(1)]), TreeNode(3, [TreeNode(3)])])]) test_cases = [ (Tree0, [0]), (Tree1, [1, 2]), (Tree2, [3]), (Tree3, [2, 2]), (Tree4, [2, 3]), (Tree5, [5, 5, 5, 5]), (Tree6, [8, 8, 8, 8]), (Tree7, [1, 2, 2, 2]), (Tree8, [3, 3, 3, 3]), (Tree9, [3, 3, 6, 3]), (Tree10, [3, 1, 1, 3]), ] for i, (root, expected) in enumerate(test_cases): result = solution(root) assert result == expected, f"Assert Error: Input Tree {i}, Expected {expected}, Got: {result}" test()
class TreeNode: """ Represents a node in a tree. Each node contains an integer value and a list of child TreeNodes. Attributes: value (int): The integer value of the node. children (list): A list of child nodes (TreeNode objects). """ def __init__(self, value: int, children: list=[]): self.value = value self.children = children def solution(root: TreeNode) -> list[int]: """ Computes the output sequence based on the given tree structure. Parameters: root (TreeNode): The root node of the tree. Returns: list[int]: A list of integers representing the output sequence as illustrated in the figure. """
q34
def solution(input_matrix: list[list[str]]) -> int: """ Count the number of edges dirived from the given matrix. Args: input_matrix (list[list[str]]): A 2D list where input_matrix[i][j] represents a character at row i, column j. Returns: int: The number of edges in the given matrix. """ rows = len(input_matrix) cols = len(input_matrix[0]) edges = 0 for i in range(rows): for j in range(cols - 1): if input_matrix[i][j] == input_matrix[i][j + 1]: edges += 1 for i in range(rows - 1): for j in range(cols): if input_matrix[i][j] == input_matrix[i + 1][j]: edges += 1 return edges
The image shows two grids, each filled with letters (A, B, C, and D), and demonstrates how the number of edges (connections between the same letters) is calculated for each grid. On the right side of each grid, connections are drawn between adjacent cells that contain the same letter, and the total number of edges is noted.
def test(): test_cases = [ { 'matrix': [ ['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I'] ], "expected": 0 }, { 'matrix': [ ['A', 'A', 'A'], ['A', 'A', 'A'], ['A', 'A', 'A'] ], 'expected': 12 }, { 'matrix': [ ['A', 'A', 'C', 'D'], ['A', 'A', 'C', 'D'], ['D', 'B', 'C', 'D'], ['D', 'B', 'C', 'C'] ], 'expected': 12 }, { 'matrix': [ ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['D', 'B', 'C', 'D'], ['D', 'B', 'C', 'D'] ], 'expected': 11 }, { 'matrix': [ ['A', 'B', 'B', 'D'], ['A', 'B', 'B', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'] ], 'expected': 13 }, { 'matrix': [ ['A', 'B', 'B', 'D'], ['A', 'B', 'B', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'] ], 'expected': 18 }, { 'matrix': [ ['D', 'A', 'B', 'C', 'D'], ['A', 'A', 'B', 'C', 'D'], ['D', 'C', 'C', 'C', 'D'], ['D', 'C', 'C', 'A', 'D'], ['D', 'C', 'C', 'A', 'D'] ], 'expected': 20 }, { 'matrix': [ ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['D', 'D', 'C', 'D', 'E'], ['D', 'C', 'C', 'C', 'E'], ['D', 'B', 'C', 'E', 'E'] ], 'expected': 18 } ] for test_case in test_cases: result = solution(test_case['matrix']) assert result == test_case['expected'], f'Assert Error: matrix {test_case["matrix"]} expected {test_case["expected"]}, but got {result}' test()
def solution(input_matrix: list[list[str]]) -> int: """ Count the number of edges. Args: input_matrix (list[list[str]]). Returns: int: The number of edges in the given matrix. """
q34-2
def solution(input_matrix: list[list[str]]) -> int: """ Count the number of edges dirived from the given matrix. Args: input_matrix (list[list[str]]): A 2D list where input_matrix[i][j] represents a character at row i, column j. Returns: int: The number of edges in the given matrix. """ rows = len(input_matrix) cols = len(input_matrix[0]) edges = 0 for i in range(rows - 1): for j in range(cols): if input_matrix[i][j] == input_matrix[i + 1][j]: edges += 1 return edges
The image shows two grids filled with letters (A, B, C, and D) and demonstrates how vertical edges (connections between vertically adjacent identical letters) are calculated. The edges are shown in red, connecting vertically adjacent cells with the same letter. Each grid has a calculated number of edges.
def test(): test_cases = [ { 'matrix': [ ['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I'] ], "expected": 0 }, { 'matrix': [ ['A', 'A', 'A'], ['A', 'A', 'A'], ['A', 'A', 'A'] ], 'expected': 6 }, { 'matrix': [ ['A', 'A', 'C', 'D'], ['A', 'A', 'C', 'D'], ['D', 'B', 'C', 'D'], ['D', 'B', 'C', 'C'] ], 'expected': 9 }, { 'matrix': [ ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['D', 'B', 'C', 'D'], ['D', 'B', 'C', 'D'] ], 'expected': 11 }, { 'matrix': [ ['A', 'B', 'B', 'D'], ['A', 'B', 'B', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'] ], 'expected': 9 }, { 'matrix': [ ['A', 'B', 'B', 'D'], ['A', 'B', 'B', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'] ], 'expected': 13 }, { 'matrix': [ ['D', 'A', 'B', 'C', 'D'], ['A', 'A', 'B', 'C', 'D'], ['D', 'C', 'C', 'C', 'D'], ['D', 'C', 'C', 'A', 'D'], ['D', 'C', 'C', 'A', 'D'] ], 'expected': 15 }, { 'matrix': [ ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['D', 'D', 'C', 'D', 'E'], ['D', 'C', 'C', 'C', 'E'], ['D', 'B', 'C', 'E', 'E'] ], 'expected': 14 } ] for test_case in test_cases: result = solution(test_case['matrix']) assert result == test_case['expected'], f'Assert Error: matrix {test_case["matrix"]} expected {test_case["expected"]}, but got {result}' test()
def solution(input_matrix: list[list[str]]) -> int: """ Count the number of edges dirived from the given matrix. Args: input_matrix (list[list[str]]): A 2D list where input_matrix[i][j] represents a character at row i, column j. Returns: int: The number of edges in the given matrix. """
q34-3
def solution(input_matrix: list[list[str]]) -> int: """ Count the number of edges dirived from the given matrix. Args: input_matrix (list[list[str]]): A 2D list where input_matrix[i][j] represents a character at row i, column j. Returns: int: The number of edges in the given matrix. """ rows = len(input_matrix) cols = len(input_matrix[0]) edges = 0 for i in range(rows): for j in range(cols - 1): if input_matrix[i][j] == input_matrix[i][j + 1]: edges += 1 return edges
The image shows two grids filled with letters (A, B, C, and D) and demonstrates how horizontal edges (connections between horizontally adjacent identical letters) are calculated. The edges are shown in red, connecting horizontally adjacent cells with the same letter. Each grid has a calculated number of edges.
def test(): test_cases = [ { 'matrix': [ ['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I'] ], "expected": 0 }, { 'matrix': [ ['A', 'A', 'A'], ['A', 'A', 'A'], ['A', 'A', 'A'] ], 'expected': 6 }, { 'matrix': [ ['A', 'A', 'C', 'D'], ['A', 'A', 'C', 'D'], ['D', 'B', 'C', 'D'], ['D', 'B', 'C', 'C'] ], 'expected': 3 }, { 'matrix': [ ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['D', 'B', 'C', 'D'], ['D', 'B', 'C', 'D'] ], 'expected': 0 }, { 'matrix': [ ['A', 'B', 'B', 'D'], ['A', 'B', 'B', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'] ], 'expected': 4 }, { 'matrix': [ ['A', 'B', 'B', 'D'], ['A', 'B', 'B', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'] ], 'expected': 5 }, { 'matrix': [ ['D', 'A', 'B', 'C', 'D'], ['A', 'A', 'B', 'C', 'D'], ['D', 'C', 'C', 'C', 'D'], ['D', 'C', 'C', 'A', 'D'], ['D', 'C', 'C', 'A', 'D'] ], 'expected': 5 }, { 'matrix': [ ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['D', 'D', 'C', 'D', 'E'], ['D', 'C', 'C', 'C', 'E'], ['D', 'B', 'C', 'E', 'E'] ], 'expected': 4 } ] for test_case in test_cases: result = solution(test_case['matrix']) assert result == test_case['expected'], f'Assert Error: matrix {test_case["matrix"]} expected {test_case["expected"]}, but got {result}' test()
def solution(input_matrix: list[list[str]]) -> int: """ Count the number of edges dirived from the given matrix. Args: input_matrix (list[list[str]]): A 2D list where input_matrix[i][j] represents a character at row i, column j. Returns: int: The number of edges in the given matrix. """
q35
import numpy as np def solution(input_matrix: np.ndarray) -> np.ndarray: """ Transform the given N*3 matrix as illustrated in the figure. Args: input_matrix: A 2D list where input_matrix[i][j] contains an integer. (i is in range [0, N-1], N % 2 == 0; j is in range [0, 2]) Returns: A 2D list containing the transformed N*3 matrix. """ n = input_matrix.shape[0] even_rows = input_matrix[0:n:2, :] odd_rows = input_matrix[1:n:2, :] result_matrix = np.vstack((even_rows, odd_rows)) return result_matrix
### Description of the transformations: 1. **First Example**: - **Original Matrix**: ``` [[ 0, 1, 2 ], [ 3, 4, 5 ]] ``` - **After Transformation**: Since the first row is odd-numbered and the second is even-numbered, the matrix remains the same: ``` [[ 0, 1, 2 ], [ 3, 4, 5 ]] ``` 2. **Second Example**: - **Original Matrix**: ``` [[ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ], [ 9, 10, 11 ]] ``` - **After Transformation**: The odd-numbered rows (1st and 3rd) are moved to the front: ``` [[ 0, 1, 2 ], [ 6, 7, 8 ], [ 3, 4, 5 ], [ 9, 10, 11 ]] ``` 3. **Third Example**: - **Original Matrix**: ``` [[ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ], [ 9, 10, 11 ], [ 12, 13, 14 ], [ 15, 16, 17 ]] ``` - **After Transformation**: The odd-numbered rows (1st, 3rd, 5th) are moved to the front: ``` [[ 0, 1, 2 ], [ 6, 7, 8 ], [ 12, 13, 14 ], [ 3, 4, 5 ], [ 9, 10, 11 ], [ 15, 16, 17 ]] ```
import numpy as np def test(): test_cases = [ ([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], [[1, 2, 3], [7, 8, 9], [4, 5, 6], [10, 11, 12]] ), ([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]], [[1, 2, 3], [7, 8, 9], [13, 14, 15], [4, 5, 6], [10, 11, 12], [16, 17, 18]] ), ([[10, 11, 12], [7, 8, 9], [4, 5, 6], [1, 2, 3]], [[10, 11, 12], [4, 5, 6], [7, 8, 9], [1, 2, 3]]), ([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9], [10, 10, 10], [11, 11, 11], [12, 12, 12]], [[1, 1, 1], [3, 3, 3], [5, 5, 5], [7, 7, 7], [9, 9, 9], [11, 11, 11], [2, 2, 2], [4, 4, 4], [6, 6, 6], [8, 8, 8], [10, 10, 10], [12, 12, 12]] ), ([[2, 4, 6], [1, 3, 5]], [[2, 4, 6], [1, 3, 5]]) ] for test_case in test_cases: input_matrix, expected = test_case result = solution(np.array(input_matrix)) expected = np.array(expected) assert np.array_equal(result, expected), f'Assert Error: input_matrix {input_matrix} expected {expected}, but got {result}' test()
import numpy as np def solution(input_matrix: np.ndarray) -> np.ndarray: """ Transform the given N*3 matrix as illustrated in the figure. Args: input_matrix: A 2D list where input_matrix[i][j] contains an integer. (i is in range [0, N-1], N % 2 == 0; j is in range [0, 2]) Returns: A 2D list containing the transformed N*3 matrix. """
q35-2
import numpy as np def solution(input_matrix: np.ndarray) -> np.ndarray: """ Transform the given N*3 matrix as illustrated in the figure. Args: input_matrix: A 2D list where input_matrix[i][j] contains an integer. (i is in range [0, N-1], N % 2 == 0; j is in range [0, 2]) Returns: A 2D list containing the transformed N*3 matrix. """ n = input_matrix.shape[0] odd_rows = input_matrix[1:n:2, :] even_rows = input_matrix[0:n:2, :] result_matrix = np.vstack((odd_rows, even_rows)) return result_matrix
The image shows three sets of matrices with transformations based on the specific rule. #### **First Example**: - **Original Matrix**: ``` [[ 0, 1, 2 ], [ 3, 4, 5 ]] ``` - Row 0 (even) contains [0, 1, 2] - Row 1 (odd) contains [3, 4, 5] - **Transformed Matrix**: ``` [[ 3, 4, 5 ], [ 0, 1, 2 ]] ``` - Row 1 (even) is moved before Row 0 (odd). #### **Second Example**: - **Original Matrix**: ``` [[ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ], [ 9, 10, 11 ]] ``` - Row 0 (even) contains [0, 1, 2] - Row 1 (odd) contains [3, 4, 5] - Row 2 (even) contains [6, 7, 8] - Row 3 (odd) contains [9, 10, 11] - **Transformed Matrix**: ``` [[ 3, 4, 5 ], [ 9, 10, 11 ], [ 0, 1, 2 ], [ 6, 7, 8 ]] ``` - Even-numbered rows (Row 1 and Row 3) are moved before odd-numbered rows (Row 0 and Row 2). #### **Third Example**: - **Original Matrix**: ``` [[ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ], [ 9, 10, 11 ], [ 12, 13, 14 ], [ 15, 16, 17 ]] ``` - Rows 0, 2, and 4 are even-numbered. - Rows 1, 3, and 5 are odd-numbered. - **Transformed Matrix**: ``` [[ 3, 4, 5 ], [ 9, 10, 11 ], [ 15, 16, 17 ], [ 0, 1, 2 ], [ 6, 7, 8 ], [ 12, 13, 14 ]] ``` - The even-numbered rows (Rows 1, 3, and 5) are placed before the odd-numbered rows (Rows 0, 2, and 4).
import numpy as np def test(): test_cases = [ ([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], [[4, 5, 6], [10, 11, 12], [1, 2, 3], [7, 8, 9]] ), ([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]], [[4, 5, 6], [10, 11, 12], [16, 17, 18], [1, 2, 3], [7, 8, 9], [13, 14, 15]] ), ([[10, 11, 12], [7, 8, 9], [4, 5, 6], [1, 2, 3]], [[7, 8, 9], [1, 2, 3], [10, 11, 12], [4, 5, 6]]), ([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9], [10, 10, 10], [11, 11, 11], [12, 12, 12]], [[2, 2, 2], [4, 4, 4], [6, 6, 6], [8, 8, 8], [10, 10, 10], [12, 12, 12], [1, 1, 1], [3, 3, 3], [5, 5, 5], [7, 7, 7], [9, 9, 9], [11, 11, 11]] ), ([[2, 4, 6], [1, 3, 5]], [[1, 3, 5], [2, 4, 6]]) ] for test_case in test_cases: input_matrix, expected = test_case result = solution(np.array(input_matrix)) expected = np.array(expected) assert np.array_equal(result, expected), f'Assert Error: input_matrix {input_matrix} expected {expected}, but got {result}' test()
import numpy as np def solution(input_matrix: np.ndarray) -> np.ndarray: """ Transform the given N*3 matrix as illustrated in the figure. Args: input_matrix: A 2D list where input_matrix[i][j] contains an integer. (i is in range [0, N-1], N % 2 == 0; j is in range [0, 2]) Returns: A 2D list containing the transformed N*3 matrix. """
q35-3
import numpy as np def solution(input_matrix: np.ndarray) -> np.ndarray: """ Transform the given N*4 matrix as illustrated in the figure. Args: input_matrix: A 2D list where input_matrix[i][j] contains an integer. (i is in range [0, N-1], N % 2 == 0; j is in range [0, 3]) Returns: A 2D list containing the transformed N*4 matrix. """ n = input_matrix.shape[0] even_rows = input_matrix[0:n:2, :] odd_rows = input_matrix[1:n:2, :] result_matrix = np.vstack((even_rows, odd_rows)) return result_matrix
The image illustrates a matrix transformation where the rows are rearranged according to the following rule: **even-numbered rows are placed before odd-numbered rows** after the transformation. Here is the explanation for each transformation step: ### **Transformation Rule**: - Rows are initially ordered sequentially. - After transformation, even-numbered rows (0, 2, 4, etc.) appear before odd-numbered rows (1, 3, 5, etc.). ### **Example 1**: - **Original Matrix**: ``` [[ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ]] ``` - Row 0 (even) contains [0, 1, 2, 3]. - Row 1 (odd) contains [4, 5, 6, 7]. - **Transformed Matrix**: Since Row 0 is already on top (even), no change is needed: ``` [[ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ]] ``` ### **Example 2**: - **Original Matrix**: ``` [[ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8, 9, 10, 11 ], [ 12, 13, 14, 15 ]] ``` - Rows 0 and 2 are even, while rows 1 and 3 are odd. - **Transformed Matrix**: Even-numbered rows (Row 0 and Row 2) are placed before odd-numbered rows (Row 1 and Row 3): ``` [[ 0, 1, 2, 3 ], [ 8, 9, 10, 11 ], [ 4, 5, 6, 7 ], [ 12, 13, 14, 15 ]] ``` ### **Example 3**: - **Original Matrix**: ``` [[ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8, 9, 10, 11 ], [ 12, 13, 14, 15 ], [ 16, 17, 18, 19 ], [ 20, 21, 22, 23 ]] ``` - Rows 0, 2, 4 are even, while rows 1, 3, 5 are odd. - **Transformed Matrix**: Even-numbered rows (Row 0, Row 2, Row 4) are placed before odd-numbered rows (Row 1, Row 3, Row 5): ``` [[ 0, 1, 2, 3 ], [ 8, 9, 10, 11 ], [ 16, 17, 18, 19 ], [ 4, 5, 6, 7 ], [ 12, 13, 14, 15 ], [ 20, 21, 22, 23 ]] ```
import numpy as np def test(): test_cases = [ ([[1, 2, 3, 4], [6, 7, 8, 9]], [[1, 2, 3, 4], [6, 7, 8, 9]]), ([[1, 2, 3, 4], [6, 7, 8, 9], [11, 12, 13, 14], [16, 17, 18, 19]], [[1, 2, 3, 4], [11, 12, 13, 14], [6, 7, 8, 9], [16, 17, 18, 19]] ), ([[1, 2, 3, 4], [6, 7, 8, 9], [11, 12, 13, 14], [16, 17, 18, 19], [21, 22, 23, 24], [26, 27, 28, 29]], [[1, 2, 3, 4], [11, 12, 13, 14], [21, 22, 23, 24], [6, 7, 8, 9], [16, 17, 18, 19], [26, 27, 28, 29]] ), ([[1, 2, 3, 4], [6, 7, 8, 9], [11, 12, 13, 14], [16, 17, 18, 19], [21, 22, 23, 24]], [[1, 2, 3, 4], [11, 12, 13, 14], [21, 22, 23, 24], [6, 7, 8, 9], [16, 17, 18, 19]] ), ([[2, 4, 6, 8], [1, 3, 5, 7]], [[2, 4, 6, 8], [1, 3, 5, 7]]) ] for test_case in test_cases: input_matrix, expected = test_case result = solution(np.array(input_matrix)) expected = np.array(expected) assert np.array_equal(result, expected), f'Assert Error: input_matrix {input_matrix} expected {expected}, but got {result}' test()
import numpy as np def solution(input_matrix: np.ndarray) -> np.ndarray: """ Transform the given N*4 matrix as illustrated in the figure. Args: input_matrix: A 2D list where input_matrix[i][j] contains an integer. (i is in range [0, N-1], N % 2 == 0; j is in range [0, 3]) Returns: A 2D list containing the transformed N*4 matrix. """
q36
from typing import List def solution(numbers: List[int]) -> int: """ Given a sequence of numbers, determine the number of red segments that would be illuminated. Parameters: numbers (List[int]): A list of integers Returns: int: The total number of segments that will turn red based on the combination of the input numbers. """ segment_map = { 0: 0b0111111, 1: 0b0000110, 2: 0b1011011, 3: 0b1001111, 4: 0b1100110, 5: 0b1101101, 6: 0b1111101, 7: 0b0000111, 8: 0b1111111, 9: 0b1101111 } if not numbers: return 0 result = 0b1111111 for number in numbers: result &= segment_map[number] red_blocks = bin(result).count('1') return red_blocks
The image demonstrates the logical **AND** operation between segments of seven-segment displays, and in each result, certain segments are **highlighted in red** to indicate the active segments common to both input digits. Here’s a detailed description of each example with the highlighted segments: ### **First Example**: - **Operation**: **0 & 1** - **Result**: Digit **1**, where only the two right segments are **red**. ### **Second Example**: - **Operation**: **5 & 3** - **Result**: The top, middle, right-bottom vertical and bottom horizontal segments are highlited in **red**. ### **Third Example**: - **Operation**: **2 & 6 & 4** - **Result**: Only middle horizontal segment is **red** ### **Fourth Example**: - **Operation**: **7 & 8 & 9** - **Result**: Digit **7** in **red**.
def test(): test_cases = [ ([0, 1], 2), ([3, 5], 4), ([5, 3], 4), ([2, 3], 4), ([4, 5], 3), ([6, 7], 2), ([8, 9], 6), ([2, 6, 4], 1), ([7, 8, 9], 3), ([1, 2, 3, 4], 1), ([5, 6, 7, 8], 2), ([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 0) ] for i, (numbers, expected) in enumerate(test_cases): result = solution(numbers) assert result == expected, f"Assert Error: Input {numbers}, Expected {expected}, Got: {result}" test()
from typing import List def solution(numbers: List[int]) -> int: """ Given a sequence of numbers, determine the number of red segments that would be illuminated. Parameters: numbers (List[int]): A list of integers Returns: int: The total number of segments that will turn red based on the combination of the input numbers. """
q36-2
from typing import List def solution(numbers: List[int]) -> int: """ Given a sequence of numbers, determine the number of red segments that would be illuminated. Parameters: numbers (List[int]): A list of integers Returns: int: The total number of segments that will turn red based on the combination of the input numbers. """ segment_map = { 0: 0b0111111, 1: 0b0000110, 2: 0b1011011, 3: 0b1001111, 4: 0b1100110, 5: 0b1101101, 6: 0b1111101, 7: 0b0000111, 8: 0b1111111, 9: 0b1101111 } if not numbers: return 0 result = 0b0000000 for number in numbers: result |= segment_map[number] red_blocks = bin(result).count('1') return red_blocks
The image demonstrates the logical **OR** operation between segments of seven-segment displays, and in each result, certain segments are **highlighted in red**. Here’s a detailed description of each example with the highlighted segments: ### **First Example**: - **Operation**: **0 OR 1** - **Result**: Digit **0**. ### **Second Example**: - **Operation**: **5 OR 3** - **Result**: Digit **9**. ### **Third Example**: - **Operation**: **2 OR 6 OR 4** - **Result**: Digit **8**. ### **Fourth Example**: - **Operation**: **1 OR 4 OR 9** - **Result**: Digit **9**.
def test(): test_cases = [ ([0, 1], 6), ([3, 5], 6), ([5, 3], 6), ([2, 3], 6), ([4, 5], 6), ([6, 7], 7), ([8, 9], 7), ([2, 6, 4], 7), ([7, 8, 9], 7), ([1, 2, 3, 4], 7), ([5, 6, 7, 8], 7), ([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 7), ([1, 3], 5), ([1, 4], 4), ] for i, (numbers, expected) in enumerate(test_cases): result = solution(numbers) assert result == expected, f"Assert Error: Input {numbers}, Expected {expected}, Got: {result}" test()
from typing import List def solution(numbers: List[int]) -> int: """ Given a sequence of numbers, determine the number of red segments that would be illuminated. Parameters: numbers (List[int]): A list of integers Returns: int: The total number of segments that will turn red based on the combination of the input numbers. """
q36-3
from typing import List def solution(numbers: List[int]) -> int: """ Given a sequence of numbers, determine the number of red segments that would be illuminated. Parameters: numbers (List[int]): A list of integers Returns: int: The total number of segments that will turn red based on the combination of the input numbers. """ segment_map = { 0: 0b0111111, 1: 0b0000110, 2: 0b1011011, 3: 0b1001111, 4: 0b1100110, 5: 0b1101101, 6: 0b1111101, 7: 0b0000111, 8: 0b1111111, 9: 0b1101111 } if not numbers: return 0 result = 0b0000000 for number in numbers: result ^= segment_map[number] red_blocks = bin(result).count('1') return red_blocks
The image demonstrates the logical **XOR** operation between segments of seven-segment displays, and in each result, certain segments are **highlighted in red**. Here’s a detailed description of each example with the highlighted segments: ### **First Example**: - **Operation**: **0 XOR 1** - **Result**: The top segment, left-side vertical two segments and the bottom segments are highlighted in red. ### **Second Example**: - **Operation**: **5 XOR 3** - **Result**: The upper left and upper right vertical segments are highlighted in red. ### **Third Example**: - **Operation**: **2 XOR 6 XOR 4** - **Result**: Only middle horizontal segment is highlited. ### **Fourth Example**: - **Operation**: **1 XOR 4 XOR 9** - **Result**: The top segment, right-side vertical two segments and the bottom segments are highlighted in red.
def test(): test_cases = [ ([0, 1], 4), ([3, 5], 2), ([5, 3], 2), ([2, 3], 2), ([4, 5], 3), ([6, 7], 5), ([8, 9], 1), ([2, 6, 4], 1), ([1, 4, 9], 4), ([7, 8, 9], 4), ([1, 2, 3, 4], 4), ([5, 6, 7, 8], 3), ([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 3) ] for i, (numbers, expected) in enumerate(test_cases): result = solution(numbers) assert result == expected, f"Assert Error: Input {numbers}, Expected {expected}, Got: {result}" test()
from typing import List def solution(numbers: List[int]) -> int: """ Given a sequence of numbers, determine the number of red segments that would be illuminated. Parameters: numbers (List[int]): A list of integers Returns: int: The total number of segments that will turn red based on the combination of the input numbers. """
q37
from math import atan2 def solution(points: list[tuple[int, int]], point_a_index: int, point_b_index: int) -> bool: """ Given a list of points and the index of two points, determine whether the two points should be connected to form the shape in the figure. Args: points (list[tuple[int, int]]): An list of tuples, where each tuple consists of two integers representing the x and y coordinates of a point. The points are not guaranteed to be in any particular order. point_a_index (int): The 0-based index of the first point. point_b_index (int): The 0-based index of the second point. Returns: bool: True if the two points should be connected, False otherwise. """ centroid_x = sum((x for x, y in points)) / len(points) centroid_y = sum((y for x, y in points)) / len(points) def polar_angle(point): x, y = point return atan2(y - centroid_y, x - centroid_x) sorted_points = sorted(range(len(points)), key=lambda i: polar_angle(points[i])) pos_a = sorted_points.index(point_a_index) pos_b = sorted_points.index(point_b_index) return (pos_a - pos_b) % len(points) == 2 or (pos_b - pos_a) % len(points) == 2
The five-pointed star in the image is formed by connecting **non-adjacent** or **alternating points**. Specifically, instead of connecting neighboring points in sequence, the points are connected by skipping one point in between, creating the signature intersecting lines of the star shape. ### Description for each star: - **Example 1**: - The points are positioned at (3,2), (4,7), (5,2), (2,5), and (6,5). - **Example 2**: - The points are positioned at (2, 4), (2, 5), (5, 2), (5, 6), (6, 5). - **Example 3**: - The points are at (1,1), (2,5), (6, 5), (5,6), and (6, 1). - **Example 4**: - The points are at (1,1), (3, 0), (8, 2), (3, 8), and (5, 6). In all of these examples, the five points are connected by **skipping one point** in the **circular** sequence, meaning each point is connected to the next non-adjacent point, which forms the five intersecting lines that create the **five-pointed star**.
def test(): test_cases = [ ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 2, 4, True), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 2, 3, False), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 0, 4, True), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 0, 2, False), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 1, 3, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 0, 4, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 0, 1, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 1, 3, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 2, 4, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 2, 3, True), ] for input_points, point_a_index, point_b_index, expected in test_cases: result = solution(input_points, point_a_index, point_b_index) assert result == expected, f"Assert Error: input {input_points} point_a_index: {point_a_index} point_b_index: {point_b_index} Expected {expected}, but got {result}" test()
def solution(points: list[tuple[int, int]], point_a_index: int, point_b_index: int) -> bool: """ Given a list of points and the index of two points, determine whether the two points should be connected to form the shape in the figure. Args: points (list[tuple[int, int]]): An list of tuples, where each tuple consists of two integers representing the x and y coordinates of a point. The points are not guaranteed to be in any particular order. point_a_index (int): The 0-based index of the first point. point_b_index (int): The 0-based index of the second point. Returns: bool: True if the two points should be connected, False otherwise. """
q37-2
from math import atan2 def solution(points: list[tuple[int, int]], point_a_index: int, point_b_index: int) -> bool: """ Given a list of points and the index of two points, determine whether the two points should be connected to form the shape in the figure. Args: points (list[tuple[int, int]]): An list of tuples, where each tuple consists of two integers representing the x and y coordinates of a point. The points are not guaranteed to be in any particular order. point_a_index (int): The 0-based index of the first point. point_b_index (int): The 0-based index of the second point. Returns: bool: True if the two points should be connected, False otherwise. """ centroid_x = sum((x for x, y in points)) / len(points) centroid_y = sum((y for x, y in points)) / len(points) def polar_angle(point): x, y = point return atan2(y - centroid_y, x - centroid_x) sorted_points = sorted(range(len(points)), key=lambda i: polar_angle(points[i])) pos_a = sorted_points.index(point_a_index) pos_b = sorted_points.index(point_b_index) return (pos_a - pos_b) % len(points) == 2 or (pos_b - pos_a) % len(points) == 2
The image shows four examples of shapes formed by connecting points on a grid, with a particular focus on creating **six-pointed stars** pattern, formed by connecting points in the **circular** sequence.
def test(): test_cases = [ ([(2, 5), (4, 7), (6, 5), (5, 2), (3, 1), (1, 2)], 2, 4, True), ([(2, 5), (4, 7), (6, 5), (5, 2), (3, 1), (1, 2)], 2, 3, False), ([(2, 5), (4, 7), (6, 5), (5, 2), (3, 1), (1, 2)], 0, 4, True), ([(2, 5), (4, 7), (6, 5), (5, 2), (3, 1), (1, 2)], 0, 2, True), ([(2, 5), (4, 7), (6, 5), (5, 2), (3, 1), (1, 2)], 1, 3, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2), (1, 5)], 0, 4, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2), (1, 5)], 0, 1, False), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2), (1, 5)], 1, 3, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2), (1, 5)], 2, 4, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2), (1, 5)], 2, 5, False), ] for input_points, point_a_index, point_b_index, expected in test_cases: result = solution(input_points, point_a_index, point_b_index) assert result == expected, f"Assert Error: input {input_points} point_a_index: {point_a_index} point_b_index: {point_b_index} Expected {expected}, but got {result}" test()
def solution(points: list[tuple[int, int]], point_a_index: int, point_b_index: int) -> bool: """ Given a list of points and the index of two points, determine whether the two points should be connected to form the shape in the figure. Args: points (list[tuple[int, int]]): An list of tuples, where each tuple consists of two integers representing the x and y coordinates of a point. The points are not guaranteed to be in any particular order. point_a_index (int): The 0-based index of the first point. point_b_index (int): The 0-based index of the second point. Returns: bool: True if the two points should be connected, False otherwise. """
q37-3
from math import atan2 def solution(points: list[tuple[int, int]], point_a_index: int, point_b_index: int) -> bool: """ Given a list of points and the index of two points, determine whether the two points should be connected to form the shape in the figure. Args: points (list[tuple[int, int]]): An list of tuples, where each tuple consists of two integers representing the x and y coordinates of a point. The points are not guaranteed to be in any particular order. point_a_index (int): The 0-based index of the first point. point_b_index (int): The 0-based index of the second point. Returns: bool: True if the two points should be connected, False otherwise. """ centroid_x = sum((x for x, y in points)) / len(points) centroid_y = sum((y for x, y in points)) / len(points) def polar_angle(point): x, y = point return atan2(y - centroid_y, x - centroid_x) sorted_points = sorted(range(len(points)), key=lambda i: polar_angle(points[i])) pos_a = sorted_points.index(point_a_index) pos_b = sorted_points.index(point_b_index) return (pos_a - pos_b) % len(points) == 1 or (pos_b - pos_a) % len(points) == 1
The image shows four examples of **pentagons**, which are shapes formed by connecting **adjacent points** on the perimeter. These points are connected in sequence, without skipping any, to create a closed five-sided figure.
def test(): test_cases = [ ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 2, 4, False), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 2, 3, True), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 0, 4, False), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 0, 2, True), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 1, 3, False), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 0, 4, False), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 0, 1, False), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 1, 3, False), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 2, 4, False), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 2, 3, False), ] for input_points, point_a_index, point_b_index, expected in test_cases: result = solution(input_points, point_a_index, point_b_index) assert result == expected, f"Assert Error: input {input_points} point_a_index: {point_a_index} point_b_index: {point_b_index} Expected {expected}, but got {result}" test()
def solution(points: list[tuple[int, int]], point_a_index: int, point_b_index: int) -> bool: """ Given a list of points and the index of two points, determine whether the two points should be connected to form the shape in the figure. Args: points (list[tuple[int, int]]): An list of tuples, where each tuple consists of two integers representing the x and y coordinates of a point. The points are not guaranteed to be in any particular order. point_a_index (int): The 0-based index of the first point. point_b_index (int): The 0-based index of the second point. Returns: bool: True if the two points should be connected, False otherwise. """
q38
from typing import List def solution(colors: List[List[int]], line_position: int) -> List[List[int]]: """ You are given a matrix of colors represented as a 2D list of integers. Your task is to generate a new color matrix based on the given dashed line position. Input: - colors: A 2D list of integers representing the initial state of the color matrix. Each integer corresponds to a specific color: 0 represents white, 1 represents light blue, and 2 represents dark blue. - line_position: An integer indicating the position of the dashed line in the transformation process. Output: - Return a 2D list of integers that represents the newly generated matrix after the transformation. The colors should be represented as 0 (white), 1 (light blue), and 2 (dark blue). """ num_rows = len(colors) # Divide the matrix into left and right parts based on the line_position left_part = [row[:line_position] for row in colors] right_part = [row[line_position:] for row in colors] # Mirror the left part left_part_mirrored = [row[::-1] for row in left_part] # If the left part is smaller than the right part, pad with zeros for row in left_part_mirrored: while len(row) < len(right_part[0]): row.append(0) for row in right_part: while len(row) < len(left_part[0]): row.append(0) # Add the mirrored left part to the right part result = [] for i in range(num_rows): result_row = [] for j in range(len(right_part[i])): # Add the corresponding cells combined_value = left_part_mirrored[i][j] + right_part[i][j] if combined_value > 1: combined_value = 2 # 1 + 1 = 2, representing dark blue result_row.append(combined_value) result.append(result_row) return result
The image demonstrates transformations of matrices by three examples. Every example consists of a colored matrix, a vertical axis, and a flipping arrow symbol on the axis. The matrix before the transformation has two colors on each cell: white(0) or light blue(1) and the resulting matrix may have one more color: dark blue(2). The columns are 0-indexed. ### **Example 1**: - **Input**: `1×3 Matrix` ``` [[1| 0, 1]] ``` - The **vertical axis** located at column index 1. - **Output**: `1×2 Matrix` [[|1, 1]]. ### **Example 2**: - **Input**: `1×5 Matrix` ``` [[0, 1, 1 | 0, 1]] ``` - The **vertical axis** located at column index 3. - **Output**: `1×2 Matrix` ``` [[|1, 2, 0]] ``` ### **Example 2**: - **Input**: `2x4 Matrix` ``` [ [0, 1, 0 | 0], [0, 1, 1 | 1] ] ``` - The **vertical axis** located at column index 3. - **Output**: `2×3 Matrix` ``` [ [|0, 1, 0], [|2, 1, 0] ] ``` ### Key Concept: - **0**, **1**, **2** represents white, blue, and dark blue respectively. - **|** represents the vertical axis shown in the image. ### Observation: The matrix seems to be transformed by flipping the colors of the cells on the right side of the vertical axis.
def test(): color_matrix = [ [0, 1, 0, 1] ] expected_result = [[1, 1]] result = solution(color_matrix, 2) assert result == expected_result, f"Assert Error: matrix {color_matrix} with line position 2, expected {expected_result} but got {result}" color_matrix = [ [0, 1, 0, 1] ] expected_result = [[1, 0, 1]] result = solution(color_matrix, 1) assert result == expected_result, f"Assert Error: matrix {color_matrix} with line position 1, expected {expected_result} but got {result}" color_matrix = [ [1, 1, 0, 1] ] expected_result = [[1, 2]] result = solution(color_matrix, 2) assert result == expected_result, f"Assert Error: matrix {color_matrix} with line position 2, expected {expected_result} but got {result}" color_matrix = [ [1, 1, 1, 1] ] expected_result = [[2, 2]] result = solution(color_matrix, 2) assert result == expected_result, f"Assert Error: matrix {color_matrix} with line position 1, expected {expected_result} but got {result}" color_matrix = [ [0, 1, 0, 0], [0, 1, 1, 1] ] expected_result = [[0, 1, 0], [2, 1, 0]] result = solution(color_matrix, 3) assert result == expected_result, f"Assert Error: matrix {color_matrix} with line position 3, expected {expected_result} but got {result}" color_matrix = [ [0, 1, 0, 0, 1, 1], [0, 1, 1, 1, 0, 1], [0, 1, 1, 0, 1, 1], ] expected_result = [[1, 0, 1, 1], [2, 1, 0, 1], [2, 0, 1, 1]] result = solution(color_matrix, 2) assert result == expected_result, f"Assert Error: matrix {color_matrix} with line position 2, expected {expected_result} but got {result}" color_matrix = [ [0, 1, 0, 0, 1, 1], [0, 1, 1, 1, 0, 1], [0, 1, 1, 0, 1, 1], ] expected_result = [[1, 0, 0, 1, 1], [1, 1, 1, 0, 1], [1, 1, 0, 1, 1]] result = solution(color_matrix, 1) assert result == expected_result, f"Assert Error: matrix {color_matrix} with line position 1, expected {expected_result} but got {result}" color_matrix = [ [0, 1, 0, 0, 1, 1], [0, 1, 1, 1, 0, 1], [1, 1, 1, 0, 1, 1], [1, 0, 1, 1, 0, 1], ] expected_result = [[1, 0, 0, 1, 1], [1, 1, 1, 0, 1], [2, 1, 0, 1, 1], [1, 1, 1, 0, 1]] result = solution(color_matrix, 1) assert result == expected_result, f"Assert Error: matrix {color_matrix} with line position 1, expected {expected_result} but got {result}" color_matrix = [ [0, 1, 0, 0, 1, 1], [0, 1, 1, 1, 0, 1], [1, 1, 1, 0, 1, 1], [1, 0, 1, 1, 0, 1], ] expected_result = [[1, 1, 1, 0], [1, 2, 1, 0], [1, 2, 1, 1], [1, 2, 0, 1]] result = solution(color_matrix, 4) assert result == expected_result, f"Assert Error: matrix {color_matrix} with line position 4, expected {expected_result} but got {result}" test()
from typing import List def solution(colors: List[List[int]], line_position: int) -> List[List[int]]: """ You are given a matrix of colors represented as a 2D list of integers. Your task is to generate a new color matrix based on the given dashed line position. Input: - colors: A 2D list of integers representing the initial state of the color matrix. Each integer corresponds to a specific color: 0 represents white, 1 represents light blue, and 2 represents dark blue. - line_position: An integer indicating the position of the dashed line in the transformation process. Output: - Return a 2D list of integers that represents the newly generated matrix after the transformation. The colors should be represented as 0 (white), 1 (light blue), and 2 (dark blue). """
q38-2
from typing import List def solution(matrix: List[List[int]], line_position: int) -> List[List[int]]: """ You are given a matrix of numbers. Your task is to generate a new matrix based on the given dashed line position. Input: - matrix: A 2D list of integers representing the initial state of the matrix. - line_position: An integer indicating the position of the dashed line in the transformation process. Output: - Return a 2D list of integers that represents the newly generated matrix after the transformation. """ num_rows = len(matrix) # Divide the matrix into left and right parts based on the line_position left_part = [row[:line_position] for row in matrix] right_part = [row[line_position:] for row in matrix] # Mirror the left part left_part_mirrored = [row[::-1] for row in left_part] # If the left part is smaller than the right part, pad with zeros for row in left_part_mirrored: while len(row) < len(right_part[0]): row.append(0) for row in right_part: while len(row) < len(left_part[0]): row.append(0) # Add the mirrored left part to the right part result = [] for i in range(num_rows): result_row = [] for j in range(len(right_part[i])): # Add the corresponding cells combined_value = left_part_mirrored[i][j] + right_part[i][j] result_row.append(combined_value) result.append(result_row) return result
The image demonstrates transformations of matrices by three examples. Every example consists of a matrix, a vertical axis and the result. There is a flipping arrow symbol on the axis. The columns are 0-indexed. ### **Example 1**: - **Input**: `1×3 Matrix` ``` [[1 | 2, 3]] ``` - The **vertical axis** located at column index 1. - **Output**: `1×2 Matrix` [[|3, 3]]. ### **Example 2**: - **Input**: `1×5 Matrix` ``` [[1, 2, 3 | 2, 1]] ``` - The **vertical axis** located at column index 3. - **Output**: `1×3 Matrix` ``` [[|5, 3, 1]] ``` ### **Example 2**: - **Input**: `2x4 Matrix` ``` [ [1, 2, 3 | 4], [5, 6, 7 | 8] ] ``` - The **vertical axis** located at column index 3. - **Output**: `2×3 Matrix` ``` [ [|7, 2, 1], [|15, 6, 5] ] ``` ### Key Concept: - **|** represents the vertical axis shown in the image. ### Observation: The matrix seems to be transformed by flipping and adding the values of the cells on the right side of the vertical axis.
def test(): matrix = [ [1, 2, 3] ] expected_result = [[3, 3]] result = solution(matrix, 1) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 2, expected {expected_result} but got {result}" matrix = [ [1, 2, 3] ] expected_result = [[5, 1]] result = solution(matrix, 2) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 1, expected {expected_result} but got {result}" matrix = [ [1, 2, 3, 2, 1] ] expected_result = [[5, 3, 1]] result = solution(matrix, 3) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 2, expected {expected_result} but got {result}" matrix = [ [1, 2, 3, 2, 1] ] expected_result = [[5, 3, 1]] result = solution(matrix, 2) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 1, expected {expected_result} but got {result}" matrix = [ [1, 2, 3, 2, 1] ] expected_result = [[3, 3, 2, 1]] result = solution(matrix, 1) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 3, expected {expected_result} but got {result}" matrix = [ [1, 2, 3, 4], [5, 6, 7, 8] ] expected_result = [[7, 2, 1], [15, 6, 5]] result = solution(matrix, 3) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 2, expected {expected_result} but got {result}" matrix = [ [1, 2, 3, 4], [5, 6, 7, 8] ] expected_result = [[5 ,5], [13, 13]] result = solution(matrix, 2) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 1, expected {expected_result} but got {result}" matrix = [ [1, 2, 3, 4], [5, 6, 7, 8] ] expected_result = [[3, 3, 4], [11, 7, 8]] result = solution(matrix, 1) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 1, expected {expected_result} but got {result}" matrix = [ [0, 1, 0, 0, 1, 1], [0, 1, 1, 1, 0, 1], [1, 1, 1, 0, 1, 1], [1, 0, 1, 1, 0, 1], ] expected_result = [[1, 1, 1, 0], [1, 2, 1, 0], [1, 2, 1, 1], [1, 2, 0, 1]] result = solution(matrix, 4) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 4, expected {expected_result} but got {result}" test()
from typing import List def solution(matrix: List[List[int]], line_position: int) -> List[List[int]]: """ You are given a matrix of numbers. Your task is to generate a new matrix based on the given dashed line position. Input: - matrix: A 2D list of integers representing the initial state of the matrix. - line_position: An integer indicating the position of the dashed line in the transformation process. Output: - Return a 2D list of integers that represents the newly generated matrix after the transformation. """
q38-3
from typing import List def solution(matrix: List[List[int]], line_position: int) -> List[List[int]]: """ You are given a matrix of numbers. Your task is to generate a new matrix based on the given dashed line position. Input: - matrix: A 2D list of integers representing the initial state of the matrix. - line_position: An integer indicating the position of the dashed line in the transformation process. Output: - Return a 2D list of integers that represents the newly generated matrix after the transformation. """ num_rows = len(matrix) # Divide the matrix into left and right parts based on the line_position left_part = [row[:line_position] for row in matrix] right_part = [row[line_position:] for row in matrix] # Mirror the left part left_part_mirrored = [row[::-1] for row in left_part] # If the left part is smaller than the right part, pad with zeros for row in left_part_mirrored: while len(row) < len(right_part[0]): row.append(0) for row in right_part: while len(row) < len(left_part[0]): row.append(0) # Add the mirrored left part to the right part result = [] for i in range(num_rows): result_row = [] for j in range(len(right_part[i])): # Add the corresponding cells combined_value = right_part[i][j] - left_part_mirrored[i][j] result_row.append(combined_value) result.append(result_row) return result
The image demonstrates transformations of matrices by three examples. Every example consists of a matrix, a vertical axis and the result. There is a flipping arrow symbol on the axis. The columns are 0-indexed. ### **Example 1**: - **Input**: `1×3 Matrix` ``` [[1 | 2, 3]] ``` - The **vertical axis** located at column index 1. - **Output**: `1×2 Matrix` [[|1, 3]]. ### **Example 2**: - **Input**: `1×5 Matrix` ``` [[1, 2, 3 | 4, 5]] ``` - The **vertical axis** located at column index 3. - **Output**: `1×3 Matrix` ``` [[|1, 3, -1]] ``` ### **Example 2**: - **Input**: `2×4 Matrix` ``` [ [1, 2, 3 | 2], [5, 6, 7 | 5] ] ``` - The **vertical axis** located at column index 3. - **Output**: `2×3 Matrix` ``` [ [|-1, -2, -1], [|-2, -6, -5] ] ``` ### Key Concept: - **|** represents the vertical axis shown in the image. ### Observation: The matrix seems to be transformed by flipping and subtracting the values of the cells on the right side of the vertical axis.
def test(): matrix = [ [1, 2, 3] ] expected_result = [[1, 3]] result = solution(matrix, 1) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 2, expected {expected_result} but got {result}" matrix = [ [1, 2, 3] ] expected_result = [[1, -1]] result = solution(matrix, 2) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 1, expected {expected_result} but got {result}" matrix = [ [1, 2, 3, 4, 5] ] expected_result = [[1, 3, -1]] result = solution(matrix, 3) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 2, expected {expected_result} but got {result}" matrix = [ [1, 2, 3, 4, 5] ] expected_result = [[1, 3, 5]] result = solution(matrix, 2) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 1, expected {expected_result} but got {result}" matrix = [ [1, 2, 3, 4, 5] ] expected_result = [[1, 3, 4, 5]] result = solution(matrix, 1) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 3, expected {expected_result} but got {result}" matrix = [ [1, 2, 3, 2], [5, 6, 7, 5] ] expected_result = [[-1, -2, -1], [-2, -6, -5]] result = solution(matrix, 3) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 2, expected {expected_result} but got {result}" matrix = [ [1, 2, 3, 2], [5, 6, 7, 5] ] expected_result = [[1 ,1], [1, 0]] result = solution(matrix, 2) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 1, expected {expected_result} but got {result}" matrix = [ [1, 2, 3, 2], [5, 6, 7, 5] ] expected_result = [[1, 3, 2], [1, 7, 5]] result = solution(matrix, 1) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 1, expected {expected_result} but got {result}" matrix = [ [0, 1, 0, 0, 1, 1], [0, 1, 1, 1, 0, 1], [1, 1, 1, 0, 1, 1], [1, 0, 1, 1, 0, 1], ] expected_result = [[1, 1, -1, 0], [-1, 0, -1, 0], [1, 0, -1, -1], [-1, 0, 0, -1]] result = solution(matrix, 4) assert result == expected_result, f"Assert Error: matrix {matrix} with line position 4, expected {expected_result} but got {result}" test()
from typing import List def solution(matrix: List[List[int]], line_position: int) -> List[List[int]]: """ You are given a matrix of numbers. Your task is to generate a new matrix based on the given dashed line position. Input: - matrix: A 2D list of integers representing the initial state of the matrix. - line_position: An integer indicating the position of the dashed line in the transformation process. Output: - Return a 2D list of integers that represents the newly generated matrix after the transformation. """
q39
from typing import List, Tuple def move_direction(x: int, y: int, direction: str) -> Tuple[int, int]: """Move to the next cell based on the given direction.""" if direction == 'L': return x, y - 1 elif direction == 'R': return x, y + 1 elif direction == 'U': return x - 1, y elif direction == 'D': return x + 1, y return x, y def escape_path(matrix: List[List[str]], start_x: int, start_y: int) -> int: """Simulate the escape from a given start position.""" n = len(matrix) m = len(matrix[0]) visited = set() x, y = start_x, start_y x_, y_ = x, y steps = 0 while 0 <= x < n and 0 <= y < m: if (x, y) in visited: x, y = move_direction(x, y, direction=matrix[x_][y_]) continue visited.add((x, y)) steps += 1 x_, y_ = x, y x, y = move_direction(x, y, matrix[x][y]) if 0 <= x < n and 0 <= y < m: # Didn't escape, cycle detected return -1 else: # Escaped return steps def solution(matrix: List[List[str]]) -> Tuple[int, int]: """ Determine the starting node that results in the most nodes visited before ending. Input: - matrix: A 2D list where each element is a string representing a direction: 'L' for left, 'R' for right, 'U' for up, and 'D' for down. Output: - A tuple of two integers representing the 0-based index (row, column) of the starting node that results in the longest visited path. """ n = len(matrix) m = len(matrix[0]) max_steps = -1 best_start = (-1, -1) for i in range(n): for j in range(m): steps = escape_path(matrix, i, j) if steps > max_steps: max_steps = steps best_start = (i, j) return best_start
The image demonstrates two grid-based paths, with directional arrows in each block guiding the movement from a **start** position to an **end** position. The paths follow the rule that **each block can change direction only once**. ### **Diagram**: 1. **Grid Layout**: - The grid is 3x3, and each block contains a blue directional arrow. - The arrows show directions: left, right, down, or up. 2. **Path Description**: - From the start at (0,0), the path follows the **right arrow** to (0,1). - At (0,1), the arrow points down, so the path continues to (1,1). - At (1,1), the arrow points left, so the path continues to (1,0). - At (1,0), the arrow points right, so the path continues to (1,1). - At (1,1), because this node has been visited before and each block can change direction only once, so the direction keeps the same of (1,0), so the path continues to (1,2). - At (1,2), the arrow points up, so the path continues to (0,2). - At (0,2), the arrow points up, so the path continues to leave the matrix and comes to the end.
def test(): matrix = [ ['R', 'D', 'L'], ['L', 'U', 'R'], ['U', 'L', 'U'] ] expected_result = (1, 1) result = solution(matrix) assert result == expected_result, f"Assert Error: Matrix {matrix}, Expected {expected_result}, Got: {result}" matrix = [ ['D', 'R', 'L', 'D'], ['U', 'L', 'U', 'L'], ['D', 'U', 'U', 'R'], ['R', 'D', 'D', 'L'] ] expected_result = (2, 2) result = solution(matrix) assert result == expected_result, f"Assert Error: Matrix {matrix}, Expected {expected_result}, Got: {result}" matrix = [ ['D', 'R', 'D', 'D'], ['L', 'U', 'R', 'U'] ] expected_result = (1, 1) result = solution(matrix) assert result == expected_result, f"Assert Error: Matrix {matrix}, Expected {expected_result}, Got: {result}" matrix = [ ['R', 'D', 'R', 'U', 'D'], ['U', 'L', 'U', 'L', 'U'], ['D', 'U', 'U', 'R', 'R'] ] expected_result = (0, 1) result = solution(matrix) assert result == expected_result, f"Assert Error: Matrix {matrix}, Expected {expected_result}, Got: {result}" matrix = [ ['D', 'R', 'D', 'U'], ['U', 'U', 'R', 'L'], ['L', 'D', 'R', 'U'] ] expected_result = (1, 1) result = solution(matrix) assert result == expected_result, f"Assert Error: Matrix {matrix}, Expected {expected_result}, Got: {result}" test()
from typing import List, Tuple def solution(matrix: List[List[str]]) -> Tuple[int, int]: """ Determine the starting node that results in the most nodes visited before ending. Input: - matrix: A 2D list where each element is a string representing a direction: 'L' for left, 'R' for right, 'U' for up, and 'D' for down. Output: - A tuple of two integers representing the 0-based index (row, column) of the starting node that results in the longest visited path. """
q39-2
from typing import List, Tuple def move_direction(x: int, y: int, direction: str) -> Tuple[int, int]: """Move to the next cell based on the given direction.""" if direction == 'L': return x, y - 1 elif direction == 'R': return x, y + 1 elif direction == 'U': return x - 1, y elif direction == 'D': return x + 1, y return x, y def escape_path(matrix: List[List[str]], start_x: int, start_y: int, home) -> int: """Simulate the escape from a given start position.""" n = len(matrix) m = len(matrix[0]) visited = set() x, y = start_x, start_y x_, y_ = x, y steps = 0 while 0 <= x < n and 0 <= y < m: if (x, y) in visited: x, y = move_direction(x, y, direction=matrix[x_][y_]) continue visited.add((x, y)) steps += 1 x_, y_ = x, y x, y = move_direction(x, y, matrix[x][y]) if (x, y) != home: return -1 else: # Escaped return steps def solution(matrix: List[List[str]], home: Tuple[int, int]) -> Tuple[int, int]: """ Determine the starting node that results in the most nodes visited before arriving home. Input: - matrix: A 2D list where each element is a string representing a direction: 'L' for left, 'R' for right, 'U' for up, and 'D' for down. - home: The position of the home node. the index range of the home node is -1 <= home[0] <= len(matrix) and -1 <= home[1] <= len(matrix[0]). Output: - A tuple of two integers representing the 0-based index (row, column) of the starting node that results in the longest visited path. """ n = len(matrix) m = len(matrix[0]) max_steps = -1 best_start = (-1, -1) for i in range(n): for j in range(m): steps = escape_path(matrix, i, j, home) if steps > max_steps: max_steps = steps best_start = (i, j) return best_start
The image demonstrates two grid-based paths, with directional arrows in each block guiding the movement from a **start** position to an **end** position. The right exit is marked as a home symbol. The paths follow the rule that **each block can change direction only once**. ### **Left Diagram**: 1. **Grid Layout**: - The grid is 3x3, and each block contains a blue directional arrow. - The arrows show directions: left, right, down, or up. - The home symbol's position is (-1,2). 2. **Path Description**: - From the start at (0,0), the path follows the **right arrow** to (0,1). - At (0,1), the arrow points down, so the path continues to (1,1). - At (1,1), the arrow points left, so the path continues to (1,0). - At (1,0), the arrow points right, so the path continues to (1,1). - At (1,1), because this node has been visited before and each block can change direction only once, so the direction keeps the same of (1,0), so the path continues to (1,2). - At (1,2), the arrow points up, so the path continues to (0,2). - At (0,2), the arrow points up, so the path continues to (-1,2) and reach the home symbol so comes to the end. ### **Right Diagram**: 1. **Grid Layout**: - The grid is 3x3, and each block contains a blue directional arrow. - The arrows show directions: left, right, down, or up. - The home symbol's position is (2,3). 2. **Path Description**: - From the start at (0,1), the path follows the **down arrow** to (1,1). - At (1,1), the arrow points down, so the path continues to (2,1). - At (2,1), the arrow points left, so the path continues to (2,0). - At (2,0), the arrow points up, so the path continues to (1,0). - At (1,0), the arrow points down, so the path continues to (2,0). - At (2,0), because this node has been visited before and each block can change direction only once, so the direction keeps the same of (1,0), so the path continues to (3,0) and leave the matrix. However, home symbol is at (2,3) so this is a wrong way.
def test(): matrix = [ ['R', 'D', 'L'], ['L', 'U', 'R'], ['U', 'L', 'U'] ] home = (1, 3) expected_result = (2, 2) result = solution(matrix, home) assert result == expected_result, f"Assert Error: Matrix {matrix}, Expected {expected_result}, Got: {result}" matrix = [ ['R', 'D', 'L'], ['L', 'U', 'R'], ['U', 'L', 'U'] ] home = (-1, 1) expected_result = (0, 0) result = solution(matrix, home) assert result == expected_result, f"Assert Error: Matrix {matrix}, Expected {expected_result}, Got: {result}" matrix = [ ['D', 'R', 'L', 'D'], ['U', 'L', 'U', 'L'], ['D', 'U', 'U', 'R'], ['R', 'D', 'D', 'L'] ] home = (2, 4) expected_result = (1, 3) result = solution(matrix, home) assert result == expected_result, f"Assert Error: Matrix {matrix}, Expected {expected_result}, Got: {result}" matrix = [ ['D', 'R', 'L', 'D'], ['U', 'L', 'U', 'L'], ['D', 'U', 'U', 'R'], ['R', 'D', 'D', 'L'] ] home = (4, 1) expected_result = (2, 2) result = solution(matrix, home) assert result == expected_result, f"Assert Error: Matrix {matrix}, Expected {expected_result}, Got: {result}" matrix = [ ['D', 'R', 'D', 'D'], ['L', 'U', 'R', 'U'] ] home = (1, -1) expected_result = (0, 0) result = solution(matrix, home) assert result == expected_result, f"Assert Error: Matrix {matrix}, Expected {expected_result}, Got: {result}" matrix = [ ['D', 'R', 'D', 'D'], ['L', 'U', 'R', 'U'] ] home = (2, 3) expected_result = (1, 1) result = solution(matrix, home) assert result == expected_result, f"Assert Error: Matrix {matrix}, Expected {expected_result}, Got: {result}" matrix = [ ['D', 'R', 'D', 'U'], ['U', 'U', 'R', 'L'], ['L', 'D', 'R', 'U'] ] home = (2, -1) expected_result = (1, 1) result = solution(matrix, home) assert result == expected_result, f"Assert Error: Matrix {matrix}, Expected {expected_result}, Got: {result}" test()
from typing import List, Tuple def solution(matrix: List[List[str]], home: Tuple[int, int]) -> Tuple[int, int]: """ Determine the starting node that results in the most nodes visited before arriving home. Input: - matrix: A 2D list where each element is a string representing a direction: 'L' for left, 'R' for right, 'U' for up, and 'D' for down. - home: The position of the home node. the index range of the home node is -1 <= home[0] <= len(matrix) and -1 <= home[1] <= len(matrix[0]). Output: - A tuple of two integers representing the 0-based index (row, column) of the starting node that results in the longest visited path. """
q4
from typing import List, Tuple def solution(dots: List[Tuple[int, int]], grid_size: int) -> int: """ Find the largest valid rectangle that can fit within the grid. Parameters: dots: A list of tuples representing the coordinates of dots in the grid. grid_size: The size of the grid (with dimensions grid_size x grid_size). Returns: The area of the located rectangle. Returns 0 if no valid rectangle can be found. """ # Initialize variables to keep track of the best rectangle found best_area = 0 best_rectangle = None # Convert the list of dots to a set for faster look-up dot_set = set(dots) # Iterate over all possible top-left corners of rectangles for top_left_x in range(grid_size+1): for top_left_y in range(grid_size+1): # Iterate over all possible bottom-right corners of rectangles for bottom_right_x in range(top_left_x + 1, grid_size + 1): for bottom_right_y in range(top_left_y): # Check if this rectangle is valid (i.e., no dots inside it) valid = True for x in range(top_left_x+1, bottom_right_x): for y in range(bottom_right_y+1, top_left_y): if (x, y) in dot_set: valid = False break if not valid: break if valid: area = (bottom_right_x - top_left_x) * (top_left_y - bottom_right_y) if area > best_area: best_area = area best_rectangle = ((top_left_x, top_left_y), (bottom_right_x, bottom_right_y)) # draw import matplotlib.pyplot as plt import matplotlib.patches as patches fig, ax = plt.subplots() ax.set_xlim(0, grid_size) ax.set_ylim(0, grid_size) for dot in dots: ax.plot(dot[0], dot[1], 'ro') top_left, bottom_right = best_rectangle if top_left and bottom_right: rect = patches.Rectangle(top_left, bottom_right[0] - top_left[0], bottom_right[1] - top_left[1], linewidth=1, edgecolor='r', facecolor='none') print(top_left, bottom_right) print((bottom_right[0] - top_left[0])* (top_left[1] - bottom_right[1])) ax.add_patch(rect) plt.show() return best_area
The image shows a grid containing many red dots. In the valid rectangular area, there are no dots inside, but red dots sometimes appear along the edges. All invalid rectangular areas have red dots inside.
def test(): test_cases = [ ([(3, 3), (5, 5)], 12, 84), ([(3, 3), (3, 5)], 12, 108), ([(3, 3), (7, 7), (9, 9), (5, 5)], 12, 49), ([(4, 4), (2, 2), (1, 1), (10, 10), (11,1), (8,1)], 12, 80), ([(1,11), (4, 4), (2, 2), (1, 1), (10, 10), (11,1), (8,1)], 12, 72), ([], 1, 1), ([(0,0), (0,1), (1,0), (1,1)], 1, 1), ([(2, 2)], 4, 8), ([(1, 2)], 4, 12), ([(1, 0)], 4, 16) ] for points, grid_size, expected in test_cases: result = solution(points, grid_size) assert result == expected, f"Assert Error: Test failed for points {points}, grid size {grid_size}. Expected {expected}, got {result}" test()
from typing import List, Tuple def solution(dots: List[Tuple[int, int]], grid_size: int) -> int: """ Find the largest valid rectangle that can fit within the grid. Parameters: dots: A list of tuples representing the coordinates of dots in the grid. grid_size: The size of the grid (with dimensions grid_size x grid_size). Returns: The area of the located rectangle. Returns 0 if no valid rectangle can be found. """
q4-2
from typing import List, Tuple def solution(dots: List[Tuple[int, int]], grid_size: int) -> int: """ Find the largest valid rectangle that can fit within the grid. Parameters: dots: A list of tuples representing the coordinates of dots in the grid. grid_size: The size of the grid (with dimensions grid_size x grid_size). Returns: The area of the located rectangle. Returns 0 if no valid rectangle can be found. """ # Initialize variables to keep track of the best rectangle found best_area = 0 best_rectangle = None # Convert the list of dots to a set for faster look-up dot_set = set(dots) # Iterate over all possible top-left corners of rectangles for top_left_x in range(grid_size+1): for top_left_y in range(grid_size+1): # Iterate over all possible bottom-right corners of rectangles for bottom_right_x in range(top_left_x + 1, grid_size + 1): for bottom_right_y in range(top_left_y): # Check if this rectangle is valid (i.e., no dots inside it) dot_num = 0 valid = True for x in range(top_left_x, bottom_right_x + 1): for y in range(bottom_right_y, top_left_y + 1): if (x, y) in dot_set: dot_num += 1 if dot_num > 1: valid = False break if not valid: break if dot_num == 0: valid = False if valid: area = (bottom_right_x - top_left_x) * (top_left_y - bottom_right_y) if area > best_area: best_area = area best_rectangle = ((top_left_x, top_left_y), (bottom_right_x, bottom_right_y)) # draw import matplotlib.pyplot as plt import matplotlib.patches as patches fig, ax = plt.subplots() ax.set_xlim(0, grid_size) ax.set_ylim(0, grid_size) for dot in dots: ax.plot(dot[0], dot[1], 'ro') top_left, bottom_right = best_rectangle if top_left and bottom_right: rect = patches.Rectangle(top_left, bottom_right[0] - top_left[0], bottom_right[1] - top_left[1], linewidth=1, edgecolor='r', facecolor='none') print(top_left, bottom_right) print((bottom_right[0] - top_left[0])* (top_left[1] - bottom_right[1])) ax.add_patch(rect) plt.show() return best_area
The image shows a grid containing many red dots. In the valid rectangular area, there is either one red dot inside or on the edge. In the invalid rectangular areas, there are no red dots or more than 1 red dots inside or on the edge.
def test(): test_cases = [ ([(3, 3), (5, 5)], 12, 96), ([(3, 4), (3, 5)], 12, 84), ([(3, 3), (7, 7), (9, 9), (5, 5)], 12, 48), ([(4, 4), (2, 2), (1, 1), (10, 10), (11,1), (8,1)], 12, 84), ([(1,11), (4, 4), (2, 2), (1, 1), (10, 10), (11,1), (8,1)], 12, 72), ([], 1, 0), ([(0,0), (0,1), (1,0), (1,1)], 1, 0), ([(2, 2)], 4, 16), ([(1, 2)], 4, 16), ([(1, 0), (1, 2)], 4, 12) ] for points, grid_size, expected in test_cases: result = solution(points, grid_size) assert result == expected, f"Assert Error: Test failed for points {points}, grid size {grid_size}. Expected {expected}, got {result}" test()
from typing import List, Tuple def solution(dots: List[Tuple[int, int]], grid_size: int) -> int: """ Find the largest valid rectangle that can fit within the grid. Parameters: dots: A list of tuples representing the coordinates of dots in the grid. grid_size: The size of the grid (with dimensions grid_size x grid_size). Returns: The area of the located rectangle. Returns 0 if no valid rectangle can be found. """
q4-3
from typing import List, Tuple def solution(dots: List[Tuple[int, int]], grid_size: int) -> int: """ Find the largest valid rectangle that can fit within the grid. Parameters: dots: A list of tuples representing the coordinates of dots in the grid. grid_size: The size of the grid (with dimensions grid_size x grid_size). Returns: The area of the located rectangle. Returns 0 if no valid rectangle can be found. """ # Initialize variables to keep track of the best rectangle found best_area = 0 best_rectangle = None # Convert the list of dots to a set for faster look-up dot_set = set(dots) # Iterate over all possible top-left corners of rectangles for top_left_x in range(grid_size+1): for top_left_y in range(grid_size+1): # Iterate over all possible bottom-right corners of rectangles for bottom_right_x in range(top_left_x + 1, grid_size + 1): for bottom_right_y in range(top_left_y): # Check if this rectangle is valid (i.e., no dots inside it) valid = True for x in range(top_left_x, bottom_right_x + 1): for y in range(bottom_right_y, top_left_y + 1): if (x, y) in dot_set: valid = False break if not valid: break if valid: area = (bottom_right_x - top_left_x) * (top_left_y - bottom_right_y) if area > best_area: best_area = area best_rectangle = ((top_left_x, top_left_y), (bottom_right_x, bottom_right_y)) # draw import matplotlib.pyplot as plt import matplotlib.patches as patches fig, ax = plt.subplots() ax.set_xlim(0, grid_size) ax.set_ylim(0, grid_size) for dot in dots: ax.plot(dot[0], dot[1], 'ro') top_left, bottom_right = best_rectangle if top_left and bottom_right: rect = patches.Rectangle(top_left, bottom_right[0] - top_left[0], bottom_right[1] - top_left[1], linewidth=1, edgecolor='r', facecolor='none') print(top_left, bottom_right) print((bottom_right[0] - top_left[0])* (top_left[1] - bottom_right[1])) ax.add_patch(rect) plt.show() return best_area
The image shows a grid containing many red dots. The valid rectangular area does not touch or contain any red dots. All the invalid rectangular areas contain red dots or have red dots on the edges.
def test(): test_cases = [ ([(3, 3), (5, 5)], 12, 72), ([(3, 4), (3, 5)], 12, 96), ([(3, 3), (7, 7), (9, 9), (5, 5)], 12, 36), ([(4, 4), (2, 2), (1, 1), (10, 10), (11,1), (8,1)], 12, 63), ([(1,11), (4, 4), (2, 2), (1, 1), (10, 10), (11,1), (8,1)], 12, 49), ([], 1, 1), ([(0,0), (0,1), (1,0), (1,1)], 1, 0), ([(2, 2)], 4, 4), ([(1, 2)], 4, 8), ([(1, 0), (1, 2)], 4, 8) ] for points, grid_size, expected in test_cases: result = solution(points, grid_size) assert result == expected, f"Assert Error: Test failed for points {points}, grid size {grid_size}. Expected {expected}, got {result}" test()
from typing import List, Tuple def solution(dots: List[Tuple[int, int]], grid_size: int) -> int: """ Find the largest valid rectangle that can fit within the grid. Parameters: dots: A list of tuples representing the coordinates of dots in the grid. grid_size: The size of the grid (with dimensions grid_size x grid_size). Returns: The area of the located rectangle. Returns 0 if no valid rectangle can be found. """
q40
import math def solution(h: int, m: int, a: int, b: int, k: int) -> float: """ Given an initial time (in 12-hour format) and the lengths of the orange and green arrows, calculate the length of the red dashed line after k minutes Parameters: h (int): Hour. m (int): Minute. a (int): Length of the orange arrow. b (int): Length of the green arrow. k (int): Duration passed (in minutes). Returns: float: Length of the red dashed line (rounded to two decimal places). """ # Calculate the new time total_minutes = h * 60 + m + k new_m = total_minutes % 60 # Calculate the angles minute_angle = new_m * 6 # 6 degrees per minute hour_angle = (h % 12) * 30 + m * 0.5 # 30 degrees per hour + 0.5 degrees per minute # Convert angles to radians minute_angle_rad = math.radians(minute_angle) hour_angle_rad = math.radians(hour_angle) # Convert to Cartesian coordinates minute_x = b * math.cos(minute_angle_rad) minute_y = b * math.sin(minute_angle_rad) hour_x = a * math.cos(hour_angle_rad) hour_y = a * math.sin(hour_angle_rad) # Calculate the distance between the two points distance = math.sqrt((minute_x - hour_x) ** 2 + (minute_y - hour_y) ** 2) return round(distance, 2)
The image depicts two scenarios of time progression on analog clocks, with arrows showing the movement of the **hour hand** and **minute hand** over specific intervals. ### Key Observation: In both scenarios, there is a **red dashed line**, and this red line represents the connection between the **original position of the hour hand** and the **new position of the minute hand** after the time has progressed. ### **Description of the Scenarios**: #### **Top Pair of Clocks**: - **Initial Time**: 3:00 - The **green arrow** points upward, showing the minute is 0. - The **orange arrow** points to the right, showing the hour is 3. - **Time Progression**: After 40 minutes, the hands have moved. - The **green arrow** shows the new position of the minute hand. - The **orange arrow** shows the new position of the hour hand. - The **red dashed line** represents the connection between the **initial position of the hour hand** (3 o’clock) and the **new position of the minute hand** after 40 minutes (pointing to the 8th indicator). #### **Bottom Pair of Clocks**: - **Initial Time**: 4:20 - The **green arrow** points slightly downwards, indicating the minute is 20. - The **orange arrow** shows the hour is after 4, before 5. - **Time Progression**: After 70 minutes, both hands have moved. - The **green arrow** shows the new position of the minute hand. - The **orange arrow** shows the new position of the hour hand. - The **red dashed line** connects the **original position of the hour hand** (4:20) with the **new position of the minute hand** after 70 minutes.
def test(): test_cases = [ (3, 0, 3, 4, 40, 6.77), (3, 0, 4, 3, 180, 5.0), (3, 0, 2, 7, 40, 8.79), (4, 20, 6, 8, 70, 6.19), (6, 0, 6, 8, 150, 2), (8, 22, 5, 9, 137, 4.46), (7, 12, 4, 6, 29, 3.23), (1, 56, 2, 7, 173, 8.29), (1, 56, 3, 4, 104, 7.0), (0, 56, 3, 4, 84, 5.08), ] for h, m, a, b, k, expected in test_cases: result = solution(h, m, a, b, k) assert result == expected, f"Assert Error: Input {(h, m, a, b, k)}, Expected {expected}, Got: {result}" test()
def solution(h: int, m: int, a: int, b: int, k: int) -> float: """ Given an initial time (in 12-hour format) and the lengths of the orange and green arrows, calculate the length of the red dashed line after k minutes Parameters: h (int): Hour. m (int): Minute. a (int): Length of the orange arrow. b (int): Length of the green arrow. k (int): Duration passed (in minutes). Returns: float: Length of the red dashed line (rounded to two decimal places). """
q40-2
import math def solution(h: int, m: int, a: int, b: int, k: int) -> float: """ Given an initial time (in 12-hour format) and the lengths of the orange and green arrows, calculate the area of the blue region after k minutes Parameters: h (int): Hour. m (int): Minute. a (int): Length of the orange arrow. b (int): Length of the green arrow. k (int): Duration passed (in minutes). Returns: float: Area of the blue region (rounded to two decimal places). """ # Calculate the new time for the minute hand total_minutes = h * 60 + m + k new_m = total_minutes % 60 # Calculate the angles minute_angle = new_m * 6 # 6 degrees per minute hour_angle = (h % 12) * 30 + m * 0.5 # 30 degrees per hour + 0.5 degrees per minute # Convert angles to radians minute_angle_rad = math.radians(minute_angle) hour_angle_rad = math.radians(hour_angle) # Convert to Cartesian coordinates minute_x = b * math.cos(minute_angle_rad) minute_y = b * math.sin(minute_angle_rad) hour_x = a * math.cos(hour_angle_rad) hour_y = a * math.sin(hour_angle_rad) # Calculate the area of the triangle using the cross product formula area = 0.5 * abs(hour_x * minute_y - hour_y * minute_x) return round(area, 2)
### **Top Pair of Clocks (3:00 to 3:40)**: - **Initial Time**: 3:00 - The **green arrow** points upward, showing the minute is 0. - The **orange arrow** points to the right, showing the hour is 3. - **Time Progression**: After 40 minutes, the hands have moved. - The **green arrow** shows the new position of the minute hand. - The **orange arrow** shows the new position of the hour hand. - The **blue triangle** is formed by the **original position of the hour hand**, the **new position of the minute hand**, and the **center of the clock**. ### **Bottom Pair of Clocks (4:20 to 5:30)**: - **Initial Time**: 4:20 - The **green arrow** points slightly downwards, indicating the minute is 20. - The **orange arrow** shows the hour is after 4, before 5. - **Time Progression**: After 70 minutes, both hands have moved. - The **green arrow** shows the new position of the minute hand. - The **orange arrow** shows the new position of the hour hand. - The **blue triangle** is formed between the **original position of the hour hand**, the **new position of the minute hand**, and the **center of the clock**.
def test(): test_cases = [ (3, 0, 3, 4, 30, 6.0), (3, 0, 4, 3, 180, 6.0), (3, 0, 2, 7, 40, 3.5), (4, 20, 6, 8, 70, 18.39), (6, 0, 6, 8, 150, 0), (8, 22, 5, 9, 137, 6.58), (7, 12, 4, 6, 29, 6.0), (1, 56, 2, 7, 173, 5.8), (1, 56, 3, 4, 104, 0.21), (0, 56, 3, 4, 84, 6.0), ] for h, m, a, b, k, expected in test_cases: result = solution(h, m, a, b, k) assert result == expected, f"Assert Error: Input {(h, m, a, b, k)}, Expected {expected}, Got: {result}" test()
def solution(h: int, m: int, a: int, b: int, k: int) -> float: """ Given an initial time (in 12-hour format) and the lengths of the orange and green arrows, calculate the area of the blue region after k minutes Parameters: h (int): Hour. m (int): Minute. a (int): Length of the orange arrow. b (int): Length of the green arrow. k (int): Duration passed (in minutes). Returns: float: Area of the blue region (rounded to two decimal places). """
q40-3
import math def solution(h: int, m: int, a: int, b: int, k: int) -> float: """ Given an initial time (in 12-hour format) and the lengths of the orange and green arrows, calculate the distance between the initial minute hand and the hour hand after k minutes. Parameters: h (int): Hour. m (int): Minute. a (int): Length of the orange arrow (hour hand). b (int): Length of the green arrow (minute hand). k (int): Duration passed (in minutes). Returns: float: Distance between the initial minute hand and the hour hand after k minutes (rounded to two decimal places). """ # Calculate the new time for the hour hand total_minutes = h * 60 + m + k new_h = (total_minutes // 60) % 12 new_m = total_minutes % 60 # Calculate the angles initial_minute_angle = m * 6 # 6 degrees per minute for the initial minute hand hour_angle = (new_h % 12) * 30 + new_m * 0.5 # 30 degrees per hour + 0.5 degrees per minute # Convert angles to radians minute_angle_rad = math.radians(initial_minute_angle) hour_angle_rad = math.radians(hour_angle) # Convert to Cartesian coordinates # Initial minute hand minute_x = b * math.cos(minute_angle_rad) minute_y = b * math.sin(minute_angle_rad) # New hour hand after k minutes hour_x = a * math.cos(hour_angle_rad) hour_y = a * math.sin(hour_angle_rad) # Calculate the distance between the two points distance = math.sqrt((minute_x - hour_x) ** 2 + (minute_y - hour_y) ** 2) return round(distance, 2)
The image depicts two scenarios of time progression on analog clocks, with arrows showing the movement of the **hour hand** and **minute hand** over specific intervals. ### Key Observation: In both scenarios, there is a **red dashed line**, and this red line represents the connection between the **original position of the minute hand** and the **new position of the hour hand** after the time has progressed. ### **Description of the Scenarios**: #### **Top Pair of Clocks**: - **Initial Time**: 3:00 - The **green arrow** points upward, showing the minute is 0. - The **orange arrow** points to the right, showing the hour is 3. - **Time Progression**: After 40 minutes, the hands have moved. - The **green arrow** shows the new position of the minute hand. - The **orange arrow** shows the new position of the hour hand. - The **red dashed line** represents the connection between the **initial position of the minute hand** (3 o’clock) and the **new position of the hour hand** after 40 minutes (pointing to the 8th indicator). #### **Bottom Pair of Clocks**: - **Initial Time**: 4:20 - The **green arrow** points slightly downwards, indicating the minute is 20. - The **orange arrow** shows the hour is after 4, before 5. - **Time Progression**: After 70 minutes, both hands have moved. - The **green arrow** shows the new position of the minute hand. - The **orange arrow** shows the new position of the hour hand. - The **red dashed line** connects the **original position of the minute hand** (4:20) with the **new position of the hour hand** after 70 minutes.
def test(): test_cases = [ (2, 0, 3, 4, 60, 5.0), (3, 0, 4, 3, 180, 7.0), (3, 0, 2, 7, 40, 7.91), (4, 20, 6, 8, 70, 5.67), (6, 0, 6, 8, 150, 11.17), (8, 22, 5, 9, 137, 13.97), (7, 12, 4, 6, 29, 9.83), (1, 56, 2, 7, 173, 8.97), (1, 56, 3, 4, 104, 6.46), (0, 56, 3, 4, 84, 5.16), ] for h, m, a, b, k, expected in test_cases: result = solution(h, m, a, b, k) assert result == expected, f"Assert Error: Input {(h, m, a, b, k)}, Expected {expected}, Got: {result}" test()
def solution(h: int, m: int, a: int, b: int, k: int) -> float: """ Given an initial time (in 12-hour format) and the lengths of the orange and green arrows, calculate the length of the red dashed line after k minutes Parameters: h (int): Hour. m (int): Minute. a (int): Length of the orange arrow. b (int): Length of the green arrow. k (int): Duration passed (in minutes). Returns: float: Length of the red dashed line (rounded to two decimal places). """
q5
from typing import List, Tuple def solution(shots: List[Tuple[int, int]]) -> int: """ Calculate the total score based on the shot locations and the areas, with points assigned according to the different colored areas on the grid. Args: shots: A list of tuples where each tuple contains the x and y coordinates of a shot. Returns: int: The total score calculated based on the shots in the grid. """ def calculate_score(x: int, y: int) -> int: # Central green area (Score 10) if 5 <= x <= 6 and 5 <= y <= 6: return 10 # Surrounding orange area (Score 5) elif 4 <= x <= 7 and 4 <= y <= 7: return 0 # Surrounding blue area (Score 1) elif 3 <= x <= 8 and 3 <= y <= 8: return 5 elif 2 <= x <= 9 and 2 <= y <= 9: return 0 elif 1 <= x <= 10 and 1 <= y <= 10: return 1 else: return 0 # Calculate total score by summing the scores for all shots total_score = sum(calculate_score(x, y) for x, y in shots) return total_score
This image shows a 10 x 10 two-dimensional matrix, with each layer having a different color and corresponding score. Here are the color regions with their top-left and bottom-right coordinates: - The innermost green area (Score: 10 points) has top-left coordinates at (5, 6) and bottom-right coordinates at (6, 5). - The second gray area (Score: 0 points) has top-left coordinates at (4, 7) and bottom-right coordinates at (7, 4). - The third light pink area (Score: 5 point) has top-left coordinates at (3, 8) and bottom-right coordinates at (8, 3). - The fourth gray area (Score: 0 points) has top-left coordinates at (2, 9) and bottom-right coordinates at (9, 2). - The outermost blue area (Score: 1 points) has top-left coordinates at (1, 10) and bottom-right coordinates at (10, 1).
def test(): test_cases = [ ([(1, 1), (3, 3)], 6), ([(2, 2), (4, 4)], 0), ([(5, 5), (6, 6), (4, 4), (7, 7), (3, 3)], 25), ([(7, 8), (3, 2), (5, 5), (6, 6)], 25), ([], 0), ([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10)], 32), ([(5, 6), (6, 5), (5, 5), (6, 6)], 40), ([(5, 4), (6, 7), (3, 8), (8, 3)], 10), ([(5, 5), (6, 6), (4, 4), (7, 7), (3, 3)], 25), ([(5, 1), (6, 2), (4, 3), (7, 4), (3, 5)], 11) ] for points, expected in test_cases: result = solution(points) assert result == expected, f"Assert Error: Test failed for points {points}. Expected {expected}, got {result}" test()
from typing import List, Tuple def solution(shots: List[Tuple[int, int]]) -> int: """ Calculate the total score based on the shot locations and the areas, with points assigned according to the different colored areas on the grid. Args: shots: A list of tuples where each tuple contains the x and y coordinates of a shot. Returns: int: The total score calculated based on the shots in the grid. """
q5-2
from typing import List, Tuple def solution(shots: List[Tuple[int, int]]) -> int: """ Calculate the total score based on the shot locations and the areas, with points assigned according to the different colored areas on the grid. Args: shots: A list of tuples where each tuple contains the x and y coordinates of a shot. Returns: int: The total score calculated based on the shots in the grid. """ def calculate_score(x: int, y: int) -> int: # Central green area (Score 10) if 4 <= x <= 7 and 4 <= y <= 7: return 10 # Surrounding orange area (Score 5) elif 2 <= x <= 9 and 2 <= y <= 9: return 5 # Surrounding blue area (Score 1) elif 1 <= x <= 10 and 1 <= y <= 10: return 1 else: return 0 # Calculate total score by summing the scores for all shots total_score = sum(calculate_score(x, y) for x, y in shots) return total_score
This image shows a 10 x 10 two-dimensional matrix with three different colored regions, each representing a specific score. Here are the regions with their top-left and bottom-right coordinates: - The innermost green area (Score: 10 points) has top-left coordinates at (4, 7) and bottom-right coordinates at (7, 4). - The second light pink area (Score: 5 points) has top-left coordinates at (2, 9) and bottom-right coordinates at (9, 2). - The outermost blue area (Score: 1 point) has top-left coordinates at (1, 10) and bottom-right coordinates at (10, 1).
def test(): test_cases = [ ([(1, 1), (3, 3)], 6), ([(2, 2), (4, 4)], 15), ([(5, 5), (6, 6), (4, 4), (7, 7), (3, 3)], 45), ([(7, 8), (3, 2), (5, 5), (6, 6)], 30), ([], 0), ([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10)], 62), ([(5, 6), (6, 5), (5, 5), (6, 6)], 40), ([(5, 4), (6, 7), (3, 8), (8, 3)], 30), ([(5, 5), (6, 6), (4, 4), (7, 7), (3, 3)], 45), ([(5, 1), (6, 2), (4, 3), (7, 4), (3, 5)], 26) ] for points, expected in test_cases: result = solution(points) assert result == expected, f"Assert Error: Test failed for points {points}. Expected {expected}, got {result}" test()
from typing import List, Tuple def solution(shots: List[Tuple[int, int]]) -> int: """ Calculate the total score based on the shot locations and the areas, with points assigned according to the different colored areas on the grid. Args: shots: A list of tuples where each tuple contains the x and y coordinates of a shot. Returns: int: The total score calculated based on the shots in the grid. """
q5-3
from typing import List, Tuple def solution(shots: List[Tuple[int, int]]) -> int: """ Calculate the total score based on the shot locations and the areas, with points assigned according to the different colored areas on the grid. Args: shots: A list of tuples where each tuple contains the x and y coordinates of a shot. Returns: int: The total score calculated based on the shots in the grid. """ def calculate_score(x: int, y: int) -> int: # Central green area (Score 10) if 5 <= x <= 6 and 5 <= y <= 6: return 0 # Surrounding orange area (Score 5) elif 4 <= x <= 7 and 4 <= y <= 7: return 10 # Surrounding blue area (Score 1) elif 3 <= x <= 8 and 3 <= y <= 8: return 1 elif 2 <= x <= 9 and 2 <= y <= 9: return 10 elif 1 <= x <= 10 and 1 <= y <= 10: return 5 else: return 0 # Calculate total score by summing the scores for all shots total_score = sum(calculate_score(x, y) for x, y in shots) return total_score
This image shows a 10 x 10 two-dimensional matrix, with each layer having a different color and corresponding score. Here are the color regions with their top-left and bottom-right coordinates: - The innermost green area (Score: 0 points) has top-left coordinates at (5, 6) and bottom-right coordinates at (6, 5). - The second gray area (Score: 10 points) has top-left coordinates at (4, 7) and bottom-right coordinates at (7, 4). - The third light pink area (Score: 1 point) has top-left coordinates at (3, 8) and bottom-right coordinates at (8, 3). - The fourth gray area (Score: 10 points) has top-left coordinates at (2, 9) and bottom-right coordinates at (9, 2). - The outermost blue area (Score: 5 points) has top-left coordinates at (1, 10) and bottom-right coordinates at (10, 1).
def test(): test_cases = [ ([(1, 1), (3, 3)], 6), ([(2, 2), (4, 4)], 20), ([(5, 5), (6, 6), (4, 4), (7, 7), (3, 3)], 21), ([(7, 8), (3, 2), (5, 5), (6, 6)], 11), ([], 0), ([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10)], 52), ([(5, 6), (6, 5), (5, 5), (6, 6)], 0), ([(5, 4), (6, 7), (3, 8), (8, 3)], 22), ([(5, 5), (6, 6), (4, 4), (7, 7), (3, 3)], 21), ([(5, 1), (6, 2), (4, 3), (7, 4), (3, 5)], 27) ] for points, expected in test_cases: result = solution(points) assert result == expected, f"Assert Error: Test failed for points {points}. Expected {expected}, got {result}" test()
from typing import List, Tuple def solution(shots: List[Tuple[int, int]]) -> int: """ Calculate the total score based on the shot locations and the areas, with points assigned according to the different colored areas on the grid. Args: shots: A list of tuples where each tuple contains the x and y coordinates of a shot. Returns: int: The total score calculated based on the shots in the grid. """
q6
from typing import List def solution(N: int) -> List[str]: """ Generates a character matrix of size N x N based on the pattern shown in the image. Parameters: N (int): The size of the matrix (both the number of rows and columns). Returns: List[str]: The generated character matrix, where each row is a string. """ matrix = [] for i in range(N * 2): row = [] for j in range(N * 2): if (i // 2 + j // 2) % 2 == 0: row.append('+') else: row.append('-') matrix.append(''.join(row)) return matrix
This image shows three matrices of different sizes, each corresponding to a different value of N, and each 2x2 sub-square contains the same symbol. - When N = 1, the matrix is a 2x2 square, and all the cells contain the "+" symbol. - When N = 2, the matrix is a 4x4 square, with the symbols alternating between "+" and "-". - When N = 3, the matrix is a 6x6 square, and similarly, the "+" and "-" symbols alternate, forming a larger pattern. The size of each matrix increases as N increases, and the pattern of symbol arrangement remains consistent.
def test(): test_cases = [ (1, ['++', '++']), (2, ['++--', '++--', '--++', '--++']), (3, ['++--++', '++--++', '--++--', '--++--', '++--++', '++--++']), (4, ['++--++--', '++--++--', '--++--++', '--++--++', '++--++--', '++--++--', '--++--++', '--++--++']), (5, ['++--++--++', '++--++--++', '--++--++--', '--++--++--', '++--++--++', '++--++--++', '--++--++--', '--++--++--', '++--++--++', '++--++--++']) ] for n, expected in test_cases: result = solution(n) assert result == expected, f"Assert Error: Test failed for n {n}. Expected {expected}, got {result}" test()
from typing import List def solution(N: int) -> List[str]: """ Generates a character matrix of size N x N based on the pattern shown in the image. Parameters: N (int): The size of the matrix (both the number of rows and columns). Returns: List[str]: The generated character matrix, where each row is a string. """
q6-2
from typing import List def solution(N: int) -> List[str]: """ Generates a character matrix of size N x N based on the pattern shown in the image. Parameters: N (int): The size of the matrix (both the number of rows and columns). Returns: List[str]: The generated character matrix, where each row is a string. """ matrix = [] for i in range(N * 2): row = [] for j in range(N * 2): if (i // 2 + j // 2) % 2 == 0: row.append('-') else: row.append('+') matrix.append(''.join(row)) return matrix
This image shows three matrices of different sizes, each corresponding to a different value of N, and each 2x2 sub-square contains the same symbol. - When N = 1, the matrix is a 2x2 square, and all the cells contain the "-" symbol. - When N = 2, the matrix is a 4x4 square, with the symbols alternating between "+" and "-". - When N = 3, the matrix is a 6x6 square, and similarly, the "+" and "-" symbols alternate, forming a larger pattern. The size of each matrix increases as N increases, and the pattern of symbol arrangement remains consistent.
def test(): test_cases = [ (1, ['--', '--']), (2, ['--++', '--++', '++--', '++--']), (3, ['--++--', '--++--', '++--++', '++--++', '--++--', '--++--']), (4, ['--++--++', '--++--++', '++--++--', '++--++--', '--++--++', '--++--++', '++--++--', '++--++--']), (5, ['--++--++--', '--++--++--', '++--++--++', '++--++--++', '--++--++--', '--++--++--', '++--++--++', '++--++--++', '--++--++--', '--++--++--']) ] for n, expected in test_cases: result = solution(n) assert result == expected, f"Assert Error: Test failed for n {n}. Expected {expected}, got {result}" test()
from typing import List def solution(N: int) -> List[str]: """ Generates a character matrix of size N x N based on the pattern shown in the image. Parameters: N (int): The size of the matrix (both the number of rows and columns). Returns: List[str]: The generated character matrix, where each row is a string. """
q6-3
from typing import List def solution(N: int) -> List[str]: """ Generates a character matrix of size N x N based on the pattern shown in the image. Parameters: N (int): The size of the matrix (both the number of rows and columns). Returns: List[str]: The generated character matrix, where each row is a string. """ matrix = [] for i in range(N * 3): row = [] for j in range(N * 3): if (i // 3 + j // 3) % 2 == 0: row.append('+') else: row.append('-') matrix.append(''.join(row)) return matrix
This image shows three matrices of different sizes, each corresponding to a different value of N, and each 3x3 sub-square contains the same symbol. - When N = 1, the matrix is a 3x3 square, and all the cells contain the "+" symbol. - When N = 2, the matrix is a 6x6 square, with the symbols alternating between "+" and "-". - When N = 3, the matrix is a 9x9 square, and similarly, the "+" and "-" symbols alternate, forming a larger pattern. The size of each matrix increases as N increases, and the pattern of symbol arrangement remains consistent.
def test(): test_cases = [ (1, ['+++', '+++', '+++']), (2, ['+++---', '+++---', '+++---', '---+++', '---+++', '---+++']), (3, ['+++---+++', '+++---+++', '+++---+++', '---+++---', '---+++---', '---+++---', '+++---+++', '+++---+++', '+++---+++']), (4, ['+++---+++---', '+++---+++---', '+++---+++---', '---+++---+++', '---+++---+++', '---+++---+++', '+++---+++---', '+++---+++---', '+++---+++---', '---+++---+++', '---+++---+++', '---+++---+++']), (5, ['+++---+++---+++', '+++---+++---+++', '+++---+++---+++', '---+++---+++---', '---+++---+++---', '---+++---+++---', '+++---+++---+++', '+++---+++---+++', '+++---+++---+++', '---+++---+++---', '---+++---+++---', '---+++---+++---', '+++---+++---+++', '+++---+++---+++', '+++---+++---+++']) ] for n, expected in test_cases: result = solution(n) assert result == expected, f"Assert Error: Test failed for n {n}. Expected {expected}, got {result}" test()
from typing import List def solution(N: int) -> List[str]: """ Generates a character matrix of size N x N based on the pattern shown in the image. Parameters: N (int): The size of the matrix (both the number of rows and columns). Returns: List[str]: The generated character matrix, where each row is a string. """
q7
from typing import Tuple def solution(line1: Tuple[int, int], line2: Tuple[int, int]) -> bool: """ Determines if two line segments intersect within the circle. Parameters: line1: A tuple containing the numbers at both ends of the first line segment. line2: A tuple containing the numbers at both ends of the second line segment. Returns: bool: True if the line segments intersect, False otherwise. """ mapping = { 1: 1, 2: 3, 3: 2, 4: 5, 5: 4, 6: 7, 7: 6, 8: 8 } line1 = tuple(mapping[x] for x in line1) line2 = tuple(mapping[x] for x in line2) a, b = sorted(line1) c, d = sorted(line2) # Check if the points (a, b) and (c, d) intersect on the circle return (a < c < b < d) or (c < a < d < b)
This image shows a circle with numbers 1 to 8 marked, representing 8 evenly spaced points. The numbers, arranged clockwise, are 8, 1, 3, 2, 5, 4, 7, 6. Two diagonal line segments connect different points on the circumference: - The blue line connects point 8 and point 2. - The orange line connects point 1 and point 5. These lines intersect inside the circle.
def test(): test_cases = [ ((3, 7), (1, 5), True), ((2, 8), (1, 3), False), ((2, 8), (5, 8), False), ((3, 6), (1, 8), False), ((1, 4), (5, 8), True), ((1, 6), (2, 8), True), ((3, 7), (2, 4), False), ((1, 7), (3, 2), False), ((1, 8), (3, 2), False), ((1, 6), (3, 8), True) ] for line1, line2, expected in test_cases: result = solution(line1, line2) assert result == expected, f"Assert Error: Test failed for lines {line1} and {line2}. Expected {expected}, got {result}" test()
from typing import Tuple def solution(line1: Tuple[int, int], line2: Tuple[int, int]) -> bool: """ Determines if two line segments intersect within the circle. Parameters: line1: A tuple containing the numbers at both ends of the first line segment. line2: A tuple containing the numbers at both ends of the second line segment. Returns: bool: True if the line segments intersect, False otherwise. """