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. """

HumanEval-V: Evaluating Visual Understanding and Reasoning Abilities of LMMs Through Coding Tasks

πŸ“„ Paper β€’ 🏠 Home Page β€’ πŸ’» GitHub Repository β€’ πŸ† Leaderboard β€’ πŸ€— Dataset Viewer

HumanEval-V includes 108 carefully crafted, entry-level Python coding tasks. LMMs are required to complete the code solution based on the provided visual context and a predefined Python function signature outlining the task requirements. Every task is equipped with meticulously handcrafted test cases for execution-based pass@k evaluation.

Dataset Structure

Each task in the dataset consists of the following fields:

  • qid: Unique identifier for each coding task (e.g., q1, with mutated versions like q1-2, q1-3).
  • image: A single image containing the essential visual context necessary to solve the task.
  • function_signature: Includes the problem description, necessary imports, and the function signature that the LMMs must complete.
  • test_script: Test cases used to validate the correctness of the generated code.
  • ground_truth_solution: Expert-crafted solutions provided for reference but not used during the evaluation process.
  • image_description: Human-labeled descriptions of the images, used for experimental analysis (not part of the benchmark evaluation).

Prompt Format

Each task is formatted with a clear instruction and provided function signature to guide the model in generating the code solution:

**Instructions:**
You are an exceptionally intelligent coding assistant that consistently delivers accurate and reliable responses to user instructions.
Please complete the function based on the provided image and code context. Return the complete solution, including the function signature, in a single response, formatted within a Python code block.

**Code Context:**
```python
{code_context}
```

After the LMM generates a response, the code solution is extracted and validated using the following process:

  • Extraction of content within the code block.
  • Parsing the generated code to detect imports, class definitions, and functions using an Abstract Syntax Tree (AST) parser.
  • Concatenation of these components to form the final predicted solution, which is then tested for correctness.
  • Generated code solution is evaluated through an execution-based metric, specifically pass@k.

Usage

You can easily load the dataset using the Hugging Face datasets library.

from datasets import load_dataset
humaneval_v = load_dataset("HumanEval-V/HumanEval-V-Benchmark", split="test")

Citation

@article{zhang2024humanevalv,
  title={HumanEval-V: Evaluating Visual Understanding and Reasoning Abilities of Large Multimodal Models Through Coding Tasks}, 
  author={Zhang, Fengji and Wu, Linquan and Bai, Huiyu and Lin, Guancheng and Li, Xiao and Yu, Xiao and Wang, Yue and Chen, Bei and Keung, Jacky},
  journal={arXiv preprint arXiv:2410.12381},
  year={2024},
}
Downloads last month
50
Edit dataset card

Space using HumanEval-V/HumanEval-V-Benchmark 1