version
stringclasses
1 value
style
stringclasses
2 values
subset
stringclasses
12 values
question_id
stringlengths
9
23
question
stringlengths
27
8.13k
solution
stringlengths
99
5.97k
test
stringlengths
105
4.45k
test_info
listlengths
0
13
gpt_pass_sequence
listlengths
1
10
gpt_pass_trial_num
int64
1
10
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
trials
dict
chosen_trial
stringclasses
10 values
metadata
dict
benchmark_similarity
float64
0.16
0.93
benchmark_instruction
stringclasses
1 value
benchmark_task_id
stringclasses
1 value
filter_reason
stringclasses
1 value
base_id
stringlengths
7
21
variant
stringclasses
2 values
top_function_names
listlengths
2
13
n_top_functions
int64
2
13
helper_call_edges
listlengths
1
16
n_helper_call_edges
int64
1
16
harness_functions
listlengths
0
3
structural_wrapper
bool
1 class
class_names
listlengths
0
5
has_class
bool
2 classes
test_kind
stringclasses
1 value
test_has_solution_import
bool
2 classes
third_party_imports
listlengths
0
5
stdlib_only
bool
2 classes
question_norm_sha1
stringlengths
40
40
solution_ast_sha1
stringlengths
40
40
v1.0
instruct
Data_Structure
Data_Structure_44310_I
### Scenario You are working on a project handling large datasets related to user permissions. Each user's permissions are represented as a 32-bit integer where each bit signifies the presence (1) or absence (0) of a specific permission. Efficiently manipulating these bits is crucial for your application’s performance....
def get_permission(user_permissions: int, permission_index: int) -> int: """ Returns whether the user has a specific permission (0 or 1). """ return (user_permissions >> permission_index) & 1 def grant_permission(user_permissions: int, permission_index: int) -> int: """ Grants a specific permis...
import pytest from solution import get_permission, grant_permission, revoke_permission, update_permission def test_get_permission(): assert get_permission(0b10101010, 3) == 1 assert get_permission(0b10101010, 1) == 1 assert get_permission(0b10101010, 2) == 0 assert get_permission(0b00000000, 0) == 0 d...
[ { "docstring": "Returns whether the user has a specific permission (0 or 1).", "function_declaration": "def get_permission(user_permissions, permission_index):", "function_name": "get_permission", "parameter_list": "(user_permissions, permission_index)" }, { "docstring": "Grants a specific p...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def get_permission(user_permissions: int, permission_index: int) -> int:\n \"\"\"\n Returns whether the user has a specific permission (0 or 1) based on...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044310", "row_id": 44310, "seed_ids": "[212]" }
0.492745
Data_Structure_44310
I
[ "get_permission", "grant_permission", "revoke_permission", "update_permission" ]
4
[ [ "update_permission", "grant_permission" ], [ "update_permission", "revoke_permission" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d010f5bff069473e6d0b95efe76f1602efd11c00
0ccc76f4aff0a159243a993e3e8c29cb59480017
v1.0
instruct
Data_Structure
Data_Structure_44341_I
### Radix Sort Implementation **Objective**: Implement a function for the Radix Sort algorithm that sorts an array of non-negative integers in ascending order. This function should allow an optional simulation mode that outputs each iteration's result. **Function Signature**: ```python def radix_sort(arr: List[int], ...
from typing import List def counting_sort(arr: List[int], exp: int, simulation: bool) -> None: n = len(arr) output = [0] * n count = [0] * 10 # Store count of occurrences in count[] for i in range(n): index = (arr[i] // exp) % 10 count[index] += 1 # Change count[i] so that...
from solution import radix_sort def test_small_list(): assert radix_sort([3, 2, 1]) == [1, 2, 3] assert radix_sort([5, 3, 8, 6]) == [3, 5, 6, 8] def test_single_element_list(): assert radix_sort([1]) == [1] def test_empty_list(): assert radix_sort([]) == [] def test_large_numbers(): asse...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp, simulation):", "function_name": "counting_sort", "parameter_list": "(arr, exp, simulation)" }, { "docstring": null, "function_declaration": "def radix_sort(arr, simulation=False):", "function_name": "radix_sort...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool) -> None:\n n = len(arr)\n output = [0] * n\n count = [0] * 1...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00044341", "row_id": 44341, "seed_ids": "[15]" }
0.648499
Data_Structure_44341
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2fbfcaf88ae12d5fad8780b17523cd71e463333b
301b626415e13af782fbb294b8d8bdae1fff18ab
v1.0
instruct
Data_Structure
Data_Structure_44399_I
### Context A company is developing a predictive typing feature where, based on the last word typed by a user, the system suggests the next word. The predictive typing algorithm employs a Markov Chain model. You have been tasked to expand this functionality by allowing the system to generate a sequence of words based o...
import random def __choose_state(state_map): """ Helper function that randomly selects the next state based on given probabilities. """ states = list(state_map.keys()) probabilities = list(state_map.values()) next_state = random.choices(states, probabilities)[0] return next_state def next_...
from solution import __choose_state, next_state, predictive_typing def test__choose_state(): state_map = {'A': 0.7, 'B': 0.3} a_count = b_count = 0 for _ in range(1000): result = __choose_state(state_map) if result == 'A': a_count += 1 elif result == 'B': b_c...
[ { "docstring": "Helper function that randomly selects the next state based on given probabilities.", "function_declaration": "def __choose_state(state_map):", "function_name": "__choose_state", "parameter_list": "(state_map)" }, { "docstring": "Retrieves the next state using the chain and th...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef __choose_state(state_map: dict) -> str:\n \"\"\"\n Helper function to randomly select the next state based on given probabilities.\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044399", "row_id": 44399, "seed_ids": "[232]" }
0.525321
Data_Structure_44399
I
[ "__choose_state", "next_state", "predictive_typing" ]
3
[ [ "next_state", "__choose_state" ], [ "predictive_typing", "next_state" ] ]
2
[]
false
[]
false
pytest
true
[]
true
06e34405f6c5edd31382a3b52db0ec29c9419176
eff5bc33045eea23b3ad3823c02a25ba96d7c51d
v1.0
instruct
Data_Structure
Data_Structure_44425_I
### Subtree Check in Binary Trees Given two binary trees, `big_tree` and `small_tree`, determine if `small_tree` is a subtree of `big_tree`. A subtree of `big_tree` is defined as any node in `big_tree` and all of its descendants in `big_tree` that match exactly with `small_tree`. #### Input Format * The input will co...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_subtree(big_tree: TreeNode, small_tree: TreeNode) -> bool: if not small_tree: return True if not big_tree: return False if is_same_tre...
from solution import TreeNode, is_subtree def test_is_subtree_example1(): # Example 1 big_tree = TreeNode(3, TreeNode(4, TreeNode(1), TreeNode(2)), TreeNode(5)) small_tree = TreeNode(4, TreeNode(1), TreeNode(2)) assert is_subtree(big_tree, small_tree) == True def test_is_subtree_example2(): # Exam...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00044425", "row_id": 44425, "seed_ids": "[288]" }
0.56124
Data_Structure_44425
I
[ "is_subtree", "is_same_tree" ]
2
[ [ "is_subtree", "is_same_tree" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
a7aef10eeac5c3aa38db393aa46f6afb3ba551e8
2f4478bfa67cc26da31bef635a06222d14a18aea
v1.0
instruct
Data_Structure
Data_Structure_44442_I
### Coding Challenge: Implement Iterative Merge Sort #### Problem Statement: Implement an iterative version of the merge sort algorithm. The iterative approach uses a bottom-up methodology (non-recursive) to sort an array. This will help save space compared to the recursive method. #### Input: - An unsorted list of i...
from typing import List def merge(arr: List[int], l: int, m: int, r: int): n1 = m - l + 1 n2 = r - m # Create temporary arrays L = arr[l:m+1] R = arr[m+1:r+1] i = 0 j = 0 k = l while i < n1 and j < n2: if L[i] <= R[j]: arr[k] = L[i] i +...
from solution import iterative_merge_sort def test_iterative_merge_sort(): assert iterative_merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] assert iterative_merge_sort([1]) == [1] assert iterative_merge_sort([]) == [] assert iterative_merge_sort([10, -1, 2, 5, 0]) == [-1, 0, 2, 5, ...
[ { "docstring": null, "function_declaration": "def merge(arr, l, m, r):", "function_name": "merge", "parameter_list": "(arr, l, m, r)" }, { "docstring": null, "function_declaration": "def iterative_merge_sort(arr):", "function_name": "iterative_merge_sort", "parameter_list": "(arr...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge(arr, temp_arr, left, mid, right):\n i = left # Starting index for left subarray\n j = mid + 1 # Starting index for right subarray\n k = ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044442", "row_id": 44442, "seed_ids": "[12]" }
0.601617
Data_Structure_44442
I
[ "merge", "iterative_merge_sort" ]
2
[ [ "iterative_merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0d07d754d6351b0569e19e08cfb0234e8ca22ae6
a5d742fc6720ca68a4ae16573413de1fb313bea8
v1.0
instruct
Data_Structure
Data_Structure_44475_I
### Question: Matrix Inversion You are required to implement a function `invert_matrix` that inverts a given n x n matrix using linear algebra principles. #### Function Signature: ```python def invert_matrix(m: List[List[float]]) -> List[List[float]]: pass ``` #### Input: - `m`: A list of lists representing an ...
from typing import List def determinant(matrix: List[List[float]], n: int) -> float: if n == 1: return matrix[0][0] if n == 2: return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0] det = 0 sign = 1 for i in range(n): sub_matrix = [] for j in range(1,...
def test_invalid_matrix_not_square(): assert invert_matrix([[1, 2, 3], [4, 5, 6]]) == [[-1]] assert invert_matrix([[1, 2], [3, 4], [5, 6]]) == [[-1]] def test_invalid_matrix_singular(): assert invert_matrix([[1, 2], [2, 4]]) == [[-4]] def test_invert_matrix_2x2(): matrix = [[4, 7], [2, 6]] expecte...
[ { "docstring": null, "function_declaration": "def determinant(matrix, n):", "function_name": "determinant", "parameter_list": "(matrix, n)" }, { "docstring": null, "function_declaration": "def get_cofactor(matrix, p, q, n):", "function_name": "get_cofactor", "parameter_list": "(m...
[ 0, 0, 0, 1, 1, 1, 0, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def invert_matrix(m):\n \"\"\"\n Function to invert a given n x n matrix.\n \"\"\"\n n = len(m)\n # Check for non-square matrix\n if any(len...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00044475", "row_id": 44475, "seed_ids": "[347]" }
0.592713
Data_Structure_44475
I
[ "determinant", "get_cofactor", "adjoint", "invert_matrix" ]
4
[ [ "adjoint", "determinant" ], [ "adjoint", "get_cofactor" ], [ "invert_matrix", "adjoint" ], [ "invert_matrix", "determinant" ] ]
4
[]
false
[]
false
pytest
false
[]
true
f4b288d862661e02daf71d169c233df175bdbe82
087cc511e01fce6d8cf38aabb1ebd503ef3e9895
v1.0
instruct
Data_Structure
Data_Structure_44501_I
### Maximum Flow in a Network with Capacity Scaling In network theory, finding the maximum flow through a network is a common problem with applications in various domains, such as traffic flow management and data routing. In this problem, you will implement a more advanced version of the Ford-Fulkerson method that opt...
def bfs(residual_graph, source, sink, parent): """ Breadth-First Search that also stores the path in parent list. Returns True if there's a path from source to sink. """ visited = [False] * len(residual_graph) queue = [source] visited[source] = True while queue: u = queue.pop(0)...
from solution import maximum_flow_capacity_scaling def test_example_case(): graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] assert maximum_flow_capacity_scaling(graph) ==...
[ { "docstring": "Breadth-First Search that also stores the path in parent list.\nReturns True if there's a path from source to sink.", "function_declaration": "def bfs(residual_graph, source, sink, parent):", "function_name": "bfs", "parameter_list": "(residual_graph, source, sink, parent)" }, { ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef bfs_with_capacity_scaling(residual_graph, source, sink, scale):\n \"\"\"\n Performs BFS to find augmenting path wit...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00044501", "row_id": 44501, "seed_ids": "[229]" }
0.633599
Data_Structure_44501
I
[ "bfs", "maximum_flow_capacity_scaling" ]
2
[ [ "maximum_flow_capacity_scaling", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
85975e48109eaa013a2c9b9cc89e2e3ef53f0876
cf69a429a124e76df3941ca04a61cf700cd19266
v1.0
instruct
Data_Structure
Data_Structure_44516_I
#### Problem Context In certain ancient cultures, number properties were often used for determining luck or prophecy. One such property is the concept of a "Magic Number". A number is said to be a magic number if summing the digits of the number and then recursively repeating this process for the resultant sum until ...
def is_magic_number(n): """ Helper function to determine if a number is a magic number. """ while n >= 10: n = sum(int(digit) for digit in str(n)) return n == 1 def find_magic_numbers(numbers): """ Returns a list of magic numbers from the given list. """ return [number for n...
from solution import find_magic_numbers def test_find_magic_numbers_all_magic(): assert find_magic_numbers([50113, 1234, 199]) == [50113, 1234, 199] def test_find_magic_numbers_some_magic(): assert find_magic_numbers([50113, 1234, 199, 111, 45]) == [50113, 1234, 199] def test_find_magic_numbers_no_magic(): ...
[ { "docstring": "Helper function to determine if a number is a magic number.", "function_declaration": "def is_magic_number(n):", "function_name": "is_magic_number", "parameter_list": "(n)" }, { "docstring": "Returns a list of magic numbers from the given list.", "function_declaration": "...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_magic_numbers(numbers):\n \"\"\"\n Determine which numbers in the given list are magic numbers.\n \n A number is a magic number if the su...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00044516", "row_id": 44516, "seed_ids": "[132]" }
0.567131
Data_Structure_44516
I
[ "is_magic_number", "find_magic_numbers" ]
2
[ [ "find_magic_numbers", "is_magic_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
63a0029a158a76d51d35456dbe6b330fd1f6b11f
760af24f26f225cbca2ceb72d86c512145b1716e
v1.0
instruct
Data_Structure
Data_Structure_44534_I
### Context Insertion Sort is a simple yet inefficient algorithm for sorting small lists. An efficient variant involves using binary search to find the correct position for insertion. You are required to implement this variant using the provided helper function `search_insert`. ### Problem Write a function `binary_ins...
from typing import List def search_insert(sorted_arr: List[int], value: int) -> int: """ Utility function to find the index at which `value` should be inserted in `sorted_arr` to keep it sorted. This uses binary search for efficiency. """ left, right = 0, len(sorted_arr) while left < right: ...
from solution import binary_insertion_sort def test_empty_list(): assert binary_insertion_sort([]) == [] def test_single_element(): assert binary_insertion_sort([1]) == [1] def test_sorted_list(): assert binary_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_list(): assert...
[ { "docstring": "Utility function to find the index at which `value` should be inserted in `sorted_arr`\nto keep it sorted. This uses binary search for efficiency.", "function_declaration": "def search_insert(sorted_arr, value):", "function_name": "search_insert", "parameter_list": "(sorted_arr, valu...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef search_insert(sorted_list: List[int], target: int) -> int:\n \"\"\"\n Perform a binary search to find the index at which ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044534", "row_id": 44534, "seed_ids": "[199]" }
0.615042
Data_Structure_44534
I
[ "search_insert", "binary_insertion_sort" ]
2
[ [ "binary_insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7532773a562975e666e5a7fa9fb754050d1d9aca
8391e30da93ba1cb05ac8d7b3aa713d776fbdf01
v1.0
instruct
Data_Structure
Data_Structure_44535_I
You have been provided with the implementation of the nearest neighbor algorithm, which classifies a given input vector based on the closest training data point. The Euclidean distance measure is used to determine the closeness of the input vector to each training point. **Your task is to extend the functionality to i...
import math from collections import Counter def euclidean_distance(point1, point2): """ Calculate the Euclidean distance between two points. """ return math.sqrt(sum((a - b) ** 2 for a, b in zip(point1, point2))) def k_nearest_neighbors(x, tSet, k): """ Classify the input vector `x` by conside...
from solution import k_nearest_neighbors def test_k_nearest_neighbors_basic(): training_set = { (2.0, 3.0): 'A', (1.0, 1.0): 'B', (1.5, 2.5): 'B', (4.0, 4.0): 'A', (3.0, 3.5): 'A' } x = (1.0, 2.0) k = 2 assert k_nearest_neighbors(x, training_set, k) == 'B' d...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import Counter\nimport math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points.\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044535", "row_id": 44535, "seed_ids": "[260]" }
0.67562
Data_Structure_44535
I
[ "euclidean_distance", "k_nearest_neighbors" ]
2
[ [ "k_nearest_neighbors", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fdd0232309a1b3647641f1632af07d1624f5b940
f3954b11079b153d2dae5c25a55634e0bd6133c0
v1.0
instruct
Data_Structure
Data_Structure_44546_I
### Strobogrammatic Number Generation Given an integer n, write a function `generate_strobogrammatic_numbers(n)` that generates all strobogrammatic numbers of length n. Additionally, write a function `count_strobogrammatic_in_range(low, high)` that returns the count of strobogrammatic numbers within the given range a...
from typing import List def generate_strobogrammatic_numbers(n: int) -> List[str]: def helper(m, n): if m == 0: return [""] if m == 1: return ["0", "1", "8"] prev = helper(m - 2, n) result = [] for num in prev: if m != n: # Prevent numbers sta...
from solution import generate_strobogrammatic_numbers, count_strobogrammatic_in_range def test_generate_strobogrammatic_numbers_length_0(): assert generate_strobogrammatic_numbers(0) == [""] def test_generate_strobogrammatic_numbers_length_1(): assert sorted(generate_strobogrammatic_numbers(1)) == sorted(["0"...
[ { "docstring": null, "function_declaration": "def generate_strobogrammatic_numbers(n):", "function_name": "generate_strobogrammatic_numbers", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def count_strobogrammatic_in_range(low, high):", "function_name": "co...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def generate_strobogrammatic_numbers(n):\n \"\"\"\n Returns all strobogrammatic numbers of length n.\n \"\"\"\n if n == 0: \n return [\"\"]...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00044546", "row_id": 44546, "seed_ids": "[140]" }
0.552146
Data_Structure_44546
I
[ "generate_strobogrammatic_numbers", "count_strobogrammatic_in_range" ]
2
[ [ "count_strobogrammatic_in_range", "generate_strobogrammatic_numbers" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2aeaa75d16d84614abbb7529ae1eb0ef24d19ee4
d170b5d5242700731095d307771df69d36fe7a8d
v1.0
instruct
Data_Structure
Data_Structure_44586_I
You are tasked with implementing a variant of the Nearest Neighbor algorithm. Instead of using Euclidean distance, you will use Manhattan distance (also known as L1 distance). ### Scenario You are given a dataset of points where each point has a label, and a test point for which you need to determine the closest point...
def manhattan_distance(point1, point2): """ Computes the Manhattan distance between two points. Parameters: point1 (tuple): The first point. point2 (tuple): The second point. Returns: int: The Manhattan distance between the two points. """ return sum(abs(a - b) ...
from solution import nearest_neighbor_manhattan def test_single_point_data_set(): test_point = (3, 4) data_set = {(1, 2): 'A'} assert nearest_neighbor_manhattan(test_point, data_set) == 'A' def test_multiple_points_data_set(): test_point = (3, 4) data_set = { (1, 2): 'A', (5, 5): '...
[ { "docstring": "Computes the Manhattan distance between two points.\n\nParameters:\n point1 (tuple): The first point.\n point2 (tuple): The second point.\n\nReturns:\n int: The Manhattan distance between the two points.", "function_declaration": "def manhattan_distance(point1, point2):", "funct...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def nearest_neighbor_manhattan(test_point, data_set):\n \"\"\"\n Finds the nearest neighbor of test_point in data_set using Manhattan distance.\n\n P...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00044586", "row_id": 44586, "seed_ids": "[260]" }
0.685643
Data_Structure_44586
I
[ "manhattan_distance", "nearest_neighbor_manhattan" ]
2
[ [ "nearest_neighbor_manhattan", "manhattan_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
aa1845576d20519cf821b17386dfe1d772b9942b
72dcfd358604f728a930dd4cb37d777f0203ba54
v1.0
instruct
Data_Structure
Data_Structure_44656_I
### KMP Algorithm: Detect Substring Occurrences #### Objective Implement and optimize the KMP algorithm to search for all occurrences of a pattern within a given text. Your implementation should be efficient and correctly handle various edge cases. #### Function Signature ```python def knuth_morris_pratt(text: str, p...
from typing import List def build_pi_table(pattern: str) -> List[int]: """ Builds the partial match (pi) table for KMP algorithm. """ m = len(pattern) pi = [0] * m j = 0 for i in range(1, m): while j > 0 and pattern[i] != pattern[j]: j = pi[j - 1] if pattern...
from solution import knuth_morris_pratt def test_kmp_basic(): assert knuth_morris_pratt('hello there hero!', 'he') == [0, 7, 12] def test_kmp_repeating_pattern(): assert knuth_morris_pratt('abcabcabcabc', 'abc') == [0, 3, 6, 9] def test_kmp_overlapping_patterns(): assert knuth_morris_pratt('aaaaa', 'aa')...
[ { "docstring": "Builds the partial match (pi) table for KMP algorithm.", "function_declaration": "def build_pi_table(pattern):", "function_name": "build_pi_table", "parameter_list": "(pattern)" }, { "docstring": "Given two strings 'text' and 'pattern', return a list of starting indices in 't...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef knuth_morris_pratt(text: str, pattern: str) -> List[int]:\n if not pattern:\n return []\n \n def compute_lps_ta...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00044656", "row_id": 44656, "seed_ids": "[93]" }
0.615857
Data_Structure_44656
I
[ "build_pi_table", "knuth_morris_pratt" ]
2
[ [ "knuth_morris_pratt", "build_pi_table" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d7acb1f9bdc331656947388b66347cad9b92305a
6486764552cccd32e67523afa85b5693287cfa94
v1.0
instruct
Data_Structure
Data_Structure_44701_I
### Coding Problem: Radix Sort for Strings **Context**: Consider a scenario where you need to sort a large list of strings consisting of lowercase letters only. String sorting algorithms often face challenges due to variable lengths and the lexicographical order. Leveraging the principles of Radix Sort could be benefi...
from typing import List def counting_sort(arr: List[str], index: int) -> List[str]: """ A helper function for radix_sort_strings to perform a stable counting sort based on characters at a specific index. """ # Create a count array for 26 lowercase letters count = [0] * 26 output = ["" for _...
from solution import radix_sort_strings def test_radix_sort_strings_basic(): input_strings = ["bca", "acb", "abc", "cab", "bac"] k = 3 expected_output = ['abc', 'acb', 'bac', 'bca', 'cab'] assert radix_sort_strings(input_strings, k) == expected_output def test_radix_sort_strings_same_strings(): in...
[ { "docstring": "A helper function for radix_sort_strings to perform a stable counting sort\nbased on characters at a specific index.", "function_declaration": "def counting_sort(arr, index):", "function_name": "counting_sort", "parameter_list": "(arr, index)" }, { "docstring": "Sorts an arra...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef radix_sort_strings(arr: List[str], k: int) -> List[str]:\n \"\"\"\n Sort a list of strings using Radix Sort.\n \n A...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044701", "row_id": 44701, "seed_ids": "[15]" }
0.624936
Data_Structure_44701
I
[ "counting_sort", "radix_sort_strings" ]
2
[ [ "radix_sort_strings", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eca35b22f2a1ec1c50ff1e774f7baca4b1e5372d
2c1b0ebd2130bed5f32ac9676994ccd61b12bf55
v1.0
instruct
Data_Structure
Data_Structure_44745_I
**Context**: You work for a tech company that is developing a predictive text feature for a messaging app. To accurately predict the next word a user will type, you need to model the typing behavior using a Markov chain. You have a record of user behavior which reveals the probabilities of transitioning between words. ...
import random def next_state(chain: dict, current_state: str) -> str: """ Returns the next state given the current state based on the Markov chain transition probabilities. Parameters: - chain: Dictionary representing the Markov chain. - current_state: String representing the current state. ...
from solution import next_state, generate_sequence def test_next_state(): chain = { 'start': {'call': 0.5, 'meet': 0.5}, 'call': {'end': 1.0}, 'meet': {'talk': 0.8, 'end': 0.2}, 'talk': {'end': 1.0}, 'end': {} } random.seed(0) # Ensure reproducibility resul...
[ { "docstring": "Returns the next state given the current state based on the Markov chain transition probabilities.\n\nParameters:\n- chain: Dictionary representing the Markov chain.\n- current_state: String representing the current state.\n\nReturns:\n- String representing the next state.", "function_declar...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef next_state(chain: dict, current_state: str) -> str:\n \"\"\"\n Returns the next state given the current state based on the Markov c...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044745", "row_id": 44745, "seed_ids": "[232]" }
0.493568
Data_Structure_44745
I
[ "next_state", "generate_sequence" ]
2
[ [ "generate_sequence", "next_state" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f3e08328f2f03b180914929f84c6c8a001b0d871
087f949f406ff0f8da1d6c1a30070600533da01a
v1.0
instruct
Data_Structure
Data_Structure_44798_I
#### Context: You have been provided with the implementation for matrix inversion. Your task is to extend this functionality to handle different scenarios and ensure robustness. This function is critical for applications like solving linear equations, computer graphics, and systems modeling. #### Task: Implement a fun...
from typing import List, Union def determinant(matrix: List[List[float]]) -> float: n = len(matrix) if n == 1: return matrix[0][0] if n == 2: return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0] det = 0 for c in range(n): det += ((-1)**c) * matrix[0][c] * deter...
from solution import invertible_matrix_check def test_valid_invertible_matrix(): matrix = [ [4, 7], [2, 6] ] expected = [ [0.6, -0.7], [-0.2, 0.4] ] assert invertible_matrix_check(matrix) == expected def test_singular_matrix(): matrix = [ [1, 2], ...
[ { "docstring": null, "function_declaration": "def determinant(matrix):", "function_name": "determinant", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def minor(matrix, i, j):", "function_name": "minor", "parameter_list": "(matrix, i, j)" }, { ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Union\n\ndef determinant(matrix: List[List[float]]) -> float:\n n = len(matrix)\n if n == 1:\n return matrix[0][0]\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00044798", "row_id": 44798, "seed_ids": "[347]" }
0.611868
Data_Structure_44798
I
[ "determinant", "minor", "transpose", "inverse", "invertible_matrix_check" ]
5
[ [ "determinant", "minor" ], [ "inverse", "determinant" ], [ "inverse", "minor" ], [ "inverse", "transpose" ], [ "invertible_matrix_check", "inverse" ] ]
5
[]
false
[]
false
pytest
true
[]
true
1da7ef13a96051c220ce21d7bec9bfc69eb91f4a
cf1a05bc82916a435264a07cff461ef81785c879
v1.0
instruct
Data_Structure
Data_Structure_44809_I
### Scenario: You are tasked with implementing matrix operations as part of a larger scientific computing library. As a first step, you need to verify your understanding of matrix exponentiation using the provided matrix multiplication and identity matrix functions. ### Problem: Given a square matrix `mat` of dimensio...
def identity(d: int) -> list: """ Returns the identity matrix of dimension d x d. """ return [[1 if i == j else 0 for j in range(d)] for i in range(d)] def multiply(mat1: list, mat2: list) -> list: """ Multiplies two matrices mat1 and mat2. Returns the resulting matrix. """ d = len(...
from solution import matrix_exponentiation_optimized def test_identity_power(): mat = [ [1, 0], [0, 1] ] assert matrix_exponentiation_optimized(mat, 5) == mat def test_zero_power(): mat = [ [2, 3], [4, 5] ] expected = [ [1, 0], [0, 1] ] a...
[ { "docstring": "Returns the identity matrix of dimension d x d.", "function_declaration": "def identity(d):", "function_name": "identity", "parameter_list": "(d)" }, { "docstring": "Multiplies two matrices mat1 and mat2.\nReturns the resulting matrix.", "function_declaration": "def multi...
[ 0, 0, 0, 1, 1, 1, 0, 1, 0 ]
4
medium
0.444
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def multiply(mat1, mat2):\n d = len(mat1)\n res = [[0] * d for _ in range(d)]\n for i in range(d):\n for j in range(d):\n for k in ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00044809", "row_id": 44809, "seed_ids": "[340]" }
0.497665
Data_Structure_44809
I
[ "identity", "multiply", "matrix_exponentiation_optimized" ]
3
[ [ "matrix_exponentiation_optimized", "identity" ], [ "matrix_exponentiation_optimized", "multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9c5de69225b71a24d85fdfae78cd58f89d431ec9
6d791cfaec652e92ae74b0cfd060e63dcb6a2c51
v1.0
instruct
Data_Structure
Data_Structure_44968_I
### Scenario You are tasked with implementing the Merge Sort algorithm for a list of integers. As part of the implementation, you also need to provide a detailed check for edge cases and optimize the helper functions as necessary. ### Task Write a Python function `merge_sort(arr)` that sorts a list of integers using t...
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers using the Merge Sort algorithm. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left...
from solution import merge_sort def test_merge_sort(): assert merge_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5] assert merge_sort([6, 5, 6, 2, 1]) == [1, 2, 5, 6, 6] assert merge_sort([]) == [] assert merge_sort([1]) == [1] assert merge_sort([3, 3, 3, 3]) == [3, 3, 3, 3] assert merge_sort([-1, 0, ...
[ { "docstring": "Sorts a list of integers using the Merge Sort algorithm.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merges two sorted lists into one sorted list.", "function_declaration": "def merge(left, ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n def merge(left: List[int], right: Li...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044968", "row_id": 44968, "seed_ids": "[12]" }
0.616265
Data_Structure_44968
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c440d93ae91940ad5c634449597ae656f7a404a2
1eb18a4059c4c330e0c38cc28753d5ed33365b1e
v1.0
instruct
Data_Structure
Data_Structure_45057_I
### Question Write a function `fibonacci_matrix(n: int) -> int` that computes the nth Fibonacci number using matrix exponentiation. The nth Fibonacci number can be derived from the relation: \[ F(n) = \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^n \begin{bmatrix} 1 \\ 0 \end{bmatrix} \] Your task is to: 1. Implement a...
def matrix_multiply(A, B): """ Multiplies two 2x2 matrices A and B. """ return [[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]], [A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]] def matrix_power(matrix, n): """ Raises the...
from solution import fibonacci_matrix def test_fibonacci_zero(): assert fibonacci_matrix(0) == 0 def test_fibonacci_one(): assert fibonacci_matrix(1) == 1 def test_fibonacci_small(): assert fibonacci_matrix(2) == 1 assert fibonacci_matrix(3) == 2 assert fibonacci_matrix(4) == 3 assert fibonac...
[ { "docstring": "Multiplies two 2x2 matrices A and B.", "function_declaration": "def matrix_multiply(A, B):", "function_name": "matrix_multiply", "parameter_list": "(A, B)" }, { "docstring": "Raises the matrix to the power of n using exponentiation by squaring.", "function_declaration": "...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def matrix_mult(A, B):\n \"\"\"\n Multiplies two 2x2 matrices A and B.\n \"\"\"\n return [[A[0][0]*B[0][0] + A[0][1]*B[1][0], A[0][0]*B[0][1] + A[...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045057", "row_id": 45057, "seed_ids": "[340]" }
0.69004
Data_Structure_45057
I
[ "matrix_multiply", "matrix_power", "fibonacci_matrix" ]
3
[ [ "fibonacci_matrix", "matrix_power" ], [ "matrix_power", "matrix_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
027bc2baf4cb613352350a0dfb8abf35d25ac2e2
b039e25856c295821bcda638103505748c9a0570
v1.0
instruct
Data_Structure
Data_Structure_45065_I
### Word Search with Constraints #### Objective: You are given a 2D grid `board` consisting of letters and a list of words. Write a function `find_words_with_constraints(board: List[List[str]], words: List[str], n: int) -> List[str]` that returns all words from the list that can be constructed on the board. The words ...
from typing import List class TrieNode: def __init__(self): self.children = {} self.word = None class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for letter in word: if letter not in node.children: ...
from solution import find_words_with_constraints def test_find_words_with_constraints_basic(): board = [['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v']] words = ["oath", "pea", "eat", "rain"] n = 5 assert sorted(find_words_with_constrain...
[]
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.is_end_of_word = False\n\nclass Trie:\n def __init__(self):\n sel...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00045065", "row_id": 45065, "seed_ids": "[115]" }
0.683836
Data_Structure_45065
I
[ "find_words_with_constraints", "get_usage_count" ]
2
[ [ "find_words_with_constraints", "get_usage_count" ] ]
1
[]
false
[ "TrieNode", "Trie" ]
true
pytest
true
[]
true
ee5fd474d189c2642c62dd4f17e36a460ccac24a
551c49efae906769ab1d32447dd9665522c3d933
v1.0
instruct
Data_Structure
Data_Structure_45110_I
### Stooge Sort Implementation and Analysis Imagine you are a data scientist who has been provided with an archaic and theoretical sorting algorithm, Stooge Sort. You are tasked with writing the implementation and providing an analysis of its performance on various edge cases. #### Task: 1. Implement the Stooge Sort ...
import time def stoogesort(arr, l, h, performance_data=None): """ Sorts arr[l..h] using Stooge Sort algorithm. """ if l >= h: return # Compare arr[l] and arr[h] if performance_data is not None: performance_data['comparisons'] += 1 if arr[l] > arr[h]: arr[l], ar...
from solution import stoogesort, analyze_stoogesort_performance def test_stoogesort_basic(): arr = [3, 2, 1] stoogesort(arr, 0, len(arr) - 1) assert arr == [1, 2, 3] def test_stoogesort_single_element(): arr = [1] stoogesort(arr, 0, len(arr) - 1) assert arr == [1] def test_stoogesort_sorted_a...
[ { "docstring": "Sorts arr[l..h] using Stooge Sort algorithm.", "function_declaration": "def stoogesort(arr, l, h, performance_data=None):", "function_name": "stoogesort", "parameter_list": "(arr, l, h, performance_data=None)" }, { "docstring": null, "function_declaration": "def analyze_s...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\n\ndef stoogesort(arr, l, h):\n \"\"\"\n Sorts an array using the Stooge Sort algorithm.\n \n Parameters:\n arr (list): the list of...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045110", "row_id": 45110, "seed_ids": "[10]" }
0.55671
Data_Structure_45110
I
[ "stoogesort", "analyze_stoogesort_performance" ]
2
[ [ "analyze_stoogesort_performance", "stoogesort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1cdfccb1578e6b4044e639d123c07960e7b5d9f2
fe940e435abc9fce0fda3dfb36445fe9a64de262
v1.0
instruct
Data_Structure
Data_Structure_45134_I
### AVL Tree Maximum Height Challenge Your task is to complete the implementation of an AVL tree as laid out in the provided partial implementation. Specifically, you need to write a function `calculate_max_height` that computes the maximum height of the AVL tree after a series of insertions. ### Function to Implemen...
class TreeNode: def __init__(self, key): self.key = key self.height = 1 self.left = None self.right = None def get_height(node): if not node: return 0 return node.height def update_height(node): if node: node.height = 1 + max(get_height(node.left), get_h...
from solution import calculate_max_height def test_empty_tree(): assert calculate_max_height([]) == 0 def test_single_element(): assert calculate_max_height([10]) == 1 def test_balanced_tree(): assert calculate_max_height([10, 20, 30, 40, 50, 25]) == 3 def test_left_heavy_tree(): assert calculate_ma...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n self.height = 1\n\nclass AVLTr...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00045134", "row_id": 45134, "seed_ids": "[313]" }
0.572973
Data_Structure_45134
I
[ "get_height", "update_height", "get_balance", "right_rotate", "left_rotate", "insert", "compute_max_height", "calculate_max_height" ]
8
[ [ "calculate_max_height", "compute_max_height" ], [ "calculate_max_height", "insert" ], [ "get_balance", "get_height" ], [ "insert", "get_balance" ], [ "insert", "left_rotate" ], [ "insert", "right_rotate" ], [ "insert", "update_height"...
10
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
de5d889cfb94a9246a6d60d86246db5cbdec8626
7167ab76575e5c542978e61d803b484571288a6b
v1.0
instruct
Data_Structure
Data_Structure_45180_I
### Question: Matrix Manipulation Functions #### Context You are working on a project that involves image processing. Images in your system are represented as 2D matrices of pixels. You need to implement various transformations on these matrices, including rotating them and inverting their contents. #### Task Impleme...
from typing import List def rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]: """ Rotate the given matrix 90 degrees clockwise. """ return [list(row) for row in zip(*matrix[::-1])] def rotate_counterclockwise(matrix: List[List[int]]) -> List[List[int]]: """ Rotate the given matrix ...
import pytest from solution import rotate_clockwise, rotate_counterclockwise, bottom_left_invert, rotate_anticlockwise def test_rotate_clockwise(): assert rotate_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]] assert rotate_clockwise([[1]]) == [[1]] assert rotate_clockwis...
[ { "docstring": "Rotate the given matrix 90 degrees clockwise.", "function_declaration": "def rotate_clockwise(matrix):", "function_name": "rotate_clockwise", "parameter_list": "(matrix)" }, { "docstring": "Rotate the given matrix 90 degrees counterclockwise.", "function_declaration": "de...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Rotate the given matrix 90 degrees clockwise.\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00045180", "row_id": 45180, "seed_ids": "[337]" }
0.512133
Data_Structure_45180
I
[ "rotate_clockwise", "rotate_counterclockwise", "bottom_left_invert", "rotate_anticlockwise" ]
4
[ [ "rotate_anticlockwise", "rotate_counterclockwise" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9f44b409d05b0f18ec254249185be67d997b6845
2fffa3f7fae1b942451fdac3b230f3b5d6d7ab98
v1.0
instruct
Data_Structure
Data_Structure_45223_I
### Question Given the provided implementations of max heap sort and min heap sort algorithms, you are required to write a function that switches between the sorting algorithms based on user input. The function signature should be defined as follows: ```python def heap_sort_switch(arr, sort_type, simulation=False): ...
def max_heapify(arr, n, i, simulation): largest = i l = 2 * i + 1 r = 2 * i + 2 if l < n and arr[l] > arr[largest]: largest = l if r < n and arr[r] > arr[largest]: largest = r if largest != i: arr[i], arr[largest] = arr[largest], arr[i] if simulation: ...
from solution import heap_sort_switch def test_heap_sort_switch_max(): arr = [4, 10, 3, 5, 1] sorted_arr = heap_sort_switch(arr, 'max') assert sorted_arr == [1, 3, 4, 5, 10] def test_heap_sort_switch_min(): arr = [4, 10, 3, 5, 1] sorted_arr = heap_sort_switch(arr, 'min') assert sorted_arr == [...
[ { "docstring": null, "function_declaration": "def max_heapify(arr, n, i, simulation):", "function_name": "max_heapify", "parameter_list": "(arr, n, i, simulation)" }, { "docstring": null, "function_declaration": "def max_heap_sort(arr, simulation=False):", "function_name": "max_heap_...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def max_heapify(arr, n, i, simulation=False):\n largest = i\n l = 2 * i + 1\n r = 2 * i + 2\n\n if l < n and arr[l] > arr[largest]:\n large...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00045223", "row_id": 45223, "seed_ids": "[8]" }
0.608702
Data_Structure_45223
I
[ "max_heapify", "max_heap_sort", "min_heapify", "min_heap_sort", "heap_sort_switch" ]
5
[ [ "heap_sort_switch", "max_heap_sort" ], [ "heap_sort_switch", "min_heap_sort" ], [ "max_heap_sort", "max_heapify" ], [ "min_heap_sort", "min_heapify" ] ]
4
[]
false
[]
false
pytest
true
[]
true
dd6af5ad6b656e552773263f6f9128022c085451
b020e44727748da63818424f2f1751e7f6e035fe
v1.0
instruct
Data_Structure
Data_Structure_45240_I
### Diffie-Hellman Secure Key Exchange Simulation You are tasked with implementing a secure key exchange algorithm using the Diffie-Hellman method. The given code snippets include all the utility functions required to verify primes, compute Euler's Totient function, find primitive roots, and perform the key exchange i...
import random def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def power_mod(base, exp, mod): ...
from solution import secure_key_exchange def test_secure_key_exchange_valid_prime_and_primitive_root(): p = 23 a = 5 shared_key = secure_key_exchange(p, a) assert isinstance(shared_key, int) assert shared_key > 0 def test_secure_key_exchange_invalid_prime(): p = 15 a = 5 assert secure_...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def power_mod(base, exp, mod):", "function_name": "power_mod", "parameter_list": "(base, exp, mod)" }, { ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import Union\nimport random\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00045240", "row_id": 45240, "seed_ids": "[146]" }
0.517084
Data_Structure_45240
I
[ "is_prime", "power_mod", "find_primitive_root", "secure_key_exchange" ]
4
[ [ "find_primitive_root", "power_mod" ], [ "secure_key_exchange", "find_primitive_root" ], [ "secure_key_exchange", "is_prime" ], [ "secure_key_exchange", "power_mod" ] ]
4
[]
false
[]
false
pytest
true
[]
true
ea936d7cdae7cd30837cff1470a9c4e140d85a77
8fa6a91146ea821ec8667a8d80d7b8c273a43fb0
v1.0
instruct
Data_Structure
Data_Structure_45244_I
#### Context You work for a company developing a low-level hardware driver for a new communication device. This device relies on efficient bit manipulation to handle its numerous control flags effectively. Your task is to implement several functions that will set, clear, get, and update specific control flags represent...
def get_bit(num, i): """ Returns the bit value (0 or 1) at the specified index from the integer `num`. """ if i < 0 or i >= 32: raise ValueError("Index out of range") return (num >> i) & 1 def set_bit(num, i): """ Returns an integer with the bit at the specified index set to 1. ...
import pytest from solution import get_bit, set_bit, clear_bit, update_bit def test_get_bit(): assert get_bit(0b101, 0) == 1 assert get_bit(0b101, 1) == 0 assert get_bit(0b101, 2) == 1 with pytest.raises(ValueError): get_bit(0b101, 32) def test_set_bit(): assert set_bit(0b101, 1) == 0b111 ...
[ { "docstring": "Returns the bit value (0 or 1) at the specified index from the integer `num`.", "function_declaration": "def get_bit(num, i):", "function_name": "get_bit", "parameter_list": "(num, i)" }, { "docstring": "Returns an integer with the bit at the specified index set to 1.", "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def get_bit(num, i):\n \"\"\"\n Returns the bit value (0 or 1) at the specified index from the integer `num`.\n \"\"\"\n if i < 0 or i > 31:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045244", "row_id": 45244, "seed_ids": "[212]" }
0.558806
Data_Structure_45244
I
[ "get_bit", "set_bit", "clear_bit", "update_bit" ]
4
[ [ "update_bit", "clear_bit" ] ]
1
[]
false
[]
false
pytest
true
[]
true
892e3520e327c98416b1ca2aa208a8b232b40b66
4d619bd34c2efe4286ab1708ef7a334a467680a8
v1.0
instruct
Data_Structure
Data_Structure_45250_I
### Graph Cloning with Path Validation You are given an undirected graph representation using a class `UndirectedGraphNode` and a function `clone_graph` that can clone graphs. Your task is to enhance this cloning function with an additional feature: validate if a particular path exists in both the original and cloned ...
from typing import List, Optional, Tuple class UndirectedGraphNode: def __init__(self, label: int): self.label = label self.neighbors = [] def add_neighbor(self, node: 'UndirectedGraphNode'): self.neighbors.append(node) def clone_graph(node: Optional[UndirectedGraphNode]) -> Optional[...
from solution import UndirectedGraphNode, clone_and_validate_path def test_clone_and_validate_path_empty_graph(): assert clone_and_validate_path(None, [1, 2]) == (None, False) def test_clone_and_validate_path_simple_graph_valid_path(): node0 = UndirectedGraphNode(0) node1 = UndirectedGraphNode(1) node...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import Optional, List, Tuple\nfrom collections import deque\n\nclass UndirectedGraphNode:\n def __init__(self, label: int):\n self.label...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00045250", "row_id": 45250, "seed_ids": "[239]" }
0.557121
Data_Structure_45250
I
[ "clone_graph", "find_path", "clone_and_validate_path" ]
3
[ [ "clone_and_validate_path", "clone_graph" ], [ "clone_and_validate_path", "find_path" ] ]
2
[]
false
[ "UndirectedGraphNode" ]
true
pytest
true
[]
true
1151c314dc0566d34901b8a6334e7e9f28873266
e65d22c6a8961ee0e8732134a0cfb42bdc1edeb3
v1.0
instruct
Data_Structure
Data_Structure_45269_I
### Quick Sort Implementation with Edge Case Handling #### Scenario: You are developing a high-performance software system that frequently requires sorting datasets of various lengths and distributions. While Quick Sort is a strong candidate due to its average-case efficiency, you need to enhance it to reliably handle...
from random import randint def insertion_sort(arr, left, right): """Use insertion sort for smaller sub-arrays for efficiency.""" for i in range(left + 1, right + 1): key = arr[i] j = i - 1 while j >= left and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j...
from solution import enhanced_quick_sort def test_empty_array(): assert enhanced_quick_sort([]) == [] def test_single_element_array(): assert enhanced_quick_sort([3]) == [3] def test_sorted_array(): assert enhanced_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reversed_array(): assert enha...
[ { "docstring": "Use insertion sort for smaller sub-arrays for efficiency.", "function_declaration": "def insertion_sort(arr, left, right):", "function_name": "insertion_sort", "parameter_list": "(arr, left, right)" }, { "docstring": "Hoare partition scheme with a randomized pivot.", "fun...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef insertion_sort(arr, left, right):\n for i in range(left + 1, right + 1):\n key = arr[i]\n j = i - 1\n while j >= ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045269", "row_id": 45269, "seed_ids": "[25]" }
0.565789
Data_Structure_45269
I
[ "insertion_sort", "partition", "_quick_sort", "enhanced_quick_sort" ]
4
[ [ "_quick_sort", "insertion_sort" ], [ "_quick_sort", "partition" ], [ "enhanced_quick_sort", "_quick_sort" ] ]
3
[]
false
[]
false
pytest
true
[]
true
df5e231f65658efe94d5625220bd6ab17d96a94f
9ea5668c66505c48b25e932a79245dba9f3cff04
v1.0
instruct
Data_Structure
Data_Structure_45343_I
In this task, you are required to write a Python function that performs the Diffie-Hellman Key Exchange algorithm outlined above. You will implement both the key exchange and verification of the shared key. Make sure to handle all edge cases and possible errors. #### Function Signature ```python def diffie_hellman_key...
import random from sympy import isprime, primerange def is_primitive_root(a, p): required_set = set(num for num in range(1, p) if gcd(num, p) == 1) actual_set = set(pow(a, powers, p) for powers in range(1, p)) return required_set == actual_set def gcd(a, b): while b: a, b = b, a % b return...
from solution import diffie_hellman_key_exchange def test_diffie_hellman_key_exchange_valid_keys(): assert diffie_hellman_key_exchange(5, 23, False) == True def test_diffie_hellman_key_exchange_invalid_prime(): try: diffie_hellman_key_exchange(5, 21, False) assert False, "Expected ValueError" ...
[ { "docstring": null, "function_declaration": "def is_primitive_root(a, p):", "function_name": "is_primitive_root", "parameter_list": "(a, p)" }, { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstri...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, primerange\n\ndef is_primitive_root(a, p):\n required_set = set(num for num in range(1, p) if gcd(num, p) == 1)\n...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00045343", "row_id": 45343, "seed_ids": "[146]" }
0.521887
Data_Structure_45343
I
[ "is_primitive_root", "gcd", "diffie_hellman_key_exchange" ]
3
[ [ "diffie_hellman_key_exchange", "is_primitive_root" ], [ "is_primitive_root", "gcd" ] ]
2
[]
false
[]
false
pytest
true
[ "sympy" ]
false
34eef7d54b065d263307288229b97d42b18cbce7
8e7a8432229e35f845ddc2d866deac3b3f402ae6
v1.0
instruct
Data_Structure
Data_Structure_45374_I
#### Objective Implement a function that determines if two binary trees are structurally identical. Two binary trees are structurally identical if they have the same structure and nodes have the same values. #### Input/Output - **Input**: Two serialized strings representing two binary trees. - **Output**: A boolean va...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def deserialize(data: str) -> TreeNode: """ Decodes your encoded data to tree. """ if not data: return None nodes = iter(data.split()) root = TreeNode(next(nodes)) queu...
from solution import are_trees_identical def test_identical_trees(): serialized_tree1 = "1 2 # # 3 # #" serialized_tree2 = "1 2 # # 3 # #" assert are_trees_identical(serialized_tree1, serialized_tree2) == True def test_different_tree_structure(): serialized_tree1 = "1 2 # # 3 # #" serialized_tree2...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef deserialize(data):\n if not d...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00045374", "row_id": 45374, "seed_ids": "[330]" }
0.551678
Data_Structure_45374
I
[ "deserialize", "are_trees_identical" ]
2
[ [ "are_trees_identical", "deserialize" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
ff7e550ee0c96c26a51d83cc3f2cb445ac2e5e5b
b3cf650e0c1115a57e96336ae21fea38db52db92
v1.0
instruct
Data_Structure
Data_Structure_45426_I
### Objective Design and implement a class for polynomials that supports basic arithmetic operations and some advanced features. Your class should be able to handle monomials and perform polynomial operations such as addition, subtraction, multiplication, and division. ### Problem Statement Imagine you are working on ...
from fractions import Fraction from collections import defaultdict class Monomial: def __init__(self, vars, coeff=1): self.vars = {v: exp for v, exp in vars.items() if exp != 0} # Filter out zero exponents self.coeff = Fraction(coeff) def __mul__(self, other): assert isinstance(other,...
from solution import Monomial, Polynomial, gcd, lcm def test_monomial_multiplication(): mon1 = Monomial({1: 2, 2: 1}, 2) mon2 = Monomial({2: 3, 3: 1}, 3) result = mon1 * mon2 assert result == Monomial({1: 2, 2: 4, 3: 1}, 6) def test_polynomial_addition(): poly1 = Polynomial([Monomial({1: 1}, 2)]) ...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from math import prod\nfrom fractions import Fraction\nfrom collections import defaultdict\n\nclass Monomial:\n def __init__(self, variables, coefficient):...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045426", "row_id": 45426, "seed_ids": "[157]" }
0.565542
Data_Structure_45426
I
[ "gcd", "lcm" ]
2
[ [ "lcm", "gcd" ] ]
1
[]
false
[ "Monomial", "Polynomial" ]
true
pytest
true
[]
true
19968b1b114a5687fc2f3a295e79e335eedcec36
454d0c0d56d387ae24dcedb68ddc9a4feb340e1c
v1.0
instruct
Data_Structure
Data_Structure_45460_I
### Question: Implement RSA Key Pair Generation with Optimized Prime Testing. The RSA algorithm provided includes simple prime testing and modular inverse calculations which may not be efficient for large bit sizes. Your task is to enhance the RSA key generation function for improved performance. #### Part 1: Optimize...
import random def miller_rabin_test(n, k: int) -> bool: """ Miller-Rabin primality test. n: the number to be tested for primality k: number of testing rounds for accuracy Returns: True if n is likely prime, False if composite """ if n in (2, 3): return True if n <= 1 or n % 2 ==...
from solution import optimized_generate_key, miller_rabin_test, generate_large_prime, extended_gcd, modinv_optimized def test_miller_rabin_test(): assert miller_rabin_test(101, 5) == True assert miller_rabin_test(10, 5) == False def test_generate_large_prime(): prime = generate_large_prime(16) assert ...
[ { "docstring": "Miller-Rabin primality test.\nn: the number to be tested for primality\nk: number of testing rounds for accuracy\nReturns: True if n is likely prime, False if composite", "function_declaration": "def miller_rabin_test(n, k):", "function_name": "miller_rabin_test", "parameter_list": "...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef miller_rabin_test(n, k: int) -> bool:\n \"\"\"\n Miller-Rabin primality test.\n n: the number to be tested for primality\n k:...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00045460", "row_id": 45460, "seed_ids": "[154]" }
0.585869
Data_Structure_45460
I
[ "miller_rabin_test", "generate_large_prime", "extended_gcd", "modinv_optimized", "optimized_generate_key" ]
5
[ [ "generate_large_prime", "miller_rabin_test" ], [ "modinv_optimized", "extended_gcd" ], [ "optimized_generate_key", "generate_large_prime" ], [ "optimized_generate_key", "modinv_optimized" ] ]
4
[]
false
[]
false
pytest
true
[]
true
df961051fc3d4c62c2d8e9eda086a9a3380a4bd3
6a4cda91e457ea443c635c25677c91f77b167331
v1.0
instruct
Data_Structure
Data_Structure_45461_I
### Quick Sort Implementation & Optimization #### Context You are working on an analytics tool that handles large datasets. Efficiency is crucial given that you sometimes work with millions of records. While Quick Sort is generally efficient, it can degrade to O(n^2) based on pivot choices. Our goal is to optimize the...
def median_of_three(arr, low, high): mid = (low + high) // 2 a, b, c = arr[low], arr[mid], arr[high] if a > b: if a < c: median = low elif b > c: median = mid else: median = high else: if b < c: median = mid elif a >...
from solution import optimized_quick_sort def test_sorted_list(): assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_list(): assert optimized_quick_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_identical_elements(): assert optimized_quick_sort([1, 1, 1, 1]) == [1,...
[ { "docstring": null, "function_declaration": "def median_of_three(arr, low, high):", "function_name": "median_of_three", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def median_of_three(arr, low, high):\n mid = (low + high) // 2\n a, b, c = arr[low], arr[mid], arr[high]\n if a > b:\n if a < c:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00045461", "row_id": 45461, "seed_ids": "[25]" }
0.591329
Data_Structure_45461
I
[ "median_of_three", "partition", "_quick_sort", "optimized_quick_sort" ]
4
[ [ "_quick_sort", "partition" ], [ "optimized_quick_sort", "_quick_sort" ], [ "partition", "median_of_three" ] ]
3
[]
false
[]
false
pytest
true
[]
true
4bcdc5d974ff71323c35fd11cc416d8c5320d6cc
5b2a360c0231485c2bf897d42762829cefc2f6d0
v1.0
instruct
Data_Structure
Data_Structure_45484_I
### Objective: Write a function implementing the nearest neighbor classification algorithm using Manhattan distance instead of Euclidean distance. ### Function Signature: ```python def nearest_neighbor_manhattan(x: tuple, tSet: dict) -> any: pass ``` ### Input: 1. `x` (tuple): A vector of numerical values repres...
def manhattan_distance(x, y): """ Calculate the Manhattan distance between two vectors x and y. """ return sum(abs(a - b) for a, b in zip(x, y)) def nearest_neighbor_manhattan(x: tuple, tSet: dict) -> any: """ Find the nearest neighbor of vector x based on Manhattan distance in training set tSe...
from solution import nearest_neighbor_manhattan def test_nearest_neighbor_single_entry(): tSet = { (1, 2): 'A' } x = (1, 2) assert nearest_neighbor_manhattan(x, tSet) == 'A' def test_nearest_neighbor_different_entries(): tSet = { (1, 2): 'A', (3, 4): 'B', (5, 6)...
[ { "docstring": "Calculate the Manhattan distance between two vectors x and y.", "function_declaration": "def manhattan_distance(x, y):", "function_name": "manhattan_distance", "parameter_list": "(x, y)" }, { "docstring": "Find the nearest neighbor of vector x based on Manhattan distance in t...
[ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def nearest_neighbor_manhattan(x: tuple, tSet: dict) -> any:\n \"\"\"\n This function finds the classification of the nearest neighbor to the vector x\n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00045484", "row_id": 45484, "seed_ids": "[260]" }
0.636419
Data_Structure_45484
I
[ "manhattan_distance", "nearest_neighbor_manhattan" ]
2
[ [ "nearest_neighbor_manhattan", "manhattan_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6379948687261b53163139f41a154b6e362c7f8c
b7366c3ed3fb6e0f5bb41848c193a96a7e8c33c8
v1.0
instruct
Data_Structure
Data_Structure_45556_I
Maximum Flow - Advanced Graph Algorithms #### Scenario A company is building a network of pipelines to transport water from a source to various facilities. The pipelines have different capacities, and the company needs to determine the maximum amount of water that can be transported from the source to the main facilit...
from typing import List from collections import deque def bfs_level_graph(capacity: List[List[int]], source: int, sink: int, level: List[int]) -> bool: V = len(capacity) for i in range(V): level[i] = -1 level[source] = 0 queue = deque([source]) while queue: u = queue.popleft() ...
from solution import max_flow def test_simple_case(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert max_flow(capacity, source, sin...
[ { "docstring": null, "function_declaration": "def bfs_level_graph(capacity, source, sink, level):", "function_name": "bfs_level_graph", "parameter_list": "(capacity, source, sink, level)" }, { "docstring": null, "function_declaration": "def dfs_send_flow(u, flow, sink, capacity, level, s...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\nfrom typing import List\n\ndef bfs(level: List[int], capacity: List[List[int]], source: int, sink: int) -> bool:\n n = len(c...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00045556", "row_id": 45556, "seed_ids": "[240]" }
0.613279
Data_Structure_45556
I
[ "bfs_level_graph", "dfs_send_flow", "max_flow" ]
3
[ [ "max_flow", "bfs_level_graph" ], [ "max_flow", "dfs_send_flow" ] ]
2
[]
false
[]
false
pytest
true
[]
true
cbfe750f87d24bc4659b471dd53317cf739035e6
e88e782732ba34cb04ba70edfed622757b630d11
v1.0
instruct
Data_Structure
Data_Structure_45589_I
### Question Create a function named `custom_heap_sort` that sorts an array of integers in ascending order using either a max-heap or min-heap, based on a flag. This function should efficiently perform heap sort and display the array at each main step for educational and debugging purposes. #### Function Signature ```...
def heapify(arr, n, i, use_max_heap): largest = i left = 2 * i + 1 right = 2 * i + 2 if use_max_heap: # Max-Heapify if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: largest = right else: # M...
from solution import custom_heap_sort def test_heap_sort_max_heap(): arr = [3, 2, 5, 1, 7, 8] assert custom_heap_sort(arr, True) == [1, 2, 3, 5, 7, 8] def test_heap_sort_min_heap(): arr = [3, 2, 5, 1, 7, 8] assert custom_heap_sort(arr, False) == [1, 2, 3, 5, 7, 8] def test_heap_sort_single_element():...
[ { "docstring": null, "function_declaration": "def heapify(arr, n, i, use_max_heap):", "function_name": "heapify", "parameter_list": "(arr, n, i, use_max_heap)" }, { "docstring": null, "function_declaration": "def build_heap(arr, n, use_max_heap, simulation):", "function_name": "build...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def custom_heap_sort(arr, use_max_heap, simulation=False):\n n = len(arr)\n \n def heapify(arr, n, i):\n if use_max_heap:\n largest...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00045589", "row_id": 45589, "seed_ids": "[8]" }
0.715126
Data_Structure_45589
I
[ "heapify", "build_heap", "custom_heap_sort" ]
3
[ [ "build_heap", "heapify" ], [ "custom_heap_sort", "build_heap" ], [ "custom_heap_sort", "heapify" ] ]
3
[]
false
[]
false
pytest
true
[]
true
1a5504aad397f061b59c479e8ba21d165e747b41
7413fa24d2e333405ea65da7f59678de5a9e4355
v1.0
instruct
Data_Structure
Data_Structure_45612_I
### Heap Sort Challenge Heap Sort is a comparison-based sorting algorithm that leverages the properties of a binary heap (a complete binary tree where each node is greater than its children in a max heap, or smaller than its children in a min heap). Your task is to implement the `heap_sort` function that accepts an ...
def heapify(arr, n, i, use_max_heap): """ To heapify a subtree rooted with node i which is an index in arr[]. n is size of heap """ if use_max_heap: largest = i # Initialize largest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 # See if left c...
from solution import heap_sort def test_heap_sort_empty(): assert heap_sort([], True) == [] assert heap_sort([], False) == [] def test_heap_sort_single_element(): assert heap_sort([1], True) == [1] assert heap_sort([1], False) == [1] def test_heap_sort_multiple_elements_max_heap(): assert heap_so...
[ { "docstring": "To heapify a subtree rooted with node i which is an index in arr[]. n is size of heap", "function_declaration": "def heapify(arr, n, i, use_max_heap):", "function_name": "heapify", "parameter_list": "(arr, n, i, use_max_heap)" }, { "docstring": "Heap sort function that sorts ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def heap_sort(arr, use_max_heap=True):\n def heapify(arr, n, i, compare):\n largest = i\n l = 2 * i + 1\n r = 2 * i + 2\n \n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045612", "row_id": 45612, "seed_ids": "[8]" }
0.677087
Data_Structure_45612
I
[ "heapify", "heap_sort" ]
2
[ [ "heap_sort", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dd987cc0649ece9fdb0112380d5c11a75111355a
ea65242d73472d3f582398377f14642d04328329
v1.0
instruct
Data_Structure
Data_Structure_45635_I
### Subtree Verification Challenge You are given two binary trees, `s` (large tree) and `t` (potential subtree). Write a function to determine if `t` is a subtree of `s`. A subtree of `s` is defined as a node in `s` and all its descendants that form a tree identical to `t`. #### Input - The function will receive two ...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_same_tree(s: TreeNode, t: TreeNode) -> bool: if not s and not t: return True if not s or not t: return False if s.val != t.val: ret...
import pytest from solution import TreeNode, is_subtree def test_subtree_case_1(): s = TreeNode(3) s.left = TreeNode(4) s.right = TreeNode(5) s.left.left = TreeNode(1) s.left.right = TreeNode(2) t = TreeNode(4) t.left = TreeNode(1) t.right = TreeNode(2) assert is_subtree(s...
[]
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n sel...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045635", "row_id": 45635, "seed_ids": "[288]" }
0.567453
Data_Structure_45635
I
[ "is_same_tree", "is_subtree" ]
2
[ [ "is_subtree", "is_same_tree" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
d005fa7eb862ff783352b642c55ca1bf8486ea43
9287c777c849d0c0f1212534a430a62dec664bea
v1.0
instruct
Data_Structure
Data_Structure_45660_I
### Scenario Imagine you are working on implementing a robust encryption algorithm. As part of the encryption process, you need to compute the modular order of integers to strengthen the encryption scheme. Given integers `a` and `n`, the order of `a` modulo `n` is defined as the smallest positive integer `k` such that...
def gcd(a, b): """Helper function to compute GCD of two integers using Euclidean algorithm.""" while b: a, b = b, a % b return a def find_order(a, n): """ Returns the smallest positive integer k such that a^k ≡ 1 (mod n). If gcd(a, n) != 1, print an error message and return -1. If a...
from solution import find_order def test_find_order_relative_primes(): assert find_order(3, 7) == 6 assert find_order(10, 17) == 16 assert find_order(4, 13) == 6 def test_find_order_non_relative_primes(): assert find_order(2, 8) == -1 assert find_order(3, 9) == -1 def test_find_order_a_equals_1_n...
[ { "docstring": "Helper function to compute GCD of two integers using Euclidean algorithm.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the smallest positive integer k such that a^k ≡ 1 (mod n).\nIf gcd(a, n) != 1, p...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef find_order(a, n):\n if gcd(a, n) != 1:\n print(\"a and n should be relati...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00045660", "row_id": 45660, "seed_ids": "[150]" }
0.585077
Data_Structure_45660
I
[ "gcd", "find_order" ]
2
[ [ "find_order", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d76a2fddf800874a41efe2c45919ee3617d68d3f
09d9b85b099d667a3359acf39a696a97ad781254
v1.0
instruct
Data_Structure
Data_Structure_45663_I
### Assessing Maximum Flow Computation **Objective**: Design an algorithm to determine the maximum flow in a network using the BFS-based Edmonds-Karp method. **Scenario/Context**: You've been tasked with optimizing the network traffic flow between a source node and sink node in a city's internet infrastructure. The n...
from collections import deque def bfs_capacity(residual_graph, source, sink, parent): visited = [False] * len(residual_graph) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() for v, capacity in enumerate(residual_graph[u]): if not visited[v] ...
def test_maximum_flow_bfs_simple(): graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] assert maximum_flow_bfs(graph) == 23 def test_maximum_flow_bfs_no_path(): graph = ...
[ { "docstring": null, "function_declaration": "def bfs_capacity(residual_graph, source, sink, parent):", "function_name": "bfs_capacity", "parameter_list": "(residual_graph, source, sink, parent)" }, { "docstring": null, "function_declaration": "def maximum_flow_bfs(adjacency_matrix):", ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef bfs_capacity(residual_graph, source, sink, parent):\n visited = [False] * len(residual_graph)\n queue = deque([sour...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00045663", "row_id": 45663, "seed_ids": "[229]" }
0.556519
Data_Structure_45663
I
[ "bfs_capacity", "maximum_flow_bfs" ]
2
[ [ "maximum_flow_bfs", "bfs_capacity" ] ]
1
[]
false
[]
false
pytest
false
[]
true
c43dfcb77f5811b0bcbdf5bba8c28fe3cd806fef
54242e1e7781fdc4082465387d650d75fa6d2d05
v1.0
instruct
Data_Structure
Data_Structure_45765_I
You are tasked with implementing an enhanced nearest neighbor classifier. In addition to the plain nearest neighbor search, you must also incorporate a weighted voting scheme based on the inverse of the distance to each neighbor. The final classification is determined by the vector class that receives the highest weigh...
import math from collections import defaultdict def distance(x: tuple, y: tuple) -> float: """ Computes the Euclidean distance between two vectors x and y. """ assert len(x) == len(y), "Vectors must be of the same length." return math.sqrt(sum((xi - yi) ** 2 for xi, yi in zip(x, y))) def nearest_n...
from solution import distance, nearest_neighbor def test_distance_same_vector(): assert distance((1.0, 2.0), (1.0, 2.0)) == 0.0 def test_distance_different_vectors(): assert distance((1.0, 2.0), (4.0, 6.0)) == 5.0 def test_distance_throws_on_different_lengths(): try: distance((1.0, 2.0), (1.0, 2....
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef distance(x: tuple, y: tuple) -> float:\n \"\"\"\n Returns the Euclidean distance between vectors x and y.\n \"\"\"\n assert len...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045765", "row_id": 45765, "seed_ids": "[260]" }
0.614288
Data_Structure_45765
I
[ "distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b2cfc899b6e209265bce276907018583f82e8874
f44498fd5129058da70a5ce85c2076721c1bcd5c
v1.0
instruct
Data_Structure
Data_Structure_45766_I
### RSA Encryption Application ### Problem Statement You are tasked with enhancing the performance of an RSA encryption algorithm by implementing an optimized solution for calculating the modular inverse and prime number generation. Using this optimized RSA key generation, encryption, and decryption should be made mo...
import random from typing import Tuple def modinv(a: int, m: int) -> int: """ Compute the modular inverse of a under modulo m using the Extended Euclidean Algorithm. """ m0, x0, x1 = m, 0, 1 if m == 1: return 0 while a > 1: q = a // m m, a = a % m, m x0, x1 ...
from solution import generate_key, encrypt, decrypt, modinv, is_prime def test_modinv(): assert modinv(3, 11) == 4 def test_is_prime(): assert is_prime(11) == True assert is_prime(15) == False def test_generate_key(): n, e, d = generate_key(16) assert isinstance(n, int) assert isinstance(e, i...
[ { "docstring": "Compute the modular inverse of a under modulo m using the Extended Euclidean Algorithm.", "function_declaration": "def modinv(a, m):", "function_name": "modinv", "parameter_list": "(a, m)" }, { "docstring": "Determine if a number is prime using the Miller-Rabin primality test...
[ 0, 1 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import Tuple\n\ndef gcd(a, b):\n while b != 0:\n a, b = b, a % b\n return a\n\ndef modinv(a, m):\n m0, x0, x1 = m, ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045766", "row_id": 45766, "seed_ids": "[154]" }
0.538123
Data_Structure_45766
I
[ "modinv", "is_prime", "generate_prime_candidate", "generate_prime_number", "generate_key", "encrypt", "decrypt" ]
7
[ [ "generate_key", "generate_prime_number" ], [ "generate_key", "modinv" ], [ "generate_prime_number", "generate_prime_candidate" ], [ "generate_prime_number", "is_prime" ] ]
4
[]
false
[]
false
pytest
true
[]
true
ac923dcd5786cc48b2d8e722f579bdda6c86c7b8
293b4c44955af9b76584798341a0aa46752fe6da
v1.0
instruct
Data_Structure
Data_Structure_45844_I
**Context:** You are developing a feature for a software system that processes and sorts large datasets. One of the fundamental requirements is to implement an efficient and reliable sorting mechanism that can handle diverse input sizes and maintain stability in sorting. **Task:** Implement the Merge Sort algorithm in...
def merge_sort(arr): """Merge Sort Algorithm""" if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(left, right): """Merge helper function""" result = [] left_cursor, right_...
from solution import merge_sort def test_merge_sort_empty_list(): assert merge_sort([]) == [] def test_merge_sort_single_element_list(): assert merge_sort([1]) == [1] def test_merge_sort_sorted_list(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_sorted_list(): a...
[ { "docstring": "Merge Sort Algorithm", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merge helper function", "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list"...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\" Merge Sort Algorithm \"\"\"\n if len(arr) <= 1:\n return arr\n mid = len(arr) // 2\n left = merge_sort(arr[:m...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045844", "row_id": 45844, "seed_ids": "[12]" }
0.563192
Data_Structure_45844
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
61ebb043a519ac8f61e3a3cae648460f9462c518
059fd2c8877d3a2ca142324ebb8f85e8d1af1ab0
v1.0
instruct
Data_Structure
Data_Structure_45854_I
### Question: Implement a Secure Diffie-Hellman Key Exchange with Primality and Primitive Root Check #### Scenario: Alice and Bob want to securely share a secret key over an insecure channel using the Diffie-Hellman key exchange algorithm. As part of this process, they need to verify that the chosen prime number and i...
from typing import Union from sympy import isprime, mod_inverse def is_primitive_root(a, p): """ Check if a is a primitive root of prime p. """ if not isprime(p): return False required_set = set(num for num in range(1, p) if gcd(num, p) == 1) actual_set = set(pow(a, powers, p) for...
import pytest from solution import secure_diffie_hellman def test_prime_verification(): assert secure_diffie_hellman(5, 20) == "20 is not a prime number" assert secure_diffie_hellman(5, 18) == "18 is not a prime number" def test_primitive_root_verification(): assert secure_diffie_hellman(5, 23) == 2 # As...
[ { "docstring": "Check if a is a primitive root of prime p.", "function_declaration": "def is_primitive_root(a, p):", "function_name": "is_primitive_root", "parameter_list": "(a, p)" }, { "docstring": null, "function_declaration": "def secure_diffie_hellman(a, p):", "function_name": "...
[ 0, 0, 0, 1, 1, 0, 0, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import Union\nimport random\nimport sympy\n\ndef is_prime(n: int) -> bool:\n return sympy.isprime(n)\n\ndef find_primitive_root(p: int) -> int:...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00045854", "row_id": 45854, "seed_ids": "[146]" }
0.504504
Data_Structure_45854
I
[ "is_primitive_root", "secure_diffie_hellman", "gcd" ]
3
[ [ "is_primitive_root", "gcd" ], [ "secure_diffie_hellman", "is_primitive_root" ] ]
2
[]
false
[]
false
pytest
true
[ "sympy" ]
false
db0205afe3d3b0853fe9c244fc4a03abf2a86b2e
fa1d247247885b5b7c8210bae9e79f7d086639ec
v1.0
instruct
Data_Structure
Data_Structure_45857_I
### Word Search with Constraints Given a 2D board of characters and a list of words, write a function `find_advanced_words` that returns a list of all words from the list that are present on the board. #### Special Constraints: 1. Words must be constructed from letters of sequentially adjacent cells. 2. A cell can o...
from typing import List class TrieNode: def __init__(self): self.children = {} self.is_end_of_word = False self.word = None def add_word_to_trie(root, word): node = root for char in word: if char not in node.children: node.children[char] = TrieNode() nod...
from solution import find_advanced_words def test_example_case(): board = [ ['o', 'a', 'a', 'n'], ['e', 't', 'a', 'e'], ['i', 'h', 'k', 'r'], ['i', 'f', 'l', 'v'] ] words = ["oath", "pea", "eat", "rain"] assert sorted(find_advanced_words(board, words)) == sorted(["oath",...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.is_end_of_word = False\n self.word = None # To store the word at en...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00045857", "row_id": 45857, "seed_ids": "[115]" }
0.576481
Data_Structure_45857
I
[ "add_word_to_trie", "find_advanced_words" ]
2
[ [ "find_advanced_words", "add_word_to_trie" ] ]
1
[]
false
[ "TrieNode" ]
true
pytest
true
[]
true
1f38531d25309906369fc3e5d96701a54e6ea1bb
5e53fd651863e832dae45505f6df63367a5ea782
v1.0
instruct
Data_Structure
Data_Structure_45940_I
### Scenario: A city has multiple pipelines that distribute water between different sectors. Each pipeline has a maximum capacity of water flow. We need to determine the maximum possible flow of water from the water plant (source) to the emergency reservoir (sink). You are required to implement this using Dinic's Algor...
from collections import deque from typing import List, Optional def bfs(level: List[Optional[int]], capacity: List[List[int]], flow: List[List[int]], source: int, sink: int) -> bool: """Performs a BFS to construct level graph.""" queue = deque([source]) level[source] = 0 while queue: u = queue....
from solution import calculate_max_flow def test_calculate_max_flow_basic_case(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] assert calculate_max_flow(capacity, 0...
[ { "docstring": "Performs a BFS to construct level graph.", "function_declaration": "def bfs(level, capacity, flow, source, sink):", "function_name": "bfs", "parameter_list": "(level, capacity, flow, source, sink)" }, { "docstring": "Sends flow along an augmenting path using DFS.", "funct...
[ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef calculate_max_flow(capacity, source, sink):\n n = len(capacity)\n \n # Residual capacity matrix\n residual_ca...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00045940", "row_id": 45940, "seed_ids": "[240]" }
0.609923
Data_Structure_45940
I
[ "bfs", "dfs", "calculate_max_flow" ]
3
[ [ "calculate_max_flow", "bfs" ], [ "calculate_max_flow", "dfs" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5ed396c5dda23bb8b4efaf52325042403fd8f7c5
6a1fbc370a2f8bc0072a193bdea639bb90d6da82
v1.0
instruct
Data_Structure
Data_Structure_45981_I
You are provided with a partial implementation of a matrix multiplication algorithm. The current implementation multiplies two matrices and returns their product. However, the existing code may raise an exception if the matrices are not conformable (i.e., the number of columns in the first matrix does not match the num...
def add_matrix(A, B): """ Adds two matrices element-wise. """ n = len(A) result = [[A[i][j] + B[i][j] for j in range(n)] for i in range(n)] return result def subtract_matrix(A, B): """ Subtracts matrix B from matrix A element-wise. """ n = len(A) result = [[A[i][j] - B[i][j]...
from solution import multiply_matrices def test_multiply_matrices_basic_case(): multiplicand = [ [1, 2], [3, 4] ] multiplier = [ [2, 0], [1, 2] ] expected = [ [4, 4], [10, 8] ] assert multiply_matrices(multiplicand, multiplier) == expected de...
[ { "docstring": "Adds two matrices element-wise.", "function_declaration": "def add_matrix(A, B):", "function_name": "add_matrix", "parameter_list": "(A, B)" }, { "docstring": "Subtracts matrix B from matrix A element-wise.", "function_declaration": "def subtract_matrix(A, B):", "func...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def add_matrix(A, B):\n \"\"\"\n Adds two matrices A and B.\n \"\"\"\n n = len(A)\n C = [[0] * n for _ in range(n)]\n for i in range(n):\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00045981", "row_id": 45981, "seed_ids": "[343]" }
0.586087
Data_Structure_45981
I
[ "add_matrix", "subtract_matrix", "strassen_mult", "multiply_matrices" ]
4
[ [ "multiply_matrices", "strassen_mult" ], [ "strassen_mult", "add_matrix" ], [ "strassen_mult", "subtract_matrix" ] ]
3
[]
false
[]
false
pytest
true
[]
true
4b816a508c9cecdae73a9960644e15b344cc1037
4d92d2847620ce2408ddae4dff16499172ccdd1d
v1.0
instruct
Data_Structure
Data_Structure_45986_I
#### Problem Statement Write a function named `find_special_numbers` that identifies and returns a list of numbers within a given range that exhibit the "special number" property. A "special number" is defined as a number whose sum of its digits raised to consecutive powers equals the number itself. For instance: * 89...
from typing import List def is_special_number(num: int) -> bool: digit_str = str(num) total = sum(int(digit_str[i]) ** (i + 1) for i in range(len(digit_str))) return total == num def find_special_numbers(start: int, end: int) -> List[int]: return [num for num in range(start, end + 1) if is_special_num...
from solution import find_special_numbers def test_single_digit_numbers(): assert find_special_numbers(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9] def test_double_digit_numbers(): assert find_special_numbers(10, 100) == [89] def test_range_including_special_numbers(): assert find_special_numbers(1, 100) == [1,...
[ { "docstring": null, "function_declaration": "def is_special_number(num):", "function_name": "is_special_number", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def find_special_numbers(start, end):", "function_name": "find_special_numbers", "parameter...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_special_number(num: int) -> bool:\n digit_str = str(num)\n total = sum(int(digit_str[i]) ** (i + 1) for i in range(len...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00045986", "row_id": 45986, "seed_ids": "[135]" }
0.601653
Data_Structure_45986
I
[ "is_special_number", "find_special_numbers" ]
2
[ [ "find_special_numbers", "is_special_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7a06075b9e330a7fa8873e67e787573f28cf78c7
409d67b3fe8902b6143c6a4b8afc1b334251c8eb
v1.0
instruct
Data_Structure
Data_Structure_45998_I
Radix Sort Implementation **Scenario**: You work as a software engineer at an e-commerce company that often deals with large datasets, such as a list of transaction amounts that need to be sorted for reporting purposes. To enhance your system's performance, you decide to implement an efficient sorting algorithm: Radix...
def counting_sort_for_radix(arr, exp): n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = arr[i] // exp count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] i = n - 1 while i >= 0: index = arr[i] // exp output[c...
from solution import radix_sort def test_radix_sort_empty(): assert radix_sort([]) == [] def test_radix_sort_sorted_elements(): assert radix_sort([1, 2, 3]) == [1, 2, 3] def test_radix_sort_unsorted_elements(): assert radix_sort([3, 1, 2]) == [1, 2, 3] def test_radix_sort_with_zeros(): assert radix_...
[ { "docstring": null, "function_declaration": "def counting_sort_for_radix(arr, exp):", "function_name": "counting_sort_for_radix", "parameter_list": "(arr, exp)" }, { "docstring": null, "function_declaration": "def radix_sort(arr, simulation=False):", "function_name": "radix_sort", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def counting_sort_for_radix(arr, exp, simulation=False):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # Store count of occurrences in ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00045998", "row_id": 45998, "seed_ids": "[15]" }
0.602784
Data_Structure_45998
I
[ "counting_sort_for_radix", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort_for_radix" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0b3b0fcbcd8c7733dbd9b6f08c53d7587bfd1c50
64c0f36b77a3d398fac51867332053aba54bf947
v1.0
instruct
Data_Structure
Data_Structure_46067_I
### Question You are tasked with implementing a merge sort algorithm, but with certain optimizations and special requirements. This will test your understanding of the algorithm’s nuances and your ability to make improvements. #### Requirements: 1. Implement the merge sort algorithm in a Python function `optimized_mer...
from typing import List def insertion_sort(arr: List[int], left: int, right: int) -> None: for i in range(left + 1, right + 1): key = arr[i] j = i - 1 while j >= left and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def merge(arr: List[int], lef...
def test_single_element(): arr = [1] k = 10 assert optimized_merge_sort(arr, k) == [1] def test_empty_array(): arr = [] k = 10 assert optimized_merge_sort(arr, k) == [] def test_already_sorted(): arr = [1, 2, 3, 4, 5] k = 10 assert optimized_merge_sort(arr, k) == [1, 2, 3, 4, 5] d...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr, left, right):", "function_name": "insertion_sort", "parameter_list": "(arr, left, right)" }, { "docstring": null, "function_declaration": "def merge(arr, left, mid, right):", "function_name": "merge", "paramete...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef insertion_sort(arr: List[int], left: int, right: int) -> None:\n for i in range(left + 1, right + 1):\n key = arr[i]\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00046067", "row_id": 46067, "seed_ids": "[12]" }
0.62844
Data_Structure_46067
I
[ "insertion_sort", "merge", "optimized_merge_sort_helper", "optimized_merge_sort" ]
4
[ [ "optimized_merge_sort", "optimized_merge_sort_helper" ], [ "optimized_merge_sort_helper", "insertion_sort" ], [ "optimized_merge_sort_helper", "merge" ] ]
3
[]
false
[]
false
pytest
false
[]
true
39bf5359ab78335ebba0c2b11fe07fdd30bb90c1
e65732799bbe32a3478f53a6db02d7b104b7f607
v1.0
instruct
Data_Structure
Data_Structure_46151_I
### Shell Sort Implementation and Adaptation **Context**: You have to implement the Shell Sort algorithm, but with a twist: you need to sort an array where multiple element types are present (integers, strings). **Task**: Write a function `shell_sort_with_mixed_types(arr: List[Union[int, str]]) -> List[Union[int, str...
from typing import List, Union def shell_sort_with_mixed_types(arr: List[Union[int, str]]) -> List[Union[int, str]]: """ Sorts an array containing mixed types (integers and strings) such that integers come first in ascending order, followed by strings in lexicographical order. """ n = len(arr) ...
def test_shell_sort_with_mixed_types(): assert shell_sort_with_mixed_types([3, "banana", 1, "apple", 5, "cherry"]) == [1, 3, 5, "apple", "banana", "cherry"] assert shell_sort_with_mixed_types([7, 2, 3, "a", "z", "m"]) == [2, 3, 7, "a", "m", "z"] assert shell_sort_with_mixed_types([10, "apple", -1, "banana",...
[ { "docstring": "Sorts an array containing mixed types (integers and strings) such that \nintegers come first in ascending order, followed by strings in lexicographical order.", "function_declaration": "def shell_sort_with_mixed_types(arr):", "function_name": "shell_sort_with_mixed_types", "parameter...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Union\n\ndef shell_sort_with_mixed_types(arr: List[Union[int, str]]) -> List[Union[int, str]]:\n n = len(arr)\n gap = n // 2\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046151", "row_id": 46151, "seed_ids": "[22]" }
0.669185
Data_Structure_46151
I
[ "shell_sort_with_mixed_types", "compare" ]
2
[ [ "shell_sort_with_mixed_types", "compare" ] ]
1
[]
false
[]
false
pytest
false
[]
true
88c7409209f39ae90d144774474400b961eb0380
301040c63503cbd6865b1d84921b7140e35acc39
v1.0
instruct
Data_Structure
Data_Structure_46154_I
You are given a directed graph where each node represents a point in the network and each edge has a capacity, representing how much can flow through that edge. Implement an optimized version of the maximum flow problem using the BFS search strategy to ensure better path selection. ### Input: - An `n x n` adjacency ma...
from collections import deque def bfs(residual_graph, source, sink, parent): """ Returns True if there is a path from source to sink in residual graph. """ visited = [False] * len(residual_graph) queue = deque([source]) visited[source] = True while queue: u = queue.popleft...
from solution import maximum_flow_bfs def test_example_case(): graph = [[0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0]] assert maximum_flow_bfs(graph) == 23 def test_s...
[ { "docstring": "Returns True if there is a path from source to sink in residual graph.", "function_declaration": "def bfs(residual_graph, source, sink, parent):", "function_name": "bfs", "parameter_list": "(residual_graph, source, sink, parent)" }, { "docstring": "Returns the maximum flow fr...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef bfs(residual_graph, source, sink, parent):\n visited = [False] * len(residual_graph)\n queue = deque([source])\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00046154", "row_id": 46154, "seed_ids": "[241]" }
0.577776
Data_Structure_46154
I
[ "bfs", "maximum_flow_bfs" ]
2
[ [ "maximum_flow_bfs", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
24306a5b6a45afa266dcef85c6d6a5b143d66de4
539d2206765315fde5b4ac21f329068e7ce8d8a5
v1.0
instruct
Data_Structure
Data_Structure_46162_I
Implementation of Bitonic Sort Algorithm #### Problem Statement You are tasked with implementing the Bitonic Sort algorithm, an efficient parallel sorting algorithm designed for arrays whose sizes are powers of two. Your implementation should handle both ascending and descending order sorting. #### Function Signature...
from typing import List def compare_and_swap(arr: List[int], i: int, j: int, ascending: bool): """ Compare and swap the elements if they are in the wrong order based on ascending flag. """ if (ascending and arr[i] > arr[j]) or (not ascending and arr[i] < arr[j]): arr[i], arr[j] = arr[j], arr[i]...
import pytest from solution import bitonic_sort def test_bitonic_sort_ascending(): assert bitonic_sort([3, 7, 2, 1, 9, 5, 6, 4]) == [1, 2, 3, 4, 5, 6, 7, 9] def test_bitonic_sort_descending(): assert bitonic_sort([3, 7, 2, 1, 9, 5, 6, 4], reverse=True) == [9, 7, 6, 5, 4, 3, 2, 1] def test_single_element(): ...
[ { "docstring": "Compare and swap the elements if they are in the wrong order based on ascending flag.", "function_declaration": "def compare_and_swap(arr, i, j, ascending):", "function_name": "compare_and_swap", "parameter_list": "(arr, i, j, ascending)" }, { "docstring": "Merge function to ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef compare_and_swap(arr: List[int], i: int, j: int, direction: bool):\n \"\"\"\n Compares and swaps the elements at indices ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046162", "row_id": 46162, "seed_ids": "[17]" }
0.648722
Data_Structure_46162
I
[ "compare_and_swap", "bitonic_merge", "bitonic_sort_recursive", "bitonic_sort" ]
4
[ [ "bitonic_merge", "compare_and_swap" ], [ "bitonic_sort", "bitonic_sort_recursive" ], [ "bitonic_sort_recursive", "bitonic_merge" ] ]
3
[]
false
[]
false
pytest
true
[]
true
cb5661995fd9157a2c5cc0a0d92b1e836f4b476e
fb27fa757834727e0736ee0d06393f1e1929b6d9
v1.0
instruct
Data_Structure
Data_Structure_46218_I
### Stooge Sort Implementation and Analysis **Scenario**: You have been presented with a list of patient IDs that need to be sorted chronologically based on their timestamps of record creation. The list of IDs might contain duplicates, and the sorting needs to maintain the sequence of identical records (i.e., it shoul...
def stoogesort(arr, l, h): if l >= h: return # If first element is greater than last, swap them if arr[l] > arr[h]: arr[l], arr[h] = arr[h], arr[l] # If there are more than 2 elements in the array if h - l + 1 > 2: t = (h - l + 1) // 3 # Recursively sort first 2/3 ...
from solution import sort_patient_ids def test_sort_empty_list(): assert sort_patient_ids([]) == [] def test_sort_single_element(): assert sort_patient_ids([1]) == [1] def test_sort_sorted_list(): assert sort_patient_ids([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_sort_reverse_list(): assert sort_p...
[ { "docstring": null, "function_declaration": "def stoogesort(arr, l, h):", "function_name": "stoogesort", "parameter_list": "(arr, l, h)" }, { "docstring": null, "function_declaration": "def sort_patient_ids(patient_ids):", "function_name": "sort_patient_ids", "parameter_list": "...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def stoogesort(arr, l, h):\n \"\"\"\n Recursive function to perform Stooge Sort on a subarray from index l to h.\n \"\"\"\n if l >= h:\n re...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046218", "row_id": 46218, "seed_ids": "[10]" }
0.530639
Data_Structure_46218
I
[ "stoogesort", "sort_patient_ids" ]
2
[ [ "sort_patient_ids", "stoogesort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
37528baa709eb34db496cfb642a05594ae99ca56
976fdb66b6786cb5d35b9b8f3c54dec413f19ac1
v1.0
instruct
Data_Structure
Data_Structure_46232_I
### Scenario You are given the task of determining whether one binary tree is a subtree of another. A subtree is defined as a node in the main tree along with all of its descendants. ### Problem Statement Write a function `is_subtree(s: TreeNode, t: TreeNode) -> bool` that determines whether tree `t` is a subtree of t...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def is_subtree(s: TreeNode, t: TreeNode) -> bool: if not t: return True if not s: return False if are_identical(s, t): return ...
from solution import TreeNode, is_subtree def test_is_subtree_example1(): s = TreeNode(3) s.left = TreeNode(4) s.right = TreeNode(5) s.left.left = TreeNode(1) s.left.right = TreeNode(2) t = TreeNode(4) t.left = TreeNode(1) t.right = TreeNode(2) assert is_subtree(s, t) == T...
[]
[ 0, 0, 0, 1, 1, 1, 1, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00046232", "row_id": 46232, "seed_ids": "[288]" }
0.537848
Data_Structure_46232
I
[ "is_subtree", "are_identical" ]
2
[ [ "is_subtree", "are_identical" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
38ba7d07325b71617580e4b034f4637259d254ab
a41d8bd8c2509f29c5de19bf9d3bcd8642d8b36b
v1.0
instruct
Data_Structure
Data_Structure_46241_I
### Palindromic Partition Finder #### Context You are a software developer responsible for implementing a feature in a text processing application aimed at revealing all possible ways to partition input text into palindromic substrings. A palindrome is a string that reads the same forward and backward (such as "level"...
from typing import List def is_palindrome(s: str) -> bool: """ Helper function to check if the input string is a palindrome. """ return s == s[::-1] def palindromic_partitions(s: str) -> List[List[str]]: """ Function to find all palindromic partitions of the input string. """ def backt...
from solution import palindromic_partitions def test_single_character(): assert palindromic_partitions("a") == [["a"]] def test_empty_string(): assert palindromic_partitions("") == [[]] def test_no_palindromic_substring(): assert palindromic_partitions("abc") == [["a", "b", "c"]] def test_multiple_parti...
[ { "docstring": "Helper function to check if the input string is a palindrome.", "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": "Function to find all palindromic partitions of the input string.", "function_decla...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def palindromic_partitions(s: str):\n \"\"\"\n Returns all possible ways to partition input string into palindromic substrings.\n \"\"\"\n def is_...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00046241", "row_id": 46241, "seed_ids": "[113]" }
0.725937
Data_Structure_46241
I
[ "is_palindrome", "palindromic_partitions" ]
2
[ [ "palindromic_partitions", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
32966357d304a1194d41bb3373c81081326d7626
2a427d21c7ab39494f6a90c76a81997ab492d2a6
v1.0
instruct
Data_Structure
Data_Structure_46259_I
### Diffie-Hellman Key Exchange Enhanced The following outlines a scenario where improvements are needed in the Diffie-Hellman key exchange algorithm implementation. **Scenario:** Two entities, Alice and Bob, wish to securely establish a shared secret key through an insecure network. You are tasked with implementing ...
def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def gcd(a, b): while b: a, b = b, ...
from solution import diffie_hellman_key_exchange_enhanced def test_diffie_hellman_valid_case(): assert diffie_hellman_key_exchange_enhanced(5, 23) == True def test_diffie_hellman_invalid_prime(): assert diffie_hellman_key_exchange_enhanced(5, 21) == False def test_diffie_hellman_invalid_primitive_root(): ...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046259", "row_id": 46259, "seed_ids": "[146]" }
0.389874
Data_Structure_46259
I
[ "is_prime", "gcd", "is_primitive_root", "diffie_hellman_key_exchange_enhanced" ]
4
[ [ "diffie_hellman_key_exchange_enhanced", "is_prime" ], [ "diffie_hellman_key_exchange_enhanced", "is_primitive_root" ], [ "is_primitive_root", "gcd" ], [ "is_primitive_root", "is_prime" ] ]
4
[]
false
[]
false
pytest
true
[]
true
2f7f7eb742d07c7dc638d9e99ab17384d203bdbf
4ac2c2bf848e78d04d68810cb7a2764f1f2f4171
v1.0
instruct
Data_Structure
Data_Structure_46264_I
#### Context In the world of search algorithms, efficiency is crucial, especially when dealing with large datasets. Interpolation Search, often optimized for uniformly distributed arrays, can outperform traditional search algorithms under specific conditions. For this assessment, you will implement an extension of the...
from typing import List def interpolation_search(array: List[int], search_key: int) -> int: low = 0 high = len(array) - 1 while low <= high and search_key >= array[low] and search_key <= array[high]: if low == high: if array[low] == search_key: return low ...
def test_adaptive_search(): assert adaptive_search([-25, -12, -1, 10, 12, 15, 20, 41, 55], -1) == 2 assert adaptive_search([5, 10, 12, 14, 17, 20, 21], 55) == -1 assert adaptive_search([5, 10, 12, 14, 17, 20, 21], -5) == -1 assert adaptive_search([], 12) == -1 assert adaptive_search([10], 10) == 0 ...
[ { "docstring": null, "function_declaration": "def interpolation_search(array, search_key):", "function_name": "interpolation_search", "parameter_list": "(array, search_key)" }, { "docstring": null, "function_declaration": "def binary_search(array, search_key):", "function_name": "bin...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef binary_search(array: List[int], search_key: int) -> int:\n left, right = 0, len(array) - 1\n \n while left <= right:\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046264", "row_id": 46264, "seed_ids": "[192]" }
0.555355
Data_Structure_46264
I
[ "interpolation_search", "binary_search", "is_uniform", "adaptive_search" ]
4
[ [ "adaptive_search", "binary_search" ], [ "adaptive_search", "interpolation_search" ], [ "adaptive_search", "is_uniform" ] ]
3
[]
false
[]
false
pytest
true
[]
true
cabfb9178246a932f7b5c5aed871992df960dbf1
d0e76e48120868f128975ac4ce2adcb3384b3aac
v1.0
instruct
Data_Structure
Data_Structure_46273_I
### Tree Subtree Check Problem **Objective**: Implement a function to check whether tree `t` is a subtree of tree `s`. **Function Signature**: ```python def is_subtree(s: Optional[TreeNode], t: Optional[TreeNode]) -> bool: ``` **Input**: - `s`: The root node of a binary tree. - `t`: The root node of a binary tree. ...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_subtree(s: TreeNode, t: TreeNode) -> bool: if not s: return not t if is_identical(s, t): return True return is_subtree(s.left, t) or is_sub...
from solution import TreeNode, is_subtree def test_subtree_present(): # Tree s s = TreeNode(3) s.left = TreeNode(4) s.right = TreeNode(5) s.left.left = TreeNode(1) s.left.right = TreeNode(2) # Tree t t = TreeNode(4) t.left = TreeNode(1) t.right = TreeNode(2) assert...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046273", "row_id": 46273, "seed_ids": "[288]" }
0.622231
Data_Structure_46273
I
[ "is_subtree", "is_identical" ]
2
[ [ "is_subtree", "is_identical" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
aae2c072a52ac3d7a510f8858ad99c88da792b4c
9feb1a0fec020e9da1f9df2b52ef0e98fce4d126
v1.0
instruct
Data_Structure
Data_Structure_46289_I
<|Analysis Begin|> **Algorithm/Data Structure**: The algorithm used here is for calculating the **maximum flow** in a flow network using the **Depth-First Search (DFS) method**. This is a specific implementation focusing on finding the maximum amount of "flow" that can be pushed from a source node to a sink node in a ...
from typing import List def dfs(graph: List[List[int]], source: int, sink: int, path: List[bool], parent: List[int]) -> bool: visited = [False] * len(graph) stack = [source] visited[source] = True while stack: u = stack.pop() for v in range(len(graph)): if visited[v] ==...
from solution import maximum_flow_dfs def test_maximum_flow_simple_case(): graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] assert maximum_flow_dfs(graph) == 23 def test_...
[ { "docstring": null, "function_declaration": "def dfs(graph, source, sink, path, parent):", "function_name": "dfs", "parameter_list": "(graph, source, sink, path, parent)" }, { "docstring": null, "function_declaration": "def maximum_flow_dfs(adjacency_matrix):", "function_name": "max...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef maximum_flow_dfs(adjacency_matrix: List[List[int]]) -> int:\n def dfs(source, sink, path):\n if source == sink:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046289", "row_id": 46289, "seed_ids": "[241]" }
0.501749
Data_Structure_46289
I
[ "dfs", "maximum_flow_dfs" ]
2
[ [ "maximum_flow_dfs", "dfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
377dfbeb167a083bfc7afe53bfa3c9801f87eeaf
b96beee0abb9cacc62042392772f1f3fc2849a0d
v1.0
instruct
Data_Structure
Data_Structure_46292_I
### Question: Markov Chain Simulation and Analysis #### Scenario Given a Markov chain described by a dictionary, you are tasked with simulating the Markov chain from an initial state and analyzing certain properties of the resulting sequence. #### Task 1. Implement a function `simulate_markov_chain(chain, initial_sta...
import random def simulate_markov_chain(chain, initial_state, steps): state = initial_state sequence = [state] for _ in range(steps): next_state = random.choices(list(chain[state].keys()), list(chain[state].values()))[0] sequence.append(next_state) state = next_state r...
from solution import simulate_markov_chain, state_visits def test_simulate_markov_chain_single_step(): chain = {'A': {'A': 1.0}} result = simulate_markov_chain(chain, 'A', 1) assert result == ['A', 'A'] def test_simulate_markov_chain_multiple_steps(): chain = {'A': {'A': 0.5, 'B': 0.5}, 'B': {'A': 1.0...
[ { "docstring": null, "function_declaration": "def simulate_markov_chain(chain, initial_state, steps):", "function_name": "simulate_markov_chain", "parameter_list": "(chain, initial_state, steps)" }, { "docstring": null, "function_declaration": "def state_visits(chain, initial_state, step...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef simulate_markov_chain(chain, initial_state, steps):\n \"\"\"\n Simulate the Markov chain for a specified number of steps starting f...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046292", "row_id": 46292, "seed_ids": "[232]" }
0.496689
Data_Structure_46292
I
[ "simulate_markov_chain", "state_visits" ]
2
[ [ "state_visits", "simulate_markov_chain" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4aa98c6441e98eeab3f5220ac2ef9f7d803c0430
ec907b45cce7670cb66ff458900f358438c49f39
v1.0
instruct
Data_Structure
Data_Structure_46333_I
### Gnome Sort Implementation and Analysis Challenge You are provided with a simple sorting algorithm known as Gnome Sort. To test your understanding of sorting algorithms and their practical application, you are required to implement a function based on the provided code snippet and analyze its performance on differe...
def gnome_sort(arr): """ Sorts an array using the Gnome sort algorithm. Parameters: arr (list): The list of integers to sort. Returns: list: The sorted list in ascending order. """ n = len(arr) index = 0 while index < n: if index == 0 or arr[index] >= arr[index ...
from solution import gnome_sort def test_gnome_sort_empty(): assert gnome_sort([]) == [] def test_gnome_sort_single_element(): assert gnome_sort([1]) == [1] def test_gnome_sort_sorted(): assert gnome_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_gnome_sort_reverse(): assert gnome_sort([5, 4, 3, ...
[ { "docstring": "Sorts an array using the Gnome sort algorithm.\n\nParameters:\narr (list): The list of integers to sort.\n\nReturns:\nlist: The sorted list in ascending order.", "function_declaration": "def gnome_sort(arr):", "function_name": "gnome_sort", "parameter_list": "(arr)" }, { "doc...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def gnome_sort(arr):\n \"\"\"\n Sorts the input list using Gnome Sort algorithm in ascending order.\n \"\"\"\n n = len(arr)\n index = 0\n wh...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00046333", "row_id": 46333, "seed_ids": "[13]" }
0.577006
Data_Structure_46333
I
[ "gnome_sort", "analyze_gnome_sort_performance" ]
2
[ [ "analyze_gnome_sort_performance", "gnome_sort" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib" ]
false
c8ed93687b86bd99cf7ee10eeb1a8892244bd747
dd3853c3b0a4a4bf8961a0db435b1ca229729c4c
v1.0
instruct
Data_Structure
Data_Structure_46339_I
## Bitonic Sort Enhancement Challenge ### Objective The task is to optimize the given Bitonic Sort algorithm by introducing a parallel processing approach. This will improve the runtime performance over large input sizes. The provided bitonic sort algorithm works well, but does not utilize the parallel processing for ...
import multiprocessing from typing import List def compare_and_swap(arr: List[int], i: int, j: int, direction: bool): if direction == (arr[i] > arr[j]): arr[i], arr[j] = arr[j], arr[i] def bitonic_merge(arr: List[int], low: int, cnt: int, direction: bool): if cnt > 1: k = cnt // 2 for ...
from solution import parallel_bitonic_sort def test_parallel_bitonic_sort_basic(): arr = [3, 7, 2, 5, 1, 6, 4, 8] assert parallel_bitonic_sort(arr) == [1, 2, 3, 4, 5, 6, 7, 8] def test_parallel_bitonic_sort_reverse(): arr = [3, 7, 2, 5, 1, 6, 4, 8] assert parallel_bitonic_sort(arr, reverse=True) == [8...
[ { "docstring": null, "function_declaration": "def compare_and_swap(arr, i, j, direction):", "function_name": "compare_and_swap", "parameter_list": "(arr, i, j, direction)" }, { "docstring": null, "function_declaration": "def bitonic_merge(arr, low, cnt, direction):", "function_name":...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import multiprocessing\nfrom typing import List\n\ndef compare_and_swap(arr: List[int], i: int, j: int, direction: bool):\n if direction == (arr[i] > arr[j...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00046339", "row_id": 46339, "seed_ids": "[17]" }
0.631466
Data_Structure_46339
I
[ "compare_and_swap", "bitonic_merge", "bitonic_sort", "parallel_bitonic_sort" ]
4
[ [ "bitonic_merge", "compare_and_swap" ], [ "bitonic_sort", "bitonic_merge" ], [ "parallel_bitonic_sort", "bitonic_merge" ], [ "parallel_bitonic_sort", "bitonic_sort" ] ]
4
[]
false
[]
false
pytest
true
[]
true
bc4ebb6adf3ac797d2a819597780f8fb02fe9e91
f2d0d558a8e01cbd7b5b69fcbac6f2efaa6b19ee
v1.0
instruct
Data_Structure
Data_Structure_46405_I
### Merge Sort Coding Challenge You are given an unsorted list of integers. Your task is to implement the Merge Sort algorithm to sort the list in ascending order. The implementation should follow the principles of Merge Sort and must handle various edge cases efficiently. Your implementation must include: 1. **Funct...
def merge_sort(arr): # Base case for recursion if len(arr) <= 1: return arr mid = len(arr) // 2 # Recursively split the arrays left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) # Create a merged array with sorted order merged = [] merge(left, righ...
from solution import merge_sort def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_two_elements(): assert merge_sort([2, 1]) == [1, 2] def test_merge_sort_random_order(): assert merge_sort([5, 3, 8, 4, 2, 7, 6, 1]) == [1, 2, 3, 4, 5, 6, 7, 8] def test_merge_sort_alre...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right, merged):", "function_name": "merge", "parameter_list": "(left, right, merged)" }...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n # Base case for recursion\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n \n # Recursively split t...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046405", "row_id": 46405, "seed_ids": "[12]" }
0.649513
Data_Structure_46405
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d8b7a27ac454a0df9a23c4b9774122ea13803d30
0918847b320e85071094f5c68aab2a69b390395d
v1.0
instruct
Data_Structure
Data_Structure_46412_I
### Bogo Sort: Implementation and Performance Testing As a crossover between coding challenge and learning exercise, this question will test your understanding of randomized algorithms and their analysis. You are provided with an extremely inefficient sorting algorithm known as **Bogo Sort**. #### Objective - Impleme...
import random def bogo_sort(arr, simulation=False): """ Perform Bogo Sort on an array with optional simulation to print intermediate steps. Parameters: arr (list): List of elements to sort. simulation (bool): If true, print intermediate array states after each shuffle. Returns: list: ...
from solution import bogo_sort, compare_sorts def test_bogo_sort_empty_array(): assert bogo_sort([]) == [] def test_bogo_sort_single_element(): assert bogo_sort([1]) == [1] def test_bogo_sort_sorted_array(): assert bogo_sort([1, 2, 3]) == [1, 2, 3] def test_bogo_sort_unsorted_array(): assert bogo_so...
[ { "docstring": "Perform Bogo Sort on an array with optional simulation to print intermediate steps.\n\nParameters:\narr (list): List of elements to sort.\nsimulation (bool): If true, print intermediate array states after each shuffle.\n\nReturns:\nlist: Sorted list of elements.", "function_declaration": "de...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef bogo_sort(arr, simulation=False):\n \"\"\"\n Perform Bogo Sort on an array with optional simulation to print intermediate steps.\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00046412", "row_id": 46412, "seed_ids": "[16]" }
0.55201
Data_Structure_46412
I
[ "bogo_sort", "compare_sorts" ]
2
[ [ "compare_sorts", "bogo_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c4ff1538012c93ba662d578369d1183cd2e89845
e963d6af07dd853b69167e23f38b03f2af62caae
v1.0
instruct
Data_Structure
Data_Structure_46427_I
### Merge Sort Strategy and Implementation Merge Sort is a well-known sorting algorithm that follows the Divide and Conquer strategy. In this task, you are required to implement this sorting algorithm. The algorithm involves three core steps: 1. **Divide**: Recursively split the array into two halves until each subarr...
def merge_sort(arr): """ Sorts an array using the Merge Sort algorithm. Parameters: arr (list): A list of elements to be sorted. Returns: list: A new sorted list containing the elements from arr in ascending order. """ if len(arr) <= 1: return arr mid = len(arr...
from solution import merge_sort, merge def test_merge_sort_basic(): arr = [38, 27, 43, 3, 9, 82, 10] assert merge_sort(arr) == [3, 9, 10, 27, 38, 43, 82] def test_merge_sort_single_element(): arr = [1] assert merge_sort(arr) == [1] def test_merge_sort_sorted(): arr = [1, 2, 3, 4, 5] assert me...
[ { "docstring": "Sorts an array using the Merge Sort algorithm.\n\nParameters:\narr (list): A list of elements to be sorted.\n\nReturns:\nlist: A new sorted list containing the elements from arr in ascending order.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "para...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array using the Merge Sort algorithm.\n \n Parameters:\n arr (list): A list of elements to be sorted.\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046427", "row_id": 46427, "seed_ids": "[12]" }
0.659835
Data_Structure_46427
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
95697d8e9b484402938a1fc5bd6e4ef4e21dae16
eaec0332e6c0dad1765f5b05109612a29c943df9
v1.0
instruct
Data_Structure
Data_Structure_46428_I
Subtree Validation **Context**: You are working on ensuring the structural integrity of hierarchical data in a large database system. Your specific task is to write a function to determine if a given tree `t` is a subtree of another tree `s`. **Problem Statement**: Write a function `is_subtree(s, t)` that takes the...
class TreeNode: def __init__(self, val: int = 0, left: 'TreeNode' = None, right: 'TreeNode' = None): self.val = val self.left = left self.right = right def is_subtree(s: TreeNode, t: TreeNode) -> bool: if not s: return False if is_same_tree(s, t): return True ret...
from solution import TreeNode, is_subtree, is_same_tree def test_is_subtree_example1(): s = TreeNode(3, TreeNode(4, TreeNode(1), TreeNode(2)), TreeNode(5)) t = TreeNode(4, TreeNode(1), TreeNode(2)) assert is_subtree(s, t) == True def test_is_subtree_example2(): s = TreeNode(3, TreeNode(4, TreeNode(1),...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046428", "row_id": 46428, "seed_ids": "[288]" }
0.574312
Data_Structure_46428
I
[ "is_subtree", "is_same_tree" ]
2
[ [ "is_subtree", "is_same_tree" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
85c8f15d4543ba8aefede041ed86118df6539f49
eb050958f642d7b31ab2e0a7b061667b43cd3d3f
v1.0
instruct
Data_Structure
Data_Structure_46450_I
**Unique File Sort** **Scenario**: You are part of a software development team that handles the storage of numerous files with varying sizes. Your task is to create an efficient sorting algorithm to sort these files by their sizes. Instead of simple sorting, you will use heap sort. **Problem Statement**: Implement a...
from typing import List def heapify(arr: List[int], n: int, i: int): ''' To maintain the heap property of a max-heap ''' largest = i # Initialize largest as root left = 2 * i + 1 # left = 2*i + 1 right = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists and is greater than ...
from solution import unique_file_sort def test_unique_file_sort_example_1(): input = [9, 4, 7, 1, -2, 6, 5] output = [9, 7, 6, 5, 4, 1, -2] assert unique_file_sort(input) == output def test_unique_file_sort_example_2_empty(): input = [] output = [] assert unique_file_sort(input) == output def...
[ { "docstring": "To maintain the heap property of a max-heap", "function_declaration": "def heapify(arr, n, i):", "function_name": "heapify", "parameter_list": "(arr, n, i)" }, { "docstring": "Performs heap sort to sort the array in descending order", "function_declaration": "def unique_f...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef heapify(arr: List[int], n: int, i: int):\n \"\"\"\n Function to maintain the max-heap property for a push down operation....
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046450", "row_id": 46450, "seed_ids": "[8]" }
0.603117
Data_Structure_46450
I
[ "heapify", "unique_file_sort" ]
2
[ [ "unique_file_sort", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9ff1875938b326c8b3445160f4a5766e32c0bea3
ad56fb9a91ca62dd241040d12bd976aa30f7edc4
v1.0
instruct
Data_Structure
Data_Structure_46462_I
Given an array of integers, implement a data structure that supports the following operations efficiently: 1. **Update**: Update the value of an element in the array. 2. **Prefix Sum**: Calculate the sum of the elements from the beginning of the array to a given index. You need to implement a Fenwick Tree to handle t...
from typing import List def update(bit_tree: List[int], n: int, i: int, val: int) -> None: """ Updates the Fenwick Tree by adding `val` at index `i`. """ i += 1 # Fenwick Tree is 1-indexed internally while i <= n: bit_tree[i] += val i += i & -i def get_sum(bit_tree: List[int], i: ...
import pytest from solution import update, get_sum, construct def test_construct(): arr = [3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3] bit_tree = construct(arr) prefix_sums = [3, 5, 4, 10, 15, 19, 16, 19, 26, 28, 31] for i, sum_val in enumerate(prefix_sums): assert get_sum(bit_tree, i) == sum_val def t...
[ { "docstring": "Updates the Fenwick Tree by adding `val` at index `i`.", "function_declaration": "def update(bit_tree, n, i, val):", "function_name": "update", "parameter_list": "(bit_tree, n, i, val)" }, { "docstring": "Returns the prefix sum from the start of the array to index `i`.", ...
[ 0, 0, 0, 1, 1, 0, 1, 0, 1 ]
4
medium
0.444
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def update(bit_tree, n, i, val):\n i += 1 # Fenwick Tree is 1-based index.\n while i <= n:\n bit_tree[i] += val\n i += (i & -i)\n\ndef ge...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00046462", "row_id": 46462, "seed_ids": "[305]" }
0.48971
Data_Structure_46462
I
[ "update", "get_sum", "construct" ]
3
[ [ "construct", "update" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e59eb430800e5d1b40ae1b70624622b03650e603
ddf9c3ba7454055cee25b4a5cbe81b3decb265b3
v1.0
instruct
Data_Structure
Data_Structure_46506_I
### Insertion Sort Helper Function Implementation #### Objective: Design a function that uses the given `search_insert` helper method to implement the Insertion Sort algorithm. #### Description: Write a Python function `insertion_sort(array)` that takes an array of integers and sorts it in ascending order using the I...
def search_insert(array, value, end): """ This function helps to find the position where the value should be inserted in the array[0:end] to maintain the sorted order. """ for i in range(end): if array[i] > value: return i return end def insertion_sort(array): """ So...
from solution import insertion_sort def test_insertion_sort_with_positive_numbers(): assert insertion_sort([4, 3, 2, 1]) == [1, 2, 3, 4] assert insertion_sort([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13] def test_insertion_sort_with_mixed_numbers(): assert insertion_sort([1, 3, 2, 5, 6, 4]) == [1, 2, 3, 4, 5...
[ { "docstring": "This function helps to find the position where the value should be inserted\nin the array[0:end] to maintain the sorted order.", "function_declaration": "def search_insert(array, value, end):", "function_name": "search_insert", "parameter_list": "(array, value, end)" }, { "do...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def insertion_sort(array):\n def search_insert(sub_array, value):\n for i in range(len(sub_array)):\n if sub_array[i] > value:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046506", "row_id": 46506, "seed_ids": "[199]" }
0.615645
Data_Structure_46506
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3b3fb8f88f340ce4ee730262d77e0f65c69b5dd4
db0609755f2f99722911b40030da174bd7834775
v1.0
instruct
Data_Structure
Data_Structure_46512_I
### Question: Advanced Bucket Sort Implementation You are tasked with implementing an advanced bucket sort function that uses a dynamic approach to bucket creation and a more efficient nested sorting algorithm. The goal is to handle large datasets and varying distributions effectively. #### Task: Implement the functi...
def merge_sort(arr): """ Helper function to perform merge sort on an array. """ if len(arr) > 1: mid = len(arr) // 2 left_half = arr[:mid] right_half = arr[mid:] merge_sort(left_half) merge_sort(right_half) i = j = k = 0 ...
def test_merge_sort(): assert merge_sort([4, 2, 7, 1, 3]) == [1, 2, 3, 4, 7] assert merge_sort([15, -2, 8, 5, 0]) == [-2, 0, 5, 8, 15] assert merge_sort([]) == [] assert merge_sort([1]) == [1] assert merge_sort([5, 5, 5]) == [5, 5, 5] def test_advanced_bucket_sort(): assert advanced_bucket_sort...
[ { "docstring": "Helper function to perform merge sort on an array.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def advanced_bucket_sort(arr):", "function_name": "advanced_b...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n left_half = arr[:mid]\n right_half = arr[mid:]\n \n merg...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00046512", "row_id": 46512, "seed_ids": "[26]" }
0.567939
Data_Structure_46512
I
[ "merge_sort", "advanced_bucket_sort" ]
2
[ [ "advanced_bucket_sort", "merge_sort" ] ]
1
[]
false
[]
false
pytest
false
[]
true
6b551dfec21361c7433f6b4e43c341c679c2424d
6f7dd6cee14d1a37875cfa315208786a6aa61111
v1.0
instruct
Data_Structure
Data_Structure_46534_I
### Merge Sort Assessment Question **Objective**: You are tasked with implementing a sorting algorithm called Merge Sort. This algorithm should take an array of integers as input and return the array sorted in non-decreasing order. **Input Format**: A single list of integers `arr` where `0 <= len(arr) <= 10^5` and a...
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts an array of integers using Merge Sort algorithm. - The function is stable and maintains O(n log n) time complexity. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) ...
from solution import merge_sort def test_merge_sort_example1(): arr = [4, 2, 5, 1, 6, 3] assert merge_sort(arr) == [1, 2, 3, 4, 5, 6] def test_merge_sort_example2(): arr = [] assert merge_sort(arr) == [] def test_merge_sort_example3(): arr = [7, -3, 4, -1, 6, -5] assert merge_sort(arr) == [-5...
[ { "docstring": "Sorts an array of integers using Merge Sort algorithm.\n- The function is stable and maintains O(n log n) time complexity.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merges two sorted lists int...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n # Divide step\n mid = len(arr) //...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046534", "row_id": 46534, "seed_ids": "[12]" }
0.683861
Data_Structure_46534
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
21016fee6855b355cd9962e72d08901ee1fc4463
f83f0a0fff5a80f2081ab7d94c7f460bd80a066e
v1.0
instruct
Data_Structure
Data_Structure_46544_I
#### Context You were recently hired by a company that manages oil pipelines. They need a program to compute the maximum flow of oil from the main reservoir (source) to the base station (sink) through a complex network of pipes. Each pipe has a certain capacity, and you need to use network flow algorithms to determine ...
from collections import deque # Helper function to perform BFS for Edmonds-Karp def bfs(C, F, source, sink, parent): visited = [False] * len(C) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() for v in range(len(C)): if not visited[v] and C[u...
from solution import compare_flow_algorithms def test_compare_flow_algorithms(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 result = c...
[ { "docstring": null, "function_declaration": "def bfs(C, F, source, sink, parent):", "function_name": "bfs", "parameter_list": "(C, F, source, sink, parent)" }, { "docstring": null, "function_declaration": "def ford_fulkerson(C, source, sink):", "function_name": "ford_fulkerson", ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\n# Ford-Fulkerson Algorithm using DFS\ndef ford_fulkerson(capacity, source, sink):\n n = len(capacity)\n residual_capaci...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00046544", "row_id": 46544, "seed_ids": "[240]" }
0.609315
Data_Structure_46544
I
[ "bfs", "ford_fulkerson", "edmonds_karp", "bfs_dinic", "dfs_dinic", "dinic", "compare_flow_algorithms" ]
7
[ [ "compare_flow_algorithms", "dinic" ], [ "compare_flow_algorithms", "edmonds_karp" ], [ "compare_flow_algorithms", "ford_fulkerson" ], [ "dinic", "bfs_dinic" ], [ "dinic", "dfs_dinic" ], [ "edmonds_karp", "ford_fulkerson" ], [ "ford_fulker...
7
[]
false
[]
false
pytest
true
[]
true
4d84f7490d9ba7e2e0fd3be26468e18888c1356e
03c0f4a6a61f628a367c5fe926d8b532105365c2
v1.0
instruct
Data_Structure
Data_Structure_46608_I
### Bucket Sort Implementation **Scenario**: You are given the task of implementing the Bucket Sort algorithm to sort an array of floating-point numbers in the range [0, 1). Bucket Sort is particularly effective in this case due to the uniform distribution characteristic. **Task**: Write a function named `bucket_s...
def insertion_sort(arr): """ Helper function to sort array using insertion sort. """ for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr def bucket_sort(arr)...
from solution import bucket_sort def test_empty_array(): assert bucket_sort([]) == [] def test_single_element_array(): assert bucket_sort([0.5]) == [0.5] def test_sorted_array(): assert bucket_sort([0.1, 0.4, 0.6, 0.7, 0.9]) == [0.1, 0.4, 0.6, 0.7, 0.9] def test_reverse_sorted_array(): assert bucket...
[ { "docstring": "Helper function to sort array using insertion sort.", "function_declaration": "def insertion_sort(arr):", "function_name": "insertion_sort", "parameter_list": "(arr)" }, { "docstring": "Sorts an array of floating-point numbers in the range [0, 1) using bucket sort.", "fun...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def bucket_sort(arr):\n ''' Bucket Sort\n Complexity: O(n^2) in the worst case\n Average Time Complexity: O(n)\n '''\n if len(arr) == 0...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046608", "row_id": 46608, "seed_ids": "[26]" }
0.54276
Data_Structure_46608
I
[ "insertion_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e93b3d45bb610b377b2e9db5fabb8dd32f0df33e
73b6a523292bce38900263b330fa349a5230ccb1
v1.0
instruct
Data_Structure
Data_Structure_46610_I
You have been hired as a software engineer by a company that specializes in DNA sequence analysis. As part of their analytical toolset, you are required to implement a function that efficiently searches for patterns within a DNA sequence using the Knuth-Morris-Pratt (KMP) string matching algorithm. #### Problem Statem...
from typing import List def compute_lps_array(pattern: str) -> List[int]: """ KMP algorithm helper function that preprocesses the pattern to produce the longest prefix suffix (LPS) array. """ lps = [0] * len(pattern) length = 0 i = 1 while i < len(pattern): if pattern[i] == pat...
from solution import dna_pattern_search def test_dna_pattern_search_case1(): assert dna_pattern_search("ACGTACGTGACG", "ACG") == [0, 4, 9] def test_dna_pattern_search_case2(): assert dna_pattern_search("GATTACA", "GATT") == [0] def test_dna_pattern_search_case3(): assert dna_pattern_search("AGCTAGC", "GG...
[ { "docstring": "KMP algorithm helper function that preprocesses the pattern to produce the longest prefix suffix (LPS) array.", "function_declaration": "def compute_lps_array(pattern):", "function_name": "compute_lps_array", "parameter_list": "(pattern)" }, { "docstring": "Function to search...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef compute_lps_array(pattern: str) -> List[int]:\n \"\"\"\n KMP algorithm helper function that preprocesses the pattern to p...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00046610", "row_id": 46610, "seed_ids": "[93]" }
0.55082
Data_Structure_46610
I
[ "compute_lps_array", "dna_pattern_search" ]
2
[ [ "dna_pattern_search", "compute_lps_array" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1a94f123d39e875866586c15e221359e1c884e36
b3388d3adf31c0d3c34cd540a0a4e8ff1fe733c9
v1.0
instruct
Data_Structure
Data_Structure_46616_I
### Matrix Operations: Determinant Calculator and Minor Matrix Extractor #### Objective: Implement functions to calculate the determinant of a matrix and extract minors, which are fundamental steps in more complex algorithms, such as matrix inversion. #### Task: 1. Implement a function `calculate_determinant(matrix)`...
def calculate_determinant(matrix): """ Computes the determinant of a given square matrix. """ # Base case for 2x2 matrix if len(matrix) == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] determinant = 0 for c in range(len(matrix)): determinant += ((-1) **...
def test_calculate_determinant_2x2(): matrix = [ [4, 6], [3, 8] ] assert calculate_determinant(matrix) == 14 def test_calculate_determinant_3x3(): matrix = [ [6, 1, 1], [4, -2, 5], [2, 8, 7] ] assert calculate_determinant(matrix) == -306 def test_calcula...
[ { "docstring": "Computes the determinant of a given square matrix.", "function_declaration": "def calculate_determinant(matrix):", "function_name": "calculate_determinant", "parameter_list": "(matrix)" }, { "docstring": "Extracts the minor of the matrix by removing the specified row and colu...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_determinant(matrix):\n \"\"\"\n Returns the determinant of a given square matrix.\n \"\"\"\n n = len(matrix)\n \n if n == 2:\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046616", "row_id": 46616, "seed_ids": "[347]" }
0.480128
Data_Structure_46616
I
[ "calculate_determinant", "extract_minor" ]
2
[ [ "calculate_determinant", "extract_minor" ] ]
1
[]
false
[]
false
pytest
false
[]
true
43d44b7b27f74abd03898245c76c3ba79492befd
400649b020f7807697ff5a0ff38f662d33e0aa99
v1.0
instruct
Data_Structure
Data_Structure_46625_I
### Question ### Check Digit-Powered Numbers Your task is to implement a function `find_digit_powered_numbers(low, high)` that takes two integers `low` and `high` as input parameters and returns a list of all numbers within this range (inclusive) that can be expressed as the sum of their digits each raised to consecu...
def sum_of_digits_to_consecutive_powers(n): digits = [int(d) for d in str(n)] return sum(d**(i+1) for i, d in enumerate(digits)) def find_digit_powered_numbers(low, high): result = [] for n in range(low, high): if n == sum_of_digits_to_consecutive_powers(n): result.append(n) ret...
from solution import find_digit_powered_numbers def test_single_digit_range(): assert find_digit_powered_numbers(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9] def test_double_digit_range(): assert find_digit_powered_numbers(10, 100) == [89] def test_edge_case_lower_bound(): assert find_digit_powered_numbers(89, ...
[ { "docstring": null, "function_declaration": "def sum_of_digits_to_consecutive_powers(n):", "function_name": "sum_of_digits_to_consecutive_powers", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def find_digit_powered_numbers(low, high):", "function_name": "...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_digit_powered_numbers(low, high):\n \"\"\"\n Returns a list of numbers between low and high (inclusive) that can be expressed\n as the sum o...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00046625", "row_id": 46625, "seed_ids": "[135]" }
0.612047
Data_Structure_46625
I
[ "sum_of_digits_to_consecutive_powers", "find_digit_powered_numbers" ]
2
[ [ "find_digit_powered_numbers", "sum_of_digits_to_consecutive_powers" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8c406c488091f48e457bebf7bc2dd9259036e748
c916cb7510dad92e2071350fb36efd855cc93761
v1.0
instruct
Data_Structure
Data_Structure_46646_I
### Insertion Sort Implementation with Optimization #### Objective You are tasked with implementing a function that sorts an array using the Insertion Sort algorithm. To optimize the insertion process, you should use binary search to determine the appropriate position to insert each element. #### Specification Write ...
from typing import List def search_insert(arr: List[int], val: int, start: int, end: int) -> int: """ Returns the index at which val should be inserted into arr to maintain sorted order. This function performs binary search in the subarray arr[start:end]. """ while start < end: mid = (start...
from solution import insertion_sort_optimized def test_already_sorted(): assert insertion_sort_optimized([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted(): assert insertion_sort_optimized([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_mixed_values(): assert insertion_sort_optimized([12, 11, 13,...
[ { "docstring": "Returns the index at which val should be inserted into arr to maintain sorted order.\nThis function performs binary search in the subarray arr[start:end].", "function_declaration": "def search_insert(arr, val, start, end):", "function_name": "search_insert", "parameter_list": "(arr, ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef search_insert(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Helper function to find the index where ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046646", "row_id": 46646, "seed_ids": "[199]" }
0.590859
Data_Structure_46646
I
[ "search_insert", "insertion_sort_optimized" ]
2
[ [ "insertion_sort_optimized", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
52adc2e28fb90cea703121f017026841cf2f32f4
06ae4fc960ae32855426f72ab59953393ba8d5fc
v1.0
instruct
Data_Structure
Data_Structure_46708_I
You are tasked with implementing a maximum flow algorithm for an application that models a city's water distribution network. Given the capacities of the pipes (edges) between different facilities (nodes), your objective is to determine the maximum amount of water that can be transported from the city's water source to...
from typing import List from collections import deque def bfs(residual_capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool: visited = [False] * len(residual_capacity) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() ...
from solution import max_water_flow def test_max_water_flow_example(): capacity = [ [0, 10, 10, 0, 0, 0], [0, 0, 1, 10, 0, 0], [0, 0, 0, 0, 10, 0], [0, 0, 0, 0, 0, 10], [0, 0, 0, 0, 0, 10], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert max_water_flo...
[ { "docstring": null, "function_declaration": "def bfs(residual_capacity, source, sink, parent):", "function_name": "bfs", "parameter_list": "(residual_capacity, source, sink, parent)" }, { "docstring": null, "function_declaration": "def max_water_flow(capacity, source, sink):", "func...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef bfs(capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n \"\"\"\n Returns True if there is a ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046708", "row_id": 46708, "seed_ids": "[240]" }
0.670741
Data_Structure_46708
I
[ "bfs", "max_water_flow" ]
2
[ [ "max_water_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
47928cfa04612832994ad08ca7928877299747f6
7be48b05e41efdadcf4e99cf94e1014fcbe036c6
v1.0
instruct
Data_Structure
Data_Structure_46736_I
#### Objective Write a function to invert a given `n x n` matrix. Your implementation should particularly focus on matrices larger than `2 x 2`, utilizing the fundamental principles of matrix inversion as analyzed above. Ensure your code handles edge cases and invalid inputs appropriately. #### Function Signature ```p...
from typing import List def get_matrix_minor(matrix: List[List[float]], i: int, j: int) -> List[List[float]]: return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])] def get_matrix_determinant(matrix: List[List[float]]) -> float: # Base case for 2x2 matrix if len(matrix) == 2: return m...
from solution import invert_matrix def test_invert_2x2_matrix(): matrix = [ [4, 7], [2, 6] ] expected = [ [0.6, -0.7], [-0.2, 0.4] ] assert invert_matrix(matrix) == expected def test_invert_3x3_matrix(): matrix = [ [1, 2, 3], [0, 1, 4], [...
[ { "docstring": null, "function_declaration": "def get_matrix_minor(matrix, i, j):", "function_name": "get_matrix_minor", "parameter_list": "(matrix, i, j)" }, { "docstring": null, "function_declaration": "def get_matrix_determinant(matrix):", "function_name": "get_matrix_determinant"...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef determinant(matrix: List[List[float]], n: int) -> float:\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046736", "row_id": 46736, "seed_ids": "[347]" }
0.545747
Data_Structure_46736
I
[ "get_matrix_minor", "get_matrix_determinant", "get_matrix_inverse", "invert_matrix" ]
4
[ [ "get_matrix_determinant", "get_matrix_minor" ], [ "get_matrix_inverse", "get_matrix_determinant" ], [ "get_matrix_inverse", "get_matrix_minor" ], [ "invert_matrix", "get_matrix_inverse" ] ]
4
[]
false
[]
false
pytest
true
[]
true
5a470ba37b5b101e604bb743f6385a4b6e14a7cc
4cd62ccd37d5b88da128115024925363043a0958
v1.0
instruct
Data_Structure
Data_Structure_46752_I
### Insertion Sort Algorithm Implementation **Objective**: Implement the full insertion sort algorithm utilizing the provided `search_insert` helper function. ### Scenario You are given an unsorted array and need to sort it using insertion sort. To optimize the insertion process, you will use the `search_insert` hel...
def search_insert(sorted_list, value): """ Helper function to find the insertion index for a value in a sorted list. :param sorted_list: List of sorted integers. :param value: Integer value to be inserted. :return: Index at which `value` should be inserted to keep the list sorted. """ left, ...
from solution import insertion_sort def test_empty_array(): assert insertion_sort([]) == [] def test_single_element_array(): assert insertion_sort([1]) == [1] def test_sorted_array(): assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): assert insertion_sort([5,...
[ { "docstring": "Helper function to find the insertion index for a value in a sorted list.\n:param sorted_list: List of sorted integers.\n:param value: Integer value to be inserted.\n:return: Index at which `value` should be inserted to keep the list sorted.", "function_declaration": "def search_insert(sorte...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def search_insert(sorted_array, target):\n \"\"\"\n Helper function to find the position where `target` should be \n inserted in the sorted subarray ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046752", "row_id": 46752, "seed_ids": "[199]" }
0.613885
Data_Structure_46752
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
75a0a4f60110526af9a4805032893f5658774252
c9766cc1b98690cdda6bf1f61c9b20542eea7f37
v1.0
instruct
Data_Structure
Data_Structure_46784_I
You have learned about various sorting algorithms and their efficiencies. One of the least efficient sorting algorithms is the Bogo Sort, which relies on random permutations of the list until it gets sorted. Despite its impracticality, it provides a good exercise to understand the concept of algorithm efficiency and ra...
import random def is_sorted(arr): """ Helper function to check if the array is sorted. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort(arr, simulation=False): """ Sorts the provided array using Bogo Sort. Parameters:...
from solution import bogo_sort def test_empty_list(): assert bogo_sort([]) == [] def test_single_element_list(): assert bogo_sort([1]) == [1] def test_sorted_list(): assert bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_list(): assert bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4,...
[ { "docstring": "Helper function to check if the array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts the provided array using Bogo Sort.\n\nParameters:\narr (list): A list of integers.\nsimulation (...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef bogo_sort(arr: list, simulation: bool=False) -> list:\n \"\"\"\n Sorts the provided array using Bogo Sort.\n \n Parameters:\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00046784", "row_id": 46784, "seed_ids": "[16]" }
0.644447
Data_Structure_46784
I
[ "is_sorted", "bogo_sort" ]
2
[ [ "bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
04c1f27db1cf3ed73b1a3ada6bfe3f832a81d5ad
7d53ceb3499266f6cddfdb3781cb3939eb21c7ba
v1.0
instruct
Data_Structure
Data_Structure_46792_I
#### Bogo Sort Improvement Challenge You are given an unsorted array `arr` of integers. Your task is to implement an improved version of Bogo Sort that minimizes the number of shuffles required on average. The new algorithm should introduce optimizations, such as: 1. Pre-check for elements that are already in place. 2...
import random from typing import List def is_sorted(arr: List[int]) -> bool: """ Helper function to check if an array is sorted. """ return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) def improved_bogo_sort(arr: List[int]) -> List[int]: """ Sort the input array using an improved ver...
from solution import improved_bogo_sort def test_improved_bogo_sort_already_sorted(): assert improved_bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_improved_bogo_sort_reversed(): assert improved_bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_improved_bogo_sort_random_order(): assert impr...
[ { "docstring": "Helper function to check if an array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sort the input array using an improved version of bogo sort.", "function_declaration": "def improved...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List\n\ndef improved_bogo_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Improved version of Bogo Sort that minimizes t...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046792", "row_id": 46792, "seed_ids": "[16]" }
0.562636
Data_Structure_46792
I
[ "is_sorted", "improved_bogo_sort" ]
2
[ [ "improved_bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5f465b0c1ead80ea6ced9f8279a3a4169469b2cd
540c77e9a9ca0285fc1982b0d0d4d014e9937a23
v1.0
instruct
Data_Structure
Data_Structure_46793_I
### Matrix Power Computation You are given three functions that perform matrix operations: `multiply` for matrix multiplication, `identity` for generating an identity matrix, and `matrix_exponentiation` for computing the power of a matrix. Your task is to implement a function `matrix_power_sequence` that takes a squa...
def multiply(A, B): """ Multiplies two matrices A and B """ d = len(A) result = [[0] * d for _ in range(d)] for i in range(d): for j in range(d): for k in range(d): result[i][j] += A[i][k] * B[k][j] return result def identity(d): """ Returns the i...
from solution import multiply, identity, matrix_exponentiation, matrix_power_sequence def test_multiply(): assert multiply([[1, 2], [3, 4]], [[1, 0], [0, 1]]) == [[1, 2], [3, 4]] assert multiply([[2, 1], [1, 2]], [[0, 1], [1, 0]]) == [[1, 2], [2, 1]] def test_identity(): assert identity(2) == [[1, 0], [0,...
[ { "docstring": "Multiplies two matrices A and B", "function_declaration": "def multiply(A, B):", "function_name": "multiply", "parameter_list": "(A, B)" }, { "docstring": "Returns the identity matrix of size d x d", "function_declaration": "def identity(d):", "function_name": "identi...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B\n \"\"\"\n d = len(A)\n result = [[0] * d for _ in range(d)]\n for i in range...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00046793", "row_id": 46793, "seed_ids": "[340]" }
0.549394
Data_Structure_46793
I
[ "multiply", "identity", "matrix_exponentiation", "matrix_power_sequence" ]
4
[ [ "matrix_exponentiation", "identity" ], [ "matrix_exponentiation", "multiply" ], [ "matrix_power_sequence", "matrix_exponentiation" ] ]
3
[]
false
[]
false
pytest
true
[]
true
395902947f5b58e4a93c244ef3534b4cf4547f4c
56a402db4e689b7bc795c0606674e5eb3cc980c5
v1.0
instruct
Data_Structure
Data_Structure_46817_I
### Maximum Flow in a Network **Context**: You are managing a network where you need to optimize the maximum flow from a source node to a sink node. You have been provided with three algorithms for calculating the maximum flow in a network: Ford-Fulkerson (using DFS), Edmonds-Karp (using BFS), and Dinic's Algorithm. ...
from typing import List from collections import deque def bfs(residual_capacity, source, sink, parent): """ A Breadth-First Search (BFS) based method to find if there is a path from source to sink in residual graph. Also fills parent[] to store the path. """ visited = [False] * len(residual_capacit...
def test_max_flow_simple(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert compute_max_flow(capacity, source, sink) == 23 def test_...
[ { "docstring": "A Breadth-First Search (BFS) based method to find if there is a path from source to sink in residual graph.\nAlso fills parent[] to store the path.", "function_declaration": "def bfs(residual_capacity, source, sink, parent):", "function_name": "bfs", "parameter_list": "(residual_capa...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\nfrom typing import List\n\ndef edmonds_karp(capacity: List[List[int]], source: int, sink: int) -> int:\n n = len(capacity)\n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00046817", "row_id": 46817, "seed_ids": "[240]" }
0.566526
Data_Structure_46817
I
[ "bfs", "edmonds_karp" ]
2
[ [ "edmonds_karp", "bfs" ] ]
1
[]
false
[]
false
pytest
false
[]
true
30ad83fba41f4fcfe58ce534b5bdca356f173eef
a8b50e1760bc8107a4d775356923b0c92f49cf9a
v1.0
instruct
Data_Structure
Data_Structure_46859_I
You have been tasked to extend the function `contain_string` to increase its efficiency. The current implementation performs a brute-force search to find the index of the first occurrence of a substring (needle) within a larger string (haystack). However, this approach can be slow for large inputs due to its O(n*m) tim...
def build_lps(needle): """ Builds the longest prefix which is also suffix array (lps) for the KMP algorithm. """ lps = [0] * len(needle) length = 0 # length of the previous longest prefix suffix i = 1 while i < len(needle): if needle[i] == needle[length]: length += 1 ...
from solution import contain_string_optimized def test_contain_string_optimized_found(): assert contain_string_optimized("abxabcabcaby", "abcaby") == 6 assert contain_string_optimized("hello", "ll") == 2 assert contain_string_optimized("aaaaa", "bba") == -1 assert contain_string_optimized("aaabaaaabaaa...
[ { "docstring": "Builds the longest prefix which is also suffix array (lps) for the KMP algorithm.", "function_declaration": "def build_lps(needle):", "function_name": "build_lps", "parameter_list": "(needle)" }, { "docstring": "Uses the KMP algorithm to find the index of the first occurrence...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def build_lps(needle):\n \"\"\"\n Builds the longest prefix which is also suffix array (lps) for the KMP algorithm.\n \"\"\"\n lps = [0] * len(nee...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00046859", "row_id": 46859, "seed_ids": "[86]" }
0.614318
Data_Structure_46859
I
[ "build_lps", "contain_string_optimized" ]
2
[ [ "contain_string_optimized", "build_lps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
35385dc64f75c9aaf47b7c1540d1a9c91a1f165c
5ad93d86160a15b490622a054ca31182e0f94d4c
v1.0
instruct
Data_Structure
Data_Structure_46862_I
### Coding Challenge: Implement and Optimize Merge Sort **Objective**: Given an array of integers, you are required to implement the Merge Sort algorithm. Your implementation should handle the array in an efficient manner and should work correctly for all edge cases. **Requirements**: - Implement the `merge_sort` fun...
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:]) # Perform in-place merging merge(left, right, arr) return arr def merge(left, right, merged): left_cursor, right_cursor = 0, 0 while left_cursor < le...
from solution import merge_sort def test_merge_sort_empty(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_sorted(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_sorted(): assert merge_sort([5,...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right, merged):", "function_name": "merge", "parameter_list": "(left, right, merged)" }...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n if len(arr) <= 1:\n return arr\n mid = len(arr) // 2\n left = merge_sort(arr[:mid])\n right = merge_sort(arr[mid:])\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046862", "row_id": 46862, "seed_ids": "[12]" }
0.674263
Data_Structure_46862
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b6d42ecc3f4a8b00cfb8a0221ab5ca29c448ee45
72ab11ccc9bc7d7cb01e330485a24f504ff5aa48
v1.0
instruct
Data_Structure
Data_Structure_46876_I
### Bogo Sort Simulation and Analysis #### Objective Given a sorting algorithm, Bogo Sort, which sorts an array by repeatedly shuffling it until it is sorted, your task is to implement a function that evaluates its performance and analyze the iterations it takes to sort arrays of different sizes. #### Prompt 1. **Imp...
import random def is_sorted(arr): """ Checks if the array is sorted in non-decreasing order. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort(arr, max_iter=10000): """ Sorts an array using Bogo Sort algorithm and returns t...
from solution import bogo_sort, evaluate_performance def test_is_sorted(): assert is_sorted([1, 2, 3, 4, 5]) == True assert is_sorted([5, 4, 3, 2, 1]) == False assert is_sorted([1, 1, 2, 2, 3]) == True def test_bogo_sort(): sorted_arr, iterations = bogo_sort([1, 2, 3]) assert sorted_arr == [1, 2, ...
[ { "docstring": "Checks if the array is sorted in non-decreasing order.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts an array using Bogo Sort algorithm and returns the sorted array along with\nthe number of i...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef bogo_sort(arr, max_iter=10000):\n \"\"\"\n Sorts the array using Bogo Sort and returns the number of iterations it took.\n Args:...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046876", "row_id": 46876, "seed_ids": "[16]" }
0.504186
Data_Structure_46876
I
[ "is_sorted", "bogo_sort", "evaluate_performance" ]
3
[ [ "bogo_sort", "is_sorted" ], [ "evaluate_performance", "bogo_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
aa8ef12b0a0aae4391402c2efb99e00553257702
0bd8834a76d3750ef283b845c27050fb4c00216e
v1.0
instruct
Data_Structure
Data_Structure_46940_I
Implement In-Place Merge Sort You are tasked to implement the merge sort algorithm with minimal space usage by merging the sorted halves within the original array without using additional subarrays. #### Problem Statement Write a function `merge_sort_inplace(arr)` that sorts an array `arr` of integers in non-decreas...
from typing import List def merge(arr: List[int], start: int, mid: int, end: int) -> None: """ Merges two sorted halves of the array in place. """ start2 = mid + 1 # If the direct merge is already sorted if arr[mid] <= arr[start2]: return # Two pointers to maintain start of both...
import pytest from solution import merge_sort_inplace def test_merge_sort_inplace_with_positive_numbers(): arr = [4, 2, 5, 1, 3] merge_sort_inplace(arr) assert arr == [1, 2, 3, 4, 5] def test_merge_sort_inplace_with_mixed_numbers(): arr = [10, -1, 2, 5, 0] merge_sort_inplace(arr) assert arr ==...
[ { "docstring": "Merges two sorted halves of the array in place.", "function_declaration": "def merge(arr, start, mid, end):", "function_name": "merge", "parameter_list": "(arr, start, mid, end)" }, { "docstring": null, "function_declaration": "def merge_sort_inplace(arr, l=0, r=None):", ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort_inplace(arr: List[int]) -> None:\n \"\"\"\n Perform in-place merge sort on the given array.\n \"\"\"\n d...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046940", "row_id": 46940, "seed_ids": "[12]" }
0.638862
Data_Structure_46940
I
[ "merge", "merge_sort_inplace" ]
2
[ [ "merge_sort_inplace", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
05db4ca5b03aee7cec149145e3d01512c355a417
07311119055bd4efa43ec34896a786cd6014ad13
v1.0
instruct
Data_Structure
Data_Structure_46949_I
### Question **RSA Key Generation and Encryption/Decryption** The RSA algorithm is widely used for secure data transmission. This question tasks you with implementing the RSA key generation, encryption, and decryption process. The RSA algorithm involves generating three numbers \(n\), \(e\), and \(d\) which are used f...
import random from typing import Tuple from sympy import isprime, mod_inverse def generate_prime(bits, seed=None): if seed: random.seed(seed) while True: p = random.getrandbits(bits) if isprime(p): return p def generate_key(k: int, seed: int = None) -> Tuple[int, int, int]:...
import pytest from solution import generate_key, encrypt, decrypt def test_generate_key_valid(): k = 16 n, e, d = generate_key(k) assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) def test_generate_key_invalid_k(): with pytest.raises(ValueError): generate_ke...
[ { "docstring": null, "function_declaration": "def generate_prime(bits, seed=None):", "function_name": "generate_prime", "parameter_list": "(bits, seed=None)" }, { "docstring": null, "function_declaration": "def generate_key(k, seed=None):", "function_name": "generate_key", "param...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import Tuple\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime(bits, seed=None):\n if seed:\n random.seed(see...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00046949", "row_id": 46949, "seed_ids": "[154]" }
0.606866
Data_Structure_46949
I
[ "generate_prime", "generate_key", "encrypt", "decrypt" ]
4
[ [ "generate_key", "generate_prime" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
ce7db06ab03d6ed14f90d346eb777d1c2a0959c6
2a86ba517f9609cd127f2dd58af814f60665b144
v1.0
instruct
Data_Structure
Data_Structure_46975_I
You are given an implementation of a Red-Black Tree. This self-balancing binary search tree structure ensures that the tree remains balanced with standard operations performed in O(log n) time complexity. Your task is to enhance the Red-Black Tree by implementing an additional function called `find_inorder_successor`,...
class RBNode: def __init__(self, val, color, left=None, right=None, parent=None): self.val = val self.color = color self.left = left self.right = right self.parent = parent class RBTree: def __init__(self): self.NIL_LEAF = RBNode(val=None, color=0) self.r...
import pytest from solution import RBNode, RBTree, find_inorder_successor def build_test_tree(): tree = RBTree() nodes = { 11: RBNode(11, 1), 2: RBNode(2, 1), 14: RBNode(14, 1), 1: RBNode(1, 1), 7: RBNode(7, 1), 15: RBNode(15, 1), 5: RBNode(5, 1), ...
[]
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class RBNode:\n def __init__(self, key, color, left=None, right=None, parent=None):\n self.key = key\n self.color = color # 1 for Red, 0 for...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00046975", "row_id": 46975, "seed_ids": "[314]" }
0.577675
Data_Structure_46975
I
[ "find_inorder_successor", "find_minimum" ]
2
[ [ "find_inorder_successor", "find_minimum" ] ]
1
[]
false
[ "RBNode", "RBTree" ]
true
pytest
true
[]
true
bfd33f57515fc05d99cd8c61bfa6a81e195679cd
0321fb4f7046336f40a0445a5f7433617bdf6733
v1.0
instruct
Data_Structure
Data_Structure_47089_I
You are given four matrix transformation functions: `rotate_clockwise`, `rotate_counterclockwise`, `top_left_invert`, and `bottom_left_invert`. These functions perform various 2D matrix manipulations either by rotating or inverting the matrix. Your task is to write a function: ```python def matrix_transform(matrix, o...
def rotate_clockwise(matrix): n = len(matrix) new_matrix = [[0]*n for _ in range(n)] for i in range(n): for j in range(n): new_matrix[j][n-1-i] = matrix[i][j] return new_matrix def rotate_counterclockwise(matrix): n = len(matrix) new_matrix = [[0]*n for _ in range(n)] fo...
from solution import matrix_transform def test_rotate_clockwise(): matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ] expected = [ [7, 4, 1], [8, 5, 2], [9, 6, 3], ] assert matrix_transform(matrix, "rotate_clockwise") == expected def test_rotate_countercl...
[ { "docstring": null, "function_declaration": "def rotate_clockwise(matrix):", "function_name": "rotate_clockwise", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def rotate_counterclockwise(matrix):", "function_name": "rotate_counterclockwise", "par...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def matrix_transform(matrix, operation):\n def rotate_clockwise(mat):\n return [list(reversed(col)) for col in zip(*mat)]\n\n def rotate_counterc...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047089", "row_id": 47089, "seed_ids": "[337]" }
0.552297
Data_Structure_47089
I
[ "rotate_clockwise", "rotate_counterclockwise", "top_left_invert", "bottom_left_invert", "matrix_transform" ]
5
[ [ "matrix_transform", "bottom_left_invert" ], [ "matrix_transform", "rotate_clockwise" ], [ "matrix_transform", "rotate_counterclockwise" ], [ "matrix_transform", "top_left_invert" ] ]
4
[]
false
[]
false
pytest
true
[]
true
4e8c6173792591d14c7430fbf73e0c0d89a31a02
11c57d845a6f6189fab67aeeb0ed0da035deafeb
v1.0
instruct
Data_Structure
Data_Structure_47097_I
### Matrix Transformation Challenge You are given a square matrix (n x n) containing integers. Your task is to implement three distinct transformations on this matrix and one composite function as follows: 1. **Rotate 90 Degrees Clockwise**: Rotate the matrix elements by 90 degrees in a clockwise direction. 2. **Rota...
from typing import List def rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]: """ Rotate the matrix 90 degrees clockwise. """ n = len(matrix) return [[matrix[n - j - 1][i] for j in range(n)] for i in range(n)] def rotate_counterclockwise(matrix: List[List[int]]) -> List[List[int]]: ...
from solution import rotate_clockwise, rotate_counterclockwise, invert_top_bottom, composite_transformations def test_rotate_clockwise(): matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] result = rotate_clockwise(matrix) expected = [ [7, 4, 1], [8, 5, 2], [9,...
[ { "docstring": "Rotate the matrix 90 degrees clockwise.", "function_declaration": "def rotate_clockwise(matrix):", "function_name": "rotate_clockwise", "parameter_list": "(matrix)" }, { "docstring": "Rotate the matrix 90 degrees counterclockwise.", "function_declaration": "def rotate_cou...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Rotate the matrix 90 degrees clockwise.\n \"\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047097", "row_id": 47097, "seed_ids": "[337]" }
0.586726
Data_Structure_47097
I
[ "rotate_clockwise", "rotate_counterclockwise", "invert_top_bottom", "composite_transformations" ]
4
[ [ "composite_transformations", "invert_top_bottom" ], [ "composite_transformations", "rotate_clockwise" ], [ "composite_transformations", "rotate_counterclockwise" ] ]
3
[]
false
[]
false
pytest
true
[]
true
6a642bcd0a5c0abe0c40cd11b16d8a1eb9bf2947
2ac572a28ed6e12778420282f49af794064e5a9d
v1.0
instruct
Data_Structure
Data_Structure_47099_I
### Insertion Sort with Binary Search #### Scenario: You have been tasked to implement a function for sorting an array of integers. To do this efficiently, you will use the insertion sort algorithm but enhance it using binary search to find the correct insertion position. Using binary search will reduce the number of...
def search_insert(array, val): """ Params: array (List[int]): A sorted list of integers val (int): The target value to find the insertion index for Returns: int: Index at which the val should be inserted to maintain sorted order """ left, right = 0, len(array) - 1 w...
from solution import search_insert, insertion_sort def test_search_insert(): assert search_insert([1, 3, 5, 6], 5) == 2 assert search_insert([1, 3, 5, 6], 2) == 1 assert search_insert([1, 3, 5, 6], 0) == 0 assert search_insert([1, 3, 5, 6], 7) == 4 assert search_insert([1, 3, 5, 5, 6, 6], 5) == 2 ...
[ { "docstring": "Params:\n array (List[int]): A sorted list of integers\n val (int): The target value to find the insertion index for\n\nReturns:\n int: Index at which the val should be inserted to maintain sorted order", "function_declaration": "def search_insert(array, val):", "function_name":...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def search_insert(array, val):\n \"\"\"\n Params:\n array (List[int]): A sorted list of integers\n val (int): The target value to find the...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047099", "row_id": 47099, "seed_ids": "[199]" }
0.575343
Data_Structure_47099
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fb837f854ee5b259e3cba204b2f3678f82f48fed
95ad760f6bcd95a84e8061923c9d596d98f7a42e
v1.0
instruct
Data_Structure
Data_Structure_47106_I
**Prime Number Batch Processor** ### Problem Statement You are required to create a function `batch_prime_check` that processes a batch of numbers and returns a list indicating whether each number in the batch is prime or not. The function should leverage the given algorithm for checking prime numbers and should handl...
import math from typing import List def is_prime(n: int) -> bool: if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return Tr...
from solution import batch_prime_check def test_batch_prime_check(): assert batch_prime_check([2, 3, 4, 5, -1, 0, 17, 18]) == [True, True, False, True, False, False, True, False] assert batch_prime_check([37, 41, 43, 47, -2, 1, 53, 60]) == [True, True, True, True, False, False, True, False] assert batch_pr...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def batch_prime_check(nums):", "function_name": "batch_prime_check", "parameter_list": "(nums)" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom typing import List\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047106", "row_id": 47106, "seed_ids": "[143]" }
0.654938
Data_Structure_47106
I
[ "is_prime", "batch_prime_check" ]
2
[ [ "batch_prime_check", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
215662cdcd04e5d2cc331677057c90b6281ba026
dd0d84ccbd6a4a8676af9f100cb1bfaa4be7254e
v1.0
instruct
Data_Structure
Data_Structure_47124_I
**Problem Statement**: Given an array of strings, write a function to find the longest common prefix string amongst them. If there is no common prefix, return an empty string. You are provided with three existing solutions using different algorithms: Horizontal Scanning, Vertical Scanning, and Divide and Conquer. You...
from typing import List def is_common_prefix(strs: List[str], length: int) -> bool: """ Check if a specific length of prefix is common among all strings. """ prefix = strs[0][:length] return all(s.startswith(prefix) for s in strs) def longest_common_prefix_binary_search(strs: List[str]) -> str: ...
from solution import ( longest_common_prefix_binary_search, longest_common_prefix_v1, longest_common_prefix_v2, longest_common_prefix_v3 ) import time def test_longest_common_prefix(): test_cases = [ (["flower", "flow", "flight"], "fl"), (["dog", "racecar", "car"], ""), ([],...
[ { "docstring": "Check if a specific length of prefix is common among all strings.", "function_declaration": "def is_common_prefix(strs, length):", "function_name": "is_common_prefix", "parameter_list": "(strs, length)" }, { "docstring": "Finds the longest common prefix string amongst an arra...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef longest_common_prefix_binary_search(strs: List[str]) -> str:\n if not strs:\n return \"\"\n \n # Find the minim...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00047124", "row_id": 47124, "seed_ids": "[67]" }
0.763006
Data_Structure_47124
I
[ "is_common_prefix", "longest_common_prefix_binary_search", "longest_common_prefix_v1", "longest_common_prefix_v2", "longest_common_prefix_v3" ]
5
[ [ "longest_common_prefix_binary_search", "is_common_prefix" ] ]
1
[]
false
[]
false
pytest
true
[]
true
de84907bc31d1d1ceb1b3d3b53533d6eee7de706
b74a4d4fe29c747c0a2c2f4d2e5c22d2d92ee9e2
v1.0
instruct
Data_Structure
Data_Structure_47160_I
Scalable Bitonic Sort Implementation #### Context You are working as a software engineer tasked with optimizing the performance of a large-scale numeric dataset analysis. For this purpose, you decide to implement the Bitonic Sort algorithm due to its efficiency in parallel processing environments. Your task is to writ...
from typing import List def bitonic_merge(arr: List[int], low: int, count: int, direction: bool): if count > 1: k = count // 2 for i in range(low, low + k): if (direction and arr[i] > arr[i + k]) or (not direction and arr[i] < arr[i + k]): arr[i], arr[i + k] = arr[i + k]...
import pytest from solution import scalable_bitonic_sort def test_scalable_bitonic_sort_ascending_simple(): assert scalable_bitonic_sort([3, 7, 4, 8, 6, 2, 1, 5], reverse=False) == [1, 2, 3, 4, 5, 6, 7, 8] def test_scalable_bitonic_sort_descending_simple(): assert scalable_bitonic_sort([12, 4, 78, 26, 9, 32, ...
[ { "docstring": null, "function_declaration": "def bitonic_merge(arr, low, count, direction):", "function_name": "bitonic_merge", "parameter_list": "(arr, low, count, direction)" }, { "docstring": null, "function_declaration": "def bitonic_sort(arr, low, count, direction):", "function...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef bitonic_compare_and_swap(arr: List[int], i: int, j: int, direction: bool):\n \"\"\"\n Compare and swap the elements at in...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047160", "row_id": 47160, "seed_ids": "[17]" }
0.676493
Data_Structure_47160
I
[ "bitonic_merge", "bitonic_sort", "scalable_bitonic_sort" ]
3
[ [ "bitonic_sort", "bitonic_merge" ], [ "scalable_bitonic_sort", "bitonic_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
855aab17c3bc78692cc017f5f8518a19c63df93b
e760a058cd78f24336672d9374b4694b232bdc81
v1.0
instruct
Data_Structure
Data_Structure_47227_I
### Coding Assessment: Radix Sort Implementation #### Objective: Implement the Radix Sort algorithm to sort an array of non-negative integers. #### Instructions: You are required to implement a function called `radix_sort` that sorts an array of non-negative integers in ascending order. Do not use any in-built sortin...
from typing import List def counting_sort_for_radix(arr, exp): n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = (arr[i] // exp) % 10 count[index] += 1 for i in range(1, 10): count[i] += count[i-1] i = n - 1 while i >= 0: ...
from solution import radix_sort def test_radix_sort_typical_case(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_empty_list(): assert radix_sort([]) == [] def test_radix_sort_single_element(): assert radix_sort([5]) == [5] def test_radix_s...
[ { "docstring": null, "function_declaration": "def counting_sort_for_radix(arr, exp):", "function_name": "counting_sort_for_radix", "parameter_list": "(arr, exp)" }, { "docstring": null, "function_declaration": "def radix_sort(arr, simulation=False):", "function_name": "radix_sort", ...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef counting_sort_for_radix(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \n for i in range(n):\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00047227", "row_id": 47227, "seed_ids": "[15]" }
0.592647
Data_Structure_47227
I
[ "counting_sort_for_radix", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort_for_radix" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0f9f4afd5bf98168286d547c646d530be82dab6d
fc1ecdd08d00b5fdc6e4cbf214176cfa024963cd
v1.0
instruct
Data_Structure
Data_Structure_47240_I
You are given a network of pipes represented as a directed graph. Each pipe has a certain maximum capacity for fluid flow. The objective is to determine the maximum amount of fluid that can flow from a designated source node to a designated sink node using one of the maximum flow algorithms. Implement a function `max_...
from typing import List from collections import deque def dinic_bfs(capacity, flow, level, source, sink): """ BFS function for Dinic's algorithm. Sets level array using a level graph concept. """ queue = deque([source]) level[source] = 0 while queue: u = queue.popleft() for ...
import pytest from solution import max_flow def test_max_flow_small_graph(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert max_flo...
[ { "docstring": "BFS function for Dinic's algorithm.\nSets level array using a level graph concept.", "function_declaration": "def dinic_bfs(capacity, flow, level, source, sink):", "function_name": "dinic_bfs", "parameter_list": "(capacity, flow, level, source, sink)" }, { "docstring": "DFS f...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef dinic_bfs(capacity: List[List[int]], flow: List[List[int]], level: List[int], source: int, sink: int) -> bool:\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047240", "row_id": 47240, "seed_ids": "[240]" }
0.601841
Data_Structure_47240
I
[ "dinic_bfs", "dinic_dfs", "max_flow" ]
3
[ [ "max_flow", "dinic_bfs" ], [ "max_flow", "dinic_dfs" ] ]
2
[]
false
[]
false
pytest
true
[]
true
62c08c4e3ba686e9d781416b6c6f0f915b4a96f5
74b461bb24eb7446bbe6154d6bdbe5850b043111
v1.0
instruct
Data_Structure
Data_Structure_47330_I
You are provided with two variants of the Heap Sort algorithm: `max_heap_sort` and `min_heap_sort`. Your task is to implement a hybrid heap sort method called `hybrid_heap_sort` that dynamically chooses between max heap sort and min heap sort based on the input array. ### Objective Write a function `hybrid_heap_sort(a...
def max_heapify(arr, n, i): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: largest = right if largest != i: arr[i], arr[largest] = arr[largest], arr[i] max_heap...
from solution import hybrid_heap_sort def test_hybrid_heap_sort_already_sorted(): assert hybrid_heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_hybrid_heap_sort_reverse_sorted(): assert hybrid_heap_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_hybrid_heap_sort_random_order(): assert hybrid_hea...
[ { "docstring": null, "function_declaration": "def max_heapify(arr, n, i):", "function_name": "max_heapify", "parameter_list": "(arr, n, i)" }, { "docstring": null, "function_declaration": "def min_heapify(arr, n, i):", "function_name": "min_heapify", "parameter_list": "(arr, n, i...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def max_heapify(arr, n, i, simulation):\n largest = i\n l = 2 * i + 1\n r = 2 * i + 2\n\n if l < n and arr[i] < arr[l]:\n largest = l\n\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00047330", "row_id": 47330, "seed_ids": "[8]" }
0.660153
Data_Structure_47330
I
[ "max_heapify", "min_heapify", "max_heap_sort", "min_heap_sort", "hybrid_heap_sort" ]
5
[ [ "hybrid_heap_sort", "max_heap_sort" ], [ "hybrid_heap_sort", "min_heap_sort" ], [ "max_heap_sort", "max_heapify" ], [ "min_heap_sort", "min_heapify" ] ]
4
[]
false
[]
false
pytest
true
[]
true
2e2e2b65eda7642229c1745063477d68eb14006d
1df97a6fc34286651b286eccc516399ec98fd3eb