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_40915_I
You are given an unsorted array consisting of integers. Your goal is to sort this array in ascending order using the **Pancake Sort** algorithm. This sorting algorithm sorts elements by repeatedly using a flip operation — flipping the order of elements in the array from position 0 to a given index. ### Function Signat...
from typing import List def flip(arr: List[int], k: int) -> None: """ Function to reverse the array from start to k index. """ arr[:k+1] = arr[:k+1][::-1] def find_max_index(arr: List[int], n: int) -> int: """ Function to find the index of the maximum element in arr[:n+1] """ max_index...
from solution import pancake_sort def test_pancake_sort_basic(): assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4] def test_pancake_sort_with_duplicates(): assert pancake_sort([3, 1, 4, 2, 2, 4, 1, 1, 3]) == [1, 1, 1, 2, 2, 3, 3, 4, 4] def test_pancake_sort_sorted(): assert pancake_sort([1, 2, 3]) ==...
[ { "docstring": "Function to reverse the array from start to k index.", "function_declaration": "def flip(arr, k):", "function_name": "flip", "parameter_list": "(arr, k)" }, { "docstring": "Function to find the index of the maximum element in arr[:n+1]", "function_declaration": "def find_...
[ 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 pancake_sort(arr):\n def flip(sub_arr, k):\n \"\"\"\n Flip the sublist from 0 to k.\n \"\"\"\n sub_arr[:k+1] = sub_arr[:k+1...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00040915", "row_id": 40915, "seed_ids": "[9]" }
0.725526
Data_Structure_40915
I
[ "flip", "find_max_index", "pancake_sort" ]
3
[ [ "pancake_sort", "find_max_index" ], [ "pancake_sort", "flip" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ec02c2966be29023230b1e273254f2fe16d0e750
4fbf271d206c73b8f908857b9c77f8ad2371e6bf
v1.0
instruct
Data_Structure
Data_Structure_40953_I
### Problem: Modified Dijkstra's Algorithm for All-Pairs Shortest Path Given the implementation of Dijkstra's Single-Source Shortest Path Algorithm, your task is to modify it to find the shortest paths between all pairs of vertices in a weighted, directed graph. ### Input 1. **vertex_count**: An integer representing ...
from typing import List, Tuple import heapq def dijkstra(vertex_count: int, graph: List[List[Tuple[int, int]]], start: int) -> List[float]: distances = [float('inf')] * vertex_count distances[start] = 0 priority_queue = [(0, start)] while priority_queue: current_distance, current_vertex = ...
from solution import all_pairs_shortest_path def test_all_pairs_shortest_path_example(): vertex_count = 4 edges = [ (0, 1, 3), (0, 3, 7), (1, 2, 1), (2, 3, 2), (3, 2, 3) ] expected = [ [0, 3, 4, 6], [float('inf'), 0, 1, 3], [float('inf...
[ { "docstring": null, "function_declaration": "def dijkstra(vertex_count, graph, start):", "function_name": "dijkstra", "parameter_list": "(vertex_count, graph, start)" }, { "docstring": null, "function_declaration": "def all_pairs_shortest_path(vertex_count, edges):", "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": "import heapq\nfrom typing import List, Tuple\n\ndef dijkstra(vertex_count: int, graph: List[List[Tuple[int, int]]], start: int) -> List[float]:\n distances...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00040953", "row_id": 40953, "seed_ids": "[238]" }
0.703345
Data_Structure_40953
I
[ "dijkstra", "all_pairs_shortest_path" ]
2
[ [ "all_pairs_shortest_path", "dijkstra" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6693e31d8504940a101f9ab91ec6203d4898a84d
4b873dcee4e0540791a43b7c719b9d62c4466335
v1.0
instruct
Data_Structure
Data_Structure_40978_I
### Problem Description You have been tasked to assess students' understanding of sorting algorithms by having them implement a variation of the Bogo Sort algorithm called **Constrained Bogo Sort**. The Constrained Bogo Sort will try to sort the list in a given number of maximum iterations. If the list is not sorted...
import random from typing import List, Union def is_sorted(arr: List[int]) -> bool: """Helper function to check if the list is sorted.""" return all(arr[i] <= arr[i+1] for i in range(len(arr)-1)) def constrained_bogo_sort(arr: List[int], max_iterations: int) -> Union[List[int], str]: """ Attempts to s...
from solution import constrained_bogo_sort def test_sorted_array(): assert constrained_bogo_sort([1, 2, 3, 4, 5], 1) == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): result = constrained_bogo_sort([5, 4, 3, 2, 1], 1000) assert result == [1, 2, 3, 4, 5] or result == "Sort failed" def test_same_elements...
[ { "docstring": "Helper function to check if the list is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Attempts to sort the list arr using Constrained Bogo Sort within max_iterations.\nIf unsuccessful, retur...
[ 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": "import random\nfrom typing import List, Union\n\ndef constrained_bogo_sort(arr: List[int], max_iterations: int) -> Union[List[int], str]:\n def is_sorted(a...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00040978", "row_id": 40978, "seed_ids": "[16]" }
0.610215
Data_Structure_40978
I
[ "is_sorted", "constrained_bogo_sort" ]
2
[ [ "constrained_bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
09cb34b740d5db4f05a19367a64ce33bc6043aeb
98951a4c5edb8c3a0becb225fbecfa20555ff70a
v1.0
instruct
Data_Structure
Data_Structure_40989_I
### Quick Sort with Pivot Optimization You have been provided a quick sort algorithm. The task is to improve this algorithm by implementing a median-of-three pivot selection strategy to enhance the average performance further. #### Requirements: 1. Implement the function `median_of_three(arr, first, last)` to: * S...
def median_of_three(arr, first, last): """ Reorders the first, middle, and last elements of the array to choose the median as the pivot. """ mid = (first + last) // 2 if arr[first] > arr[mid]: arr[first], arr[mid] = arr[mid], arr[first] if arr[first] > arr[last]: arr[first], arr[...
from solution import quick_sort def test_quick_sort_with_duplicates(): assert quick_sort([3,1,2,1,4]) == [1,1,2,3,4] def test_quick_sort_already_sorted(): assert quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_quick_sort_reversed(): assert quick_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_...
[ { "docstring": "Reorders the first, middle, and last elements of the array to choose the median as the pivot.", "function_declaration": "def median_of_three(arr, first, last):", "function_name": "median_of_three", "parameter_list": "(arr, first, last)" }, { "docstring": null, "function_d...
[ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def median_of_three(arr, first, last):\n \"\"\"\n Selects the median of the first, middle, and last elements of the list.\n Reorders so the pivot end...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00040989", "row_id": 40989, "seed_ids": "[25]" }
0.580873
Data_Structure_40989
I
[ "median_of_three", "partition", "quick_sort_recursive", "quick_sort" ]
4
[ [ "partition", "median_of_three" ], [ "quick_sort", "quick_sort_recursive" ], [ "quick_sort_recursive", "partition" ] ]
3
[]
false
[]
false
pytest
true
[]
true
c694a52cc44d71053279bcf1d6354968190ea023
a05acf7a838421b738a3db98925d6e709041ebb6
v1.0
instruct
Data_Structure
Data_Structure_40997_I
Your task is to implement two functions, `extended_gcd(a, b)` and `modular_inverse(a, m)`. #### Function 1: extended_gcd(a, b) This function calculates the greatest common divisor (GCD) of two integers a and b, and also finds two coefficients s and t such that the equation a * s + b * t = GCD(a, b) is satisfied. - **...
def extended_gcd(a, b): """ Returns the greatest common divisor (GCD) of integers a and b, as well as two coefficients s and t such that a * s + b * t = GCD(a, b). """ if b == 0: return (1, 0, a) else: s, t, gcd = extended_gcd(b, a % b) return (t, s - (a // b) * t, gcd) ...
from solution import extended_gcd, modular_inverse def test_extended_gcd(): assert extended_gcd(30, 20) == (1, -1, 10) assert extended_gcd(54, 24) == (1, -2, 6) assert extended_gcd(81, 57) == (-7, 10, 3) assert extended_gcd(101, 10) == (1, -10, 1) def test_modular_inverse(): assert modular_inverse...
[ { "docstring": "Returns the greatest common divisor (GCD) of integers a and b,\nas well as two coefficients s and t such that a * s + b * t = GCD(a, b).", "function_declaration": "def extended_gcd(a, b):", "function_name": "extended_gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns...
[ 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 extended_gcd(a, b):\n \"\"\"\n Computes the greatest common divisor of a and b, and the coefficients s and t\n such that a * s + b * t = GCD(a, b...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00040997", "row_id": 40997, "seed_ids": "[161]" }
0.664902
Data_Structure_40997
I
[ "extended_gcd", "modular_inverse" ]
2
[ [ "modular_inverse", "extended_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
865d148ebeb59d01b5a0141603e8ebe91c46fe6c
c079d72ade1e594c9fb818004d5968419a356c2c
v1.0
instruct
Data_Structure
Data_Structure_41085_I
### Objective You are required to implement the Insertion Sort algorithm using a helper function that efficiently finds the correct insertion position using binary search. ### Task Write a function `insertion_sort(array)` that sorts an array of integers in ascending order using the Insertion Sort algorithm. Utilize th...
def search_insert(array, val): low = 0 high = len(array) - 1 while low <= high: mid = low + (high - low) // 2 if val > array[mid]: low = mid + 1 else: high = mid - 1 return low def insertion_sort(array): for i in range(1, len(array)): key = ar...
def test_insertion_sort_empty(): assert insertion_sort([]) == [] def test_insertion_sort_single_element(): assert insertion_sort([5]) == [5] def test_insertion_sort_sorted_order(): assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_insertion_sort_reverse_order(): assert insertion_sort...
[ { "docstring": null, "function_declaration": "def search_insert(array, val):", "function_name": "search_insert", "parameter_list": "(array, val)" }, { "docstring": null, "function_declaration": "def insertion_sort(array):", "function_name": "insertion_sort", "parameter_list": "(a...
[ 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 low = 0\n high = len(array) - 1\n while low <= high:\n mid = low + (high - low) // 2\n if val > array[...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041085", "row_id": 41085, "seed_ids": "[199]" }
0.565957
Data_Structure_41085
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
false
[]
true
7225032a9e78f1251a5ffe3a95c3243d85626c56
9eb483565e14b366f44a4a76228e23fd566fd557
v1.0
instruct
Data_Structure
Data_Structure_41101_I
Given two arrays representing the preorder and postorder traversal of a full binary tree, your task is to construct the binary tree and return its inorder traversal. **Input:** - `pre` (list): A list of integers representing the preorder traversal of the full binary tree. - `post` (list): A list of integers representi...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def buildTree(preorder, postorder): """ Constructs a full binary tree given its preorder and postorder traversals. :param preorder: List[int] :param postorder...
import pytest from solution import getInorderFromPrePost def test_example_case(): pre = [1, 2, 4, 8, 9, 5, 3, 6, 7] post = [8, 9, 4, 5, 2, 6, 7, 3, 1] expected = [8, 4, 9, 2, 5, 1, 6, 3, 7] assert getInorderFromPrePost(pre, post) == expected def test_single_node_tree(): pre = [1] post = [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": "# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041101", "row_id": 41101, "seed_ids": "[300]" }
0.602618
Data_Structure_41101
I
[ "buildTree", "inorderTraversal", "getInorderFromPrePost" ]
3
[ [ "getInorderFromPrePost", "buildTree" ], [ "getInorderFromPrePost", "inorderTraversal" ] ]
2
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
4d8b20604be7e6cbe79d1c4cd8e2d0b851edddb2
5d2507276128088ed1070241d54d53159f68d1ca
v1.0
instruct
Data_Structure
Data_Structure_41181_I
### Radix Sort Implementation and Analysis #### Scenario You are tasked with sorting a list of non-negative integers efficiently for a large-scale data processing system. Given the constraints on execution time, you decide to implement the Radix Sort algorithm, which can offer better performance than traditional compa...
def counting_sort(arr, exp, simulation): 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 count[i] contains actual position of this digi...
from solution import radix_sort def test_radix_sort_example_1(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_example_2(): assert radix_sort([78, 56, 89, 234, 12, 789]) == [12, 56, 78, 89, 234, 789] def test_radix_sort_empty_list(): assert ...
[ { "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, 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(arr, exp, simulation):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n for i in range(n):\n index = (arr[i] // e...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00041181", "row_id": 41181, "seed_ids": "[15]" }
0.653996
Data_Structure_41181
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e92a2a84b873f69b50b665605e39cc28b0c439a1
0eb744d9f30f839cf3e5c8d23d52de04db26ec1e
v1.0
instruct
Data_Structure
Data_Structure_41228_I
You are given a function that generates a hailstone sequence starting from a given number `n`. Your task is to modify the function to handle large inputs more efficiently by leveraging memoization. You also need to implement a secondary function that, given an integer `m`, finds the starting number `n` in the range `1`...
def hailstone(n, memo={}): """ Return the 'hailstone sequence' from n to 1 with memoization to improve performance. n: The starting point of the hailstone sequence memo: A dictionary to store previously computed sequences """ if n in memo: return memo[n] original_n = n sequence...
def test_hailstone_sequence(): assert hailstone(10) == [10, 5, 16, 8, 4, 2, 1] assert hailstone(1) == [1] assert hailstone(7) == [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] def test_longest_hailstone_sequence(): assert longest_hailstone_sequence(10) == (9, 20) assert longest_hail...
[ { "docstring": "Return the 'hailstone sequence' from n to 1 with memoization to improve performance.\nn: The starting point of the hailstone sequence\nmemo: A dictionary to store previously computed sequences", "function_declaration": "def hailstone(n, memo={}):", "function_name": "hailstone", "para...
[ 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 hailstone(n, memo={}):\n \"\"\"\n Return the 'hailstone sequence' from n to 1 with memoization to improve performance.\n n: The starting point of...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00041228", "row_id": 41228, "seed_ids": "[167]" }
0.562921
Data_Structure_41228
I
[ "hailstone", "longest_hailstone_sequence" ]
2
[ [ "longest_hailstone_sequence", "hailstone" ] ]
1
[]
false
[]
false
pytest
false
[]
true
1b1f7e419397cd6f198eae8fc063f7a406381388
29d688dba40b4c5bc15a866c850fb5d95f06d1d7
v1.0
instruct
Data_Structure
Data_Structure_41237_I
#### Reversal Algorithm Function Implementation You are given four different implementations of a string reversal algorithm. Each implementation represents a unique approach to the problem. Your objective is to write a new function that combines these methods and performs additional specific validation. ### Function ...
def iterative(s: str) -> str: """ Reverses a string using an iterative approach. """ reversed_str = '' for char in s: reversed_str = char + reversed_str return reversed_str def ultra_pythonic(s: str) -> str: """ Reverses a string using Python slicing. """ return s[::-1] ...
import pytest from solution import validated_reverse def test_validated_reverse_empty(): assert validated_reverse("") == "" def test_validated_reverse_single_char(): assert validated_reverse("a") == "a" def test_validated_reverse_short_string(): assert validated_reverse("hello") == "hello" def test_vali...
[ { "docstring": "Reverses a string using an iterative approach.", "function_declaration": "def iterative(s):", "function_name": "iterative", "parameter_list": "(s)" }, { "docstring": "Reverses a string using Python slicing.", "function_declaration": "def ultra_pythonic(s):", "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": "def validated_reverse(s: str) -> str:\n \"\"\"\n Validate and reverse a string using a combination of iterative and ultra_pythonic methods.\n \n :...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041237", "row_id": 41237, "seed_ids": "[61]" }
0.668993
Data_Structure_41237
I
[ "iterative", "ultra_pythonic", "validated_reverse" ]
3
[ [ "validated_reverse", "iterative" ], [ "validated_reverse", "ultra_pythonic" ] ]
2
[]
false
[]
false
pytest
true
[]
true
61dfe17658b6a222cfc34893c735d17205ade8df
9f2a239fb51179d176ba0f2b8b27d341d4619ed4
v1.0
instruct
Data_Structure
Data_Structure_41251_I
You are given a directed graph represented by an adjacency matrix where each entry `[i][j]` indicates the capacity of the edge from node `i` to node `j`. Your task is to compute the maximum flow from the source node (node 0) to the sink node (the last node) using the Edmonds-Karp algorithm, which is an implementation o...
from collections import deque def bfs(capacity, source, sink, parent): visited = [False] * len(capacity) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() for ind, val in enumerate(capacity[u]): if visited[ind] == False and val > 0: ...
from solution import maximum_flow_bfs def test_maximum_flow_example(): 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_maxi...
[ { "docstring": null, "function_declaration": "def bfs(capacity, source, sink, parent):", "function_name": "bfs", "parameter_list": "(capacity, source, sink, parent)" }, { "docstring": null, "function_declaration": "def maximum_flow_bfs(graph):", "function_name": "maximum_flow_bfs", ...
[ 0, 0, 0, 1, 0, 1, 0, 0, 1, 0 ]
3
hard
0.3
{ "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, source, sink, parent):\n \"\"\"\n Perform BFS to find an augmenting path.\n \"\"\"\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00041251", "row_id": 41251, "seed_ids": "[229]" }
0.613812
Data_Structure_41251
I
[ "bfs", "maximum_flow_bfs" ]
2
[ [ "maximum_flow_bfs", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b3b831a87f66c54c93a714c3208ee1bbc6b9523b
60203454646e8c0c33d42e8db92031bafb7c649d
v1.0
instruct
Data_Structure
Data_Structure_41299_I
### Bitonic Sort Implementation You are tasked with implementing the bitonic sort algorithm, which is useful for sorting arrays in parallel processing environments but here we are focused on a non-parallel implementation. Given an array of integers and a boolean indicating the desired order, implement the bitonic sort...
from typing import List def bitonic_merge(arr: List[int], low: int, cnt: int, direction: bool) -> None: if cnt > 1: k = cnt // 2 for i in range(low, low + k): if (direction == (arr[i] > arr[i + k])): arr[i], arr[i + k] = arr[i + k], arr[i] bitonic_merge(arr, low,...
from solution import bitonic_sort def test_bitonic_sort_ascending(): arr = [3, 7, 2, 5, 6, 1, 4, 8] expected = [1, 2, 3, 4, 5, 6, 7, 8] assert bitonic_sort(arr, reverse=False) == expected def test_bitonic_sort_descending(): arr = [10, 30, 20, 50, 60, 40, 90, 70] expected = [90, 70, 60, 50, 40, 30,...
[ { "docstring": null, "function_declaration": "def bitonic_merge(arr, low, cnt, direction):", "function_name": "bitonic_merge", "parameter_list": "(arr, low, cnt, direction)" }, { "docstring": null, "function_declaration": "def bitonic_sort_recursive(arr, low, cnt, direction):", "func...
[ 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 compare_and_swap(arr: List[int], i: int, j: int, direction: bool):\n if (direction and arr[i] > arr[j]) or (not direction an...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041299", "row_id": 41299, "seed_ids": "[17]" }
0.658288
Data_Structure_41299
I
[ "bitonic_merge", "bitonic_sort_recursive", "bitonic_sort" ]
3
[ [ "bitonic_sort", "bitonic_sort_recursive" ], [ "bitonic_sort_recursive", "bitonic_merge" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6093805adae92926bc4bc46fe02175f4794ab830
f8d70c24f8c08a478bf238f01d49765fdcfdd704
v1.0
instruct
Data_Structure
Data_Structure_41345_I
### Question Statement Consider the RSA algorithm implementation provided. Your task is to extend this system by implementing a secure communication protocol using RSA encryption. You will design a function that takes two sets of RSA keys as input (one for the sender and one for the receiver) and encrypts and decrypts...
def encrypt_message(n, e, msg): """ Encrypt the message using the receiver's public key (n, e). """ encrypted_message = [pow(ord(char), e, n) for char in msg] return encrypted_message def decrypt_message(n, d, encrypted_msg): """ Decrypt the message using the receiver's private key (n, d). ...
from solution import secure_communication def test_secure_communication_basic(): sender_keys = (3233, 17, 413) # Example sender keys receiver_keys = (3233, 17, 413) # Example receiver keys, same for simplicity message = "HELLO123" assert secure_communication(sender_keys, receiver_keys, message) ...
[ { "docstring": "Encrypt the message using the receiver's public key (n, e).", "function_declaration": "def encrypt_message(n, e, msg):", "function_name": "encrypt_message", "parameter_list": "(n, e, msg)" }, { "docstring": "Decrypt the message using the receiver's private key (n, d).", "...
[ 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 string_to_int(message: str) -> int:\n \"\"\"Converts a string message to an integer representation.\"\"\"\n return int.from_bytes(message.encode(), ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041345", "row_id": 41345, "seed_ids": "[154]" }
0.596338
Data_Structure_41345
I
[ "encrypt_message", "decrypt_message", "secure_communication" ]
3
[ [ "secure_communication", "decrypt_message" ], [ "secure_communication", "encrypt_message" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d87b135ebd870cad91927a9e6ee767a1aebf9aa2
6a487946c22181920c8c7639c8c3ff0489543ea3
v1.0
instruct
Data_Structure
Data_Structure_41422_I
#### Bogo Sort Analysis and Implementation Bogo Sort is a highly inefficient sorting algorithm based on generating permutations of the input list until the list is sorted. Your task is to write a Bogo Sort function and deeply comprehend its inefficiencies and limitations. #### Task: Implement a Bogo Sort function and...
import random def is_sorted(arr): """ Helper function to check if the list is sorted in ascending order. """ return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) def bogo_sort(arr): """ Sorts an array using the highly inefficient BogoSort method. """ attempts = 0 max_attem...
from solution import bogo_sort def test_bogo_sort_simple_array(): assert bogo_sort([3, 1, 2]) == [1, 2, 3] def test_bogo_sort_with_duplicates(): assert bogo_sort([1, 2, 2, 3]) == [1, 2, 2, 3] def test_bogo_sort_already_sorted(): assert bogo_sort([1, 2, 3]) == [1, 2, 3] def test_bogo_sort_reverse_order()...
[ { "docstring": "Helper function to check if the list is sorted in ascending order.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts an array using the highly inefficient BogoSort method.", "function_declarat...
[ 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": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if the list is sorted in ascending order.\n \"\"\"\n return all(arr[i] <=...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041422", "row_id": 41422, "seed_ids": "[16]" }
0.580476
Data_Structure_41422
I
[ "is_sorted", "bogo_sort" ]
2
[ [ "bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
94087bfebe3339d0fc94000e51f7a8ccf18829b2
299f5f2a696a913b6aeda0c334b399d0e3e9a781
v1.0
instruct
Data_Structure
Data_Structure_41507_I
### Question: Implement Diffie-Hellman Key Exchange Algorithm Alice and Bob need to securely exchange keys over a network. You are to implement the Diffie-Hellman Key Exchange algorithm in Python. #### Task Write a function `diffie_hellman_key_exchange` which takes the following input: - `a`: an integer which is a pr...
import random def is_prime(n): """Check if a number is prime.""" 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...
from solution import diffie_hellman_key_exchange def test_valid_case(): assert diffie_hellman_key_exchange(5, 23, False) == True def test_invalid_a_not_primitive_root(): assert diffie_hellman_key_exchange(4, 23, False) == False def test_invalid_p_not_prime(): assert diffie_hellman_key_exchange(5, 22, Fal...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Compute (base ^ exponent) % modulus efficiently.", "function_declaration": "def power_mod(base, exponent, modulus):", "fun...
[ 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 is_prime(n):\n \"\"\" Check if a number is prime. \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00041507", "row_id": 41507, "seed_ids": "[146]" }
0.483693
Data_Structure_41507
I
[ "is_prime", "power_mod", "is_primitive_root", "diffie_hellman_key_exchange" ]
4
[ [ "diffie_hellman_key_exchange", "is_prime" ], [ "diffie_hellman_key_exchange", "is_primitive_root" ], [ "diffie_hellman_key_exchange", "power_mod" ], [ "is_primitive_root", "is_prime" ], [ "is_primitive_root", "power_mod" ] ]
5
[]
false
[]
false
pytest
true
[]
true
6e973cbc038b09a12febcc7dc55df102f1533b01
620e3b62003234509f69928e1f42c8bbbf9c55ac
v1.0
instruct
Data_Structure
Data_Structure_41540_I
### Question: Implement an Enhanced Merge Sort Merge Sort is a classic divide-and-conquer algorithm for sorting an array of numbers. We have provided a simplified version of the Merge Sort algorithm that sorts an array in ascending order. For this task, you are required to enhance and implement the Merge Sort algorith...
from typing import List, Callable def enhanced_merge_sort(arr: List[int], compare: Callable[[int, int], int]) -> List[int]: """ Iterative bottom-up merge sort that uses a custom comparator function. """ n = len(arr) width = 1 temp = arr[:] while width < n: for i in range(0, n, ...
from solution import enhanced_merge_sort def comparator_ascending(a, b): return a - b def comparator_descending(a, b): return b - a def test_enhanced_merge_sort_ascending(): arr = [4, 2, 7, 1, 9, 3] sorted_arr = enhanced_merge_sort(arr, comparator_ascending) assert sorted_arr == [1, 2, 3, 4, 7, 9...
[ { "docstring": "Iterative bottom-up merge sort that uses a custom comparator function.", "function_declaration": "def enhanced_merge_sort(arr, compare):", "function_name": "enhanced_merge_sort", "parameter_list": "(arr, compare)" }, { "docstring": null, "function_declaration": "def merge...
[ 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, Callable\n\ndef merge(arr: List[int], aux: List[int], left: int, mid: int, right: int, compare: Callable[[int, int], int]) -> None:\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041540", "row_id": 41540, "seed_ids": "[12]" }
0.662353
Data_Structure_41540
I
[ "enhanced_merge_sort", "merge" ]
2
[ [ "enhanced_merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0255231712df3acc4ad58d2894e1c433515d76f9
1b7ee6ba3b4ce266951ced39be981179eb528d1f
v1.0
instruct
Data_Structure
Data_Structure_41589_I
### Question You are required to implement a function for calculating the least common multiple (LCM) of two non-negative integers, taking into consideration proper error handling and integer output. #### Function Signature ```python def lcm(a: int, b: int) -> int: pass ``` #### Input - Two non-negative integers,...
def gcd(a, b): """ Calculate the Greatest Common Divisor of a and b. """ while b: a, b = b, a % b return a def lcm(a: int, b: int) -> int: """ Calculate the Least Common Multiple of two non-negative integers a and b. """ if a == 0 or b == 0: return 0 return abs(a...
from solution import lcm def test_lcm_with_zeros(): assert lcm(0, 5) == 0 assert lcm(7, 0) == 0 assert lcm(0, 0) == 0 def test_lcm_positive_numbers(): assert lcm(15, 20) == 60 assert lcm(3, 7) == 21 assert lcm(8, 12) == 24 def test_lcm_with_one(): assert lcm(1, 5) == 5 assert lcm(1, 1...
[ { "docstring": "Calculate the Greatest Common Divisor of a and b.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Calculate the Least Common Multiple of two non-negative integers a and b.", "function_declaration": "def lcm...
[ 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 lcm(a: int, b: int) -> int:\n \"\"\"\n Calculate the Least Common Multiple of two non-negative integers.\n \"\"\"\n if a < 0 or b < 0:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041589", "row_id": 41589, "seed_ids": "[166]" }
0.725667
Data_Structure_41589
I
[ "gcd", "lcm" ]
2
[ [ "lcm", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
460caece758f5b0875b2677e5236949013c5ba33
2614b7a309b222a963d27dd4cf63344d5247d53a
v1.0
instruct
Data_Structure
Data_Structure_41601_I
**Scenario**: You are developing a part of a cryptographic library that requires identifying primitive roots of a given number `n`. Understanding this requires knowledge of number theory, particularly Euler's Totient function and modular arithmetic. **Objective**: Implement a function that finds all primitive roots of...
from math import gcd def euler_totient(n): """Calculate Euler's Totient function φ(n).""" result = n p = 2 while p * p <= n: if n % p == 0: while n % p == 0: n //= p result -= result // p p += 1 if n > 1: result -= result // n retu...
from solution import find_primitive_roots def test_single_one(): assert find_primitive_roots(1) == [0] def test_prime_number(): assert find_primitive_roots(7) == [3, 5] def test_non_prime_coprime(): assert find_primitive_roots(9) == [2, 5] def test_no_primitive_roots(): assert find_primitive_roots(8...
[ { "docstring": "Calculate Euler's Totient function φ(n).", "function_declaration": "def euler_totient(n):", "function_name": "euler_totient", "parameter_list": "(n)" }, { "docstring": "Check if g is a primitive root of n.", "function_declaration": "def is_primitive_root(n, g):", "fun...
[ 0, 0, 0, 0, 0, 1, 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 gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef euler_totient(n):\n result = n\n p = 2\n while p * p <= n:\n if n %...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00041601", "row_id": 41601, "seed_ids": "[160]" }
0.513031
Data_Structure_41601
I
[ "euler_totient", "is_primitive_root", "find_primitive_roots" ]
3
[ [ "find_primitive_roots", "is_primitive_root" ], [ "is_primitive_root", "euler_totient" ] ]
2
[]
false
[]
false
pytest
true
[]
true
470b6ca504bc12780faad1972ef92cd3540c0190
185f0aca66b330059f87f6bc2c8469d54d85b27c
v1.0
instruct
Data_Structure
Data_Structure_41693_I
### Insertion Sort Enhancement with Binary Search Insertion Sort is a simple and intuitive algorithm suitable for small data sets. To perform insertion efficiently, we can utilize Binary Search to find the proper insertion spot instead of a linear search. **Prompt:** Implement the `insertion_sort` function that tak...
from typing import List def search_insert(array: List[int], val: int) -> int: low = 0 high = len(array) - 1 while low <= high: mid = low + (high - low) // 2 if val > array[mid]: low = mid + 1 else: high = mid - 1 return low def insertion_sort(array: List...
from solution import insertion_sort def test_insertion_sort(): assert insertion_sort([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12] assert insertion_sort([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13] assert insertion_sort([]) == [] assert insertion_sort([1]) == [1] assert insertion_sort([2, ...
[ { "docstring": null, "function_declaration": "def search_insert(array, val):", "function_name": "search_insert", "parameter_list": "(array, val)" }, { "docstring": null, "function_declaration": "def insertion_sort(array):", "function_name": "insertion_sort", "parameter_list": "(a...
[ 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(array: List[int], val: int) -> int:\n low = 0\n high = len(array) - 1\n while low <= high:\n mid ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041693", "row_id": 41693, "seed_ids": "[199]" }
0.564874
Data_Structure_41693
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1f5d4b9f9704a8d0642c5dc1bcebfbe4c6c5ac04
431ee613e602c03aba240e00936c7ea3eae416e2
v1.0
instruct
Data_Structure
Data_Structure_41708_I
### Context: Radix Sort is an efficient, stable sorting algorithm that can handle large sets of numbers by sorting based on individual digit places. It processes digits from either least significant to most significant place (LSD) or vice versa. ### Problem: Write a function `optimized_radix_sort(arr)` that sorts an i...
def optimized_radix_sort(arr): """ Returns the sorted version of the input list 'arr' using Radix Sort. """ if not arr: return arr max_num = max(arr) exp = 1 while max_num // exp > 0: counting_sort_by_digit(arr, exp) exp *= 10 return arr def counting_sort_by...
from solution import optimized_radix_sort def test_basic_example(): assert optimized_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_example_with_repeated_elements(): assert optimized_radix_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3]) == [1, 1, 2, 3, 3, 4, 5, 5, 6, 9] def ...
[ { "docstring": "Returns the sorted version of the input list 'arr' using Radix Sort.", "function_declaration": "def optimized_radix_sort(arr):", "function_name": "optimized_radix_sort", "parameter_list": "(arr)" }, { "docstring": "A helper function that performs counting sort on the array ba...
[ 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 optimized_radix_sort(arr):\n \"\"\"\n Sorts a list of non-negative integers using Radix Sort.\n \"\"\"\n if not arr:\n return []\n\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041708", "row_id": 41708, "seed_ids": "[15]" }
0.612691
Data_Structure_41708
I
[ "optimized_radix_sort", "counting_sort_by_digit" ]
2
[ [ "optimized_radix_sort", "counting_sort_by_digit" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ce21932da99b3569f9c66ab3c9a183b5c01fc9c7
adc2d5211d04bd3ec7fc3265a3ec9ec1751acd89
v1.0
instruct
Data_Structure
Data_Structure_41722_I
### Question: Optimal Strobogrammatic Number Generation and Counting #### Context A strobogrammatic number is one that looks the same when rotated 180 degrees. Your task is to implement two functions: one that generates all strobogrammatic numbers of a given length and another that counts how many such numbers fall wi...
from typing import List def generate_strobogrammatic(n: int) -> List[str]: # pairs of strobogrammatic numbers pairs = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'} def helper(n, length): if n == 0: return [""] if n == 1: return ["0", "1", "8"] middles = helper(n-2, le...
from solution import generate_strobogrammatic, count_strobogrammatic_in_range def test_generate_strobogrammatic_length_2(): result = generate_strobogrammatic(2) expected = sorted(["11", "69", "88", "96"]) assert sorted(result) == expected def test_generate_strobogrammatic_length_3(): result = generate...
[ { "docstring": null, "function_declaration": "def generate_strobogrammatic(n):", "function_name": "generate_strobogrammatic", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def count_strobogrammatic_in_range(low, high):", "function_name": "count_strobogramma...
[ 0, 0, 0, 0, 1, 0, 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 generate_strobogrammatic(n):\n \"\"\"\n Generates all strobogrammatic numbers of length n.\n \"\"\"\n if n == 0:\n return [\"\"]\n e...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00041722", "row_id": 41722, "seed_ids": "[140]" }
0.568531
Data_Structure_41722
I
[ "generate_strobogrammatic", "count_strobogrammatic_in_range" ]
2
[ [ "count_strobogrammatic_in_range", "generate_strobogrammatic" ] ]
1
[]
false
[]
false
pytest
true
[]
true
57121bf2a8f307b931cfa72d838d2976da167ca4
f26cdff53261a08b5e2c8fc0f47213fa5ab3da1e
v1.0
instruct
Data_Structure
Data_Structure_41749_I
You are tasked with sorting an array of integers using the merge sort algorithm. Your objective is to implement the `merge_sort` function and handle edge cases properly. ### Function Signature ```python def merge_sort(arr: List[int]) -> List[int]: ``` ### Input * `arr` (List[int]): A list of integers. ### Output * R...
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts an array 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(le...
from solution import merge_sort def test_merge_sort_empty_array(): assert 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_multiple_elements(): assert merge_sort([5, 2,...
[ { "docstring": "Sorts an array of integers using the merge sort algorithm.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merges two sorted arrays into one sorted array.", "function_declaration": "def merge(le...
[ 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 \"\"\"\n Sorts an array of integers using the merge sort algorithm.\n \n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041749", "row_id": 41749, "seed_ids": "[12]" }
0.705416
Data_Structure_41749
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2f0e1fe07f9610581d8858e83c36306906add3cf
2cb730c6cd3f2805765c309608a57119f9df94e7
v1.0
instruct
Data_Structure
Data_Structure_41789_I
#### Context Heap Sort is an efficient comparison-based sorting algorithm that can either use a Max-Heap or Min-Heap. This task will help you understand the operational mechanics of both types and their implementations. #### Task Implement a function `dual_heap_sort` which sorts an array using both max-heap and min-he...
import heapq from typing import List def max_heap_sort(arr: List[int]) -> List[int]: """ Perform a heap sort using a max heap. """ # heapify transforms list into a heap, in-place, in linear time. heap = [-x for x in arr] heapq.heapify(heap) sorted_list = [] while heap: max_...
from solution import dual_heap_sort def test_dual_heap_sort_with_mixed_numbers(): assert dual_heap_sort([3, 6, 1, 5, 2, 4]) == [1, 2, 3, 4, 5, 6] def test_dual_heap_sort_with_negative_numbers(): assert dual_heap_sort([-3, -6, -1, -5, -2, -4]) == [-6, -5, -4, -3, -2, -1] def test_dual_heap_sort_with_zeros_and...
[ { "docstring": "Perform a heap sort using a max heap.", "function_declaration": "def max_heap_sort(arr):", "function_name": "max_heap_sort", "parameter_list": "(arr)" }, { "docstring": "Perform a heap sort using a min heap.", "function_declaration": "def min_heap_sort(arr):", "functi...
[ 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 List\n\ndef max_heapify(arr: List[int], n: int, i: int):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n a...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00041789", "row_id": 41789, "seed_ids": "[8]" }
0.717133
Data_Structure_41789
I
[ "max_heap_sort", "min_heap_sort", "dual_heap_sort" ]
3
[ [ "dual_heap_sort", "max_heap_sort" ], [ "dual_heap_sort", "min_heap_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c686963c5aa59d6a1098fe9000676973cec6e976
1fa60112366ac1018dcf1808029345d4b79ada5b
v1.0
instruct
Data_Structure
Data_Structure_41792_I
### Secure Messaging Using Diffie-Hellman Key Exchange Alice and Bob want to securely share a secret key over an insecure communication channel, using the Diffie-Hellman Key Exchange algorithm. Given a large prime number \(p\) and its primitive root \(a\), write Python functions to simulate this secure key exchange an...
import random def prime_check(num: int) -> bool: if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return False i += 6 return True ...
def test_prime_check(): assert prime_check(23) == True assert prime_check(29) == True assert prime_check(4) == False assert prime_check(1) == False def test_find_primitive_root(): assert 5 in find_primitive_root(23) assert 3 in find_primitive_root(7) assert find_primitive_root(4) == [] ...
[ { "docstring": null, "function_declaration": "def prime_check(num):", "function_name": "prime_check", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def find_primitive_root(n):", "function_name": "find_primitive_root", "parameter_list": "(n)" }, { ...
[ 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 prime_check(num: int) -> bool:\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041792", "row_id": 41792, "seed_ids": "[146]" }
0.517852
Data_Structure_41792
I
[ "prime_check", "find_primitive_root", "alice_private_key", "alice_public_key", "bob_private_key", "bob_public_key", "alice_shared_key", "bob_shared_key", "diffie_hellman_key_exchange" ]
9
[ [ "diffie_hellman_key_exchange", "alice_private_key" ], [ "diffie_hellman_key_exchange", "alice_public_key" ], [ "diffie_hellman_key_exchange", "alice_shared_key" ], [ "diffie_hellman_key_exchange", "bob_private_key" ], [ "diffie_hellman_key_exchange", "bob_pu...
7
[]
false
[]
false
pytest
false
[]
true
49733d7531110f8a05f21599bbe52752ec9454d9
167105ef0cd7d026fe87e831eb12db599ea45387
v1.0
instruct
Data_Structure
Data_Structure_41912_I
### Radix Sort Implementation and Analysis You are tasked with implementing an advanced sorting algorithm, Radix Sort. This algorithm is particularly efficient for sorting lists of integers where the number of digits in the largest number is significantly smaller than the size of the list itself. Your implementation s...
from typing import List def counting_sort_for_radix(arr: List[int], exp: int) -> List[int]: 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 w...
from solution import radix_sort def test_radix_sort_basic(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_single_element(): assert radix_sort([5]) == [5] def test_radix_sort_empty_list(): assert radix_sort([]) == [] def test_radix_sort_wit...
[ { "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", ...
[ 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 counting_sort(arr: List[int], exp: int, simulation: bool):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041912", "row_id": 41912, "seed_ids": "[15]" }
0.658776
Data_Structure_41912
I
[ "counting_sort_for_radix", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort_for_radix" ] ]
1
[]
false
[]
false
pytest
true
[]
true
db5bf2589e9283984365aa0cbbf19efe619d3da0
778f02b094d60d9160b9dd7370c73c1447a9cabf
v1.0
instruct
Data_Structure
Data_Structure_41990_I
### RSA Key Generation and Encryption You are required to implement RSA encryption and decryption using the principles outlined in the RSA algorithm. Your task is to write functions that: 1. **Generate the RSA keys**: Public key (e, n) and private key (d, n). 2. **Encrypt and Decrypt Data**: Using the generated keys, ...
import random from sympy import isprime, mod_inverse def generate_prime(bits): while True: num = random.getrandbits(bits) if isprime(num): return num def generate_key(k_bits: int) -> (int, int, int): """ Generate RSA public and private keys. Args: - k_bits (int): N...
from solution import generate_key, encrypt, decrypt def test_generate_key(): n, e, d = generate_key(16) assert n > 0 assert e > 0 assert d > 0 assert gcd(e, (n//2 - 1) * (n//2 - 1)) == 1 # Check if e and phi(n) are coprime def test_encrypt_decrypt(): n, e, d = generate_key(16) data =...
[ { "docstring": null, "function_declaration": "def generate_prime(bits):", "function_name": "generate_prime", "parameter_list": "(bits)" }, { "docstring": "Generate RSA public and private keys.\n\nArgs:\n- k_bits (int): Number of bits for the primes p and q used to compute n.\n\nReturns:\n- T...
[ 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": "import random\nfrom sympy import isprime, randprime\nfrom math import gcd\n\ndef generate_key(k_bits: int) -> (int, int, int):\n if k_bits < 2:\n ra...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00041990", "row_id": 41990, "seed_ids": "[154]" }
0.719429
Data_Structure_41990
I
[ "generate_prime", "generate_key", "gcd", "encrypt", "decrypt" ]
5
[ [ "generate_key", "gcd" ], [ "generate_key", "generate_prime" ] ]
2
[]
false
[]
false
pytest
true
[ "sympy" ]
false
b392bf08bc57bdea5f8ef7e9fbe371d4b5ef66c0
bf200bd31e1c385ef85a6b79ea02d12cb5fee9ba
v1.0
instruct
Data_Structure
Data_Structure_41999_I
**Scenario**: You are tasked with implementing a modified insertion sort algorithm for a performance-critical application. The classic insertion sort algorithm works efficiently for small arrays or nearly sorted arrays, but it can be slow on larger datasets due to its O(n^2) time complexity. One way to improve insertio...
def search_insert(array, element, start, end): """ Perform a binary search to find the index at which 'element' should be inserted into 'array'. Args: array (list): The list where the search should be performed. element (int): The element for which to find the insertion index. start (int): The ...
from solution import binary_insertion_sort def test_binary_insertion_sort_empty(): assert binary_insertion_sort([]) == [] def test_binary_insertion_sort_single_element(): assert binary_insertion_sort([1]) == [1] def test_binary_insertion_sort_sorted_array(): assert binary_insertion_sort([1, 2, 3, 4, 5]) ...
[ { "docstring": "Perform a binary search to find the index at which 'element' should be inserted into 'array'.\n\nArgs:\narray (list): The list where the search should be performed.\nelement (int): The element for which to find the insertion index.\nstart (int): The starting index of the sublist to be searched.\...
[ 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 binary_search_insert_position(array, left, right, key):\n \"\"\"\n Utilizes binary search to find the insertion position for key in array[left:right...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041999", "row_id": 41999, "seed_ids": "[199]" }
0.537813
Data_Structure_41999
I
[ "search_insert", "binary_insertion_sort" ]
2
[ [ "binary_insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5161605cdd008da0af7fabfd7a40e58883d77dd6
5ba3876be14d3186138351fe9229ced862793611
v1.0
instruct
Data_Structure
Data_Structure_42036_I
### Question: Finding Primitive Roots of a Number You are required to implement functions related to finding primitive roots of a number. A primitive root of a positive integer `n` is any integer `a` such that all integers coprime with `n` are generated in a sequence modulo `n` by powers of `a`. Your implementation ne...
def find_order(a, n): """ Determine the smallest positive integer `k` such that pow(a, k) % n == 1. a: int - (must be coprime with n) n: int - positive integer Returns: k: int - the order of a modulo n, or -1 if no such k exists. """ k = 1 current = a % n while current != 1:...
from solution import find_order, euler_totient, find_primitive_root def test_find_order(): assert find_order(3, 7) == 6 assert find_order(2, 5) == 4 assert find_order(5, 9) == 6 assert find_order(7, 13) == 12 assert find_order(2, 9) == 6 def test_euler_totient(): assert euler_totient(9) == 6 ...
[ { "docstring": "Determine the smallest positive integer `k` such that pow(a, k) % n == 1.\na: int - (must be coprime with n)\nn: int - positive integer\n\nReturns:\nk: int - the order of a modulo n, or -1 if no such k exists.", "function_declaration": "def find_order(a, n):", "function_name": "find_orde...
[ 0, 0, 0, 0, 0, 1, 1, 0, 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 find_order(a, n):\n \"\"\"\n Determine the smallest positive integer `k` such that pow(a, k) % n == 1.\n a: int - (must be coprime with n)\n n...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00042036", "row_id": 42036, "seed_ids": "[160]" }
0.551526
Data_Structure_42036
I
[ "find_order", "euler_totient", "find_primitive_root" ]
3
[ [ "find_primitive_root", "euler_totient" ], [ "find_primitive_root", "find_order" ] ]
2
[]
false
[]
false
pytest
true
[]
true
34c83ae5eaffdf2a7acdd7867f6efa439ee43325
8e50229818c9c3e9b3aa6fa920cc99c57260b005
v1.0
instruct
Data_Structure
Data_Structure_42066_I
### Problem: Check if Tree is a Subtree Given two binary trees `s` and `t`, write a function `is_subtree(s, t)` that returns `True` if `t` is a subtree of `s`, and `False` otherwise. A subtree of a tree `t` is a tree consisting of a node in `t` and all of its descendants. ### Input Format: - `s`, `t` - binary trees ...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_subtree(s, t): """ Returns True if binary tree t is a subtree of binary tree s. """ if not s: return False if is_same_tree(s, t): r...
from solution import TreeNode, is_subtree def test_example_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, t) == True def t...
[]
[ 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": "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_1
{ "original_instruction": "", "prompt_id": "00042066", "row_id": 42066, "seed_ids": "[288]" }
0.59092
Data_Structure_42066
I
[ "is_subtree", "is_same_tree" ]
2
[ [ "is_subtree", "is_same_tree" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
5f0887e2ab802ba51ce19cb5896002af7ef354b4
d37c84ccab83bc17eda4963eec8c365ac7224603
v1.0
instruct
Data_Structure
Data_Structure_42083_I
You have been provided with a set of fundamental bit manipulation functions that perform basic operations on individual bits of an integer. These four functions are: 1. `get_bit(num, i)` - Returns the value of the bit at index `i`. 2. `set_bit(num, i)` - Sets the bit at index `i` to 1. 3. `clear_bit(num, i)` - Clears ...
def get_bit(num, i): """ Returns the value of the bit at index i. """ return (num >> i) & 1 def set_bit(num, i): """ Sets the bit at index i to 1. """ return num | (1 << i) def clear_bit(num, i): """ Clears (sets to 0) the bit at index i. """ return num & ~(1 << i) def...
from solution import get_bit, set_bit, clear_bit, update_bit, modify_bits def test_get_bit(): assert get_bit(0b0101, 0) == 1 assert get_bit(0b0101, 1) == 0 assert get_bit(0b0101, 2) == 1 assert get_bit(0b0101, 3) == 0 def test_set_bit(): assert set_bit(0b0100, 0) == 0b0101 assert set_bit(0b000...
[ { "docstring": "Returns the value of the bit at index i.", "function_declaration": "def get_bit(num, i):", "function_name": "get_bit", "parameter_list": "(num, i)" }, { "docstring": "Sets the bit at index i to 1.", "function_declaration": "def set_bit(num, i):", "function_name": "set...
[ 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, Tuple, Optional\n\ndef get_bit(num: int, i: int) -> int:\n \"\"\"\n Returns the value of the bit at index i.\n \"\"\"\n r...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042083", "row_id": 42083, "seed_ids": "[212]" }
0.681313
Data_Structure_42083
I
[ "get_bit", "set_bit", "clear_bit", "update_bit", "modify_bits" ]
5
[ [ "modify_bits", "clear_bit" ], [ "modify_bits", "get_bit" ], [ "modify_bits", "set_bit" ], [ "modify_bits", "update_bit" ] ]
4
[]
false
[]
false
pytest
true
[]
true
5ad60a137ccaef9bd14989e11cd8d1f47bd4a08b
228bd68d183492f7650d2ccd725894a1876e247b
v1.0
instruct
Data_Structure
Data_Structure_42101_I
### Krishnamurthy Number Checker #### Scenario: You are working on a number puzzle game where players need to identify special numbers with unique properties. A Krishnamurthy number is a special number where the sum of the factorials of its digits equals the number itself. You need to write a function to check this pr...
def find_factorial(n): """Calculates the factorial of a given number n.""" if n == 0 or n == 1: return 1 factorial = 1 for i in range(2, n + 1): factorial *= i return factorial def krishnamurthy_number(n): """Checks if n is a Krishnamurthy number.""" def compute_digit_factor...
from solution import find_factorial, krishnamurthy_number def test_find_factorial(): assert find_factorial(0) == 1 assert find_factorial(1) == 1 assert find_factorial(2) == 2 assert find_factorial(3) == 6 assert find_factorial(4) == 24 assert find_factorial(5) == 120 def test_krishnamurthy_num...
[ { "docstring": "Calculates the factorial of a given number n.", "function_declaration": "def find_factorial(n):", "function_name": "find_factorial", "parameter_list": "(n)" }, { "docstring": "Checks if n is a Krishnamurthy number.", "function_declaration": "def krishnamurthy_number(n):",...
[ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_factorial(n):\n \"\"\"\n Calculates the factorial of a given number n.\n \"\"\"\n if n == 0:\n return 1\n factorial = 1\n fo...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00042101", "row_id": 42101, "seed_ids": "[142]" }
0.623815
Data_Structure_42101
I
[ "find_factorial", "krishnamurthy_number" ]
2
[ [ "krishnamurthy_number", "find_factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6058cbfd402145a77975ae93ad40525234aadc84
0971ce45caab9953ebce8ac0b33153ed9bd69a98
v1.0
instruct
Data_Structure
Data_Structure_42136_I
### Objective Design a function that implements a string matching algorithm, demonstrating your understanding of the Knuth-Morris-Pratt (KMP) algorithm. ### Problem Statement Given two sequences, `text` and `pattern`, write a function `find_pattern_occurrences(text: Sequence[str], pattern: Sequence[str]) -> List[int]`...
from typing import List, Sequence def kmp_partial_match_table(pattern: Sequence[str]) -> List[int]: """ Generates the partial match table (pi table) using the pattern. """ m = len(pattern) pi = [0] * m k = 0 for q in range(1, m): while k > 0 and pattern[k] != pattern[q]: ...
from solution import find_pattern_occurrences def test_find_pattern_occurrences_single_occurrence(): assert find_pattern_occurrences("hello there hero!", "there") == [6] def test_find_pattern_occurrences_multiple_occurrences(): assert find_pattern_occurrences("hello there hero!", "he") == [0, 7, 12] def test...
[ { "docstring": "Generates the partial match table (pi table) using the pattern.", "function_declaration": "def kmp_partial_match_table(pattern):", "function_name": "kmp_partial_match_table", "parameter_list": "(pattern)" }, { "docstring": "Returns the starting indices of all occurrences of `...
[ 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, Sequence\n\ndef find_pattern_occurrences(text: Sequence[str], pattern: Sequence[str]) -> List[int]:\n \"\"\"\n Implement the Kn...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00042136", "row_id": 42136, "seed_ids": "[93]" }
0.619792
Data_Structure_42136
I
[ "kmp_partial_match_table", "find_pattern_occurrences" ]
2
[ [ "find_pattern_occurrences", "kmp_partial_match_table" ] ]
1
[]
false
[]
false
pytest
true
[]
true
53eae5e50ff3f986bee413930874b4edfa724605
14958c79ac2ba01788885d003f0c50501ba3186f
v1.0
instruct
Data_Structure
Data_Structure_42150_I
### Gnome Sort Implementation and Optimization #### Objective: You are tasked with implementing the gnome sort algorithm as provided and enhancing it to switch to a more efficient sorting algorithm when the list is longer than a certain threshold. #### Problem Statement: Write a function `enhanced_gnome_sort` that so...
def gnome_sort(arr): index = 0 while index < len(arr): if index == 0 or arr[index] >= arr[index - 1]: index += 1 else: arr[index], arr[index - 1] = arr[index - 1], arr[index] index -= 1 return arr def enhanced_gnome_sort(arr): if len(arr) <= 10: ...
from solution import enhanced_gnome_sort def test_small_list(): assert enhanced_gnome_sort([34, 2, 78, 12, 5]) == [2, 5, 12, 34, 78] assert enhanced_gnome_sort([5, 8, 1, 3, 7, 9, 2]) == [1, 2, 3, 5, 7, 8, 9] assert enhanced_gnome_sort([3, 1, 2, 2, 1, 3]) == [1, 1, 2, 2, 3, 3] def test_empty_and_single_ele...
[ { "docstring": null, "function_declaration": "def gnome_sort(arr):", "function_name": "gnome_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def enhanced_gnome_sort(arr):", "function_name": "enhanced_gnome_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 enhanced_gnome_sort(arr):\n \"\"\"\n Sorts a list of integers using the gnome sort for small lists (len <= 10) \n and quicksort for larger lists....
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042150", "row_id": 42150, "seed_ids": "[13]" }
0.607901
Data_Structure_42150
I
[ "gnome_sort", "enhanced_gnome_sort" ]
2
[ [ "enhanced_gnome_sort", "gnome_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d12bf802e6bb0a7c1f4985029c5cec2d4512b688
b8ad33dabde8799a4cc441b02d1c68e1d0bfb206
v1.0
instruct
Data_Structure
Data_Structure_42175_I
### RSA Key Generation and Encryption/Decryption Implementation As a skilled software engineer at a tech startup, you are tasked with implementing a secure message transfer system that uses RSA for encryption and decryption. Your first goal is to correctly generate RSA keys and ensure the encryption and decryption pro...
import random from sympy import isprime, mod_inverse def generate_prime(bits): """Function to generate a prime number of given bits.""" p = random.getrandbits(bits) while not isprime(p): p = random.getrandbits(bits) return p def generate_key(k): """ Generates RSA key pair. Par...
import pytest from solution import generate_key, encrypt, decrypt def test_key_generation(): n, e, d = generate_key(16) assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) assert n > 0 assert e > 0 assert d > 0 def test_encrypt_decrypt_simple(): n, e, d = gene...
[ { "docstring": "Function to generate a prime number of given bits.", "function_declaration": "def generate_prime(bits):", "function_name": "generate_prime", "parameter_list": "(bits)" }, { "docstring": "Generates RSA key pair.\n\nParameters:\nk (int): Key size in bits.\n\nReturns:\ntuple: (n...
[ 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 sympy import randprime, gcd, mod_inverse\n\ndef generate_key(k):\n \"\"\"\n Generates RSA keys.\n \n Args:\n k (int): Key s...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00042175", "row_id": 42175, "seed_ids": "[154]" }
0.613002
Data_Structure_42175
I
[ "generate_prime", "generate_key", "encrypt", "decrypt", "gcd" ]
5
[ [ "generate_key", "gcd" ], [ "generate_key", "generate_prime" ] ]
2
[]
false
[]
false
pytest
true
[ "sympy" ]
false
b83f85005fb9eed8c2ea8c32ae40926cc296d2f3
551de53d79850d6679ab8afaa1bd1a34979f2649
v1.0
instruct
Data_Structure
Data_Structure_42180_I
**Context**: You are implementing a sorting functionality for a small e-commerce site that often processes relatively small and nearly sorted datasets. Given the nature of the data, an optimized insertion sort using a helper function to find the insertion position would be an ideal choice. **Task**: Write a function `...
from typing import List def search_insert(arr: List[int], start: int, end: int, target: int) -> int: """ Helper function to find the position to insert target into arr[start:end].""" while start < end: mid = (start + end) // 2 if arr[mid] < target: start = mid + 1 else: ...
from solution import insertion_sort_with_helper def test_insertion_sort_with_helper(): assert insertion_sort_with_helper([4, 2, 6, 1, 5]) == [1, 2, 4, 5, 6] assert insertion_sort_with_helper([1, 3, 2, 4]) == [1, 2, 3, 4] assert insertion_sort_with_helper([]) == [] assert insertion_sort_with_helper([5])...
[ { "docstring": "Helper function to find the position to insert target into arr[start:end].", "function_declaration": "def search_insert(arr, start, end, target):", "function_name": "search_insert", "parameter_list": "(arr, start, end, target)" }, { "docstring": "Sorts an array of integers us...
[ 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], target: int, end: int) -> int:\n \"\"\"\n Binary search helper function to find the index w...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042180", "row_id": 42180, "seed_ids": "[199]" }
0.594431
Data_Structure_42180
I
[ "search_insert", "insertion_sort_with_helper" ]
2
[ [ "insertion_sort_with_helper", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
64fee890b11578e5c46ab16326592507e4d3d86b
c2ddc0a89f37128e712b4ade0cf736c745e204a1
v1.0
instruct
Data_Structure
Data_Structure_42186_I
## Question: Dynamic Island Tracker ### Scenario You are managing a coastal region represented by a 2D grid of water (0s) and land (1s). Initially, the grid is filled with water. Any land formation operation connects adjacent lands horizontally or vertically to form islands. Your task is to determine the number of isl...
from typing import List def find(parent, i): if parent[i] != i: parent[i] = find(parent, parent[i]) # path compression return parent[i] def union(parent, rank, x, y): rootx = find(parent, x) rooty = find(parent, y) if rootx != rooty: if rank[rootx] > rank[rooty]: ...
from solution import dynamic_island_tracker def test_no_positions(): assert dynamic_island_tracker(5, 5, []) == [] def test_single_position(): assert dynamic_island_tracker(3, 3, [[0, 0]]) == [1] def test_disconnected_positions(): assert dynamic_island_tracker(3, 3, [[0, 0], [2, 2]]) == [1, 2] def test_...
[ { "docstring": null, "function_declaration": "def find(parent, i):", "function_name": "find", "parameter_list": "(parent, i)" }, { "docstring": null, "function_declaration": "def union(parent, rank, x, y):", "function_name": "union", "parameter_list": "(parent, rank, x, y)" }, ...
[ 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 dynamic_island_tracker(rows: int, cols: int, positions: List[List[int]]) -> List[int]:\n parent = {}\n rank = {}\n isl...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042186", "row_id": 42186, "seed_ids": "[125]" }
0.625303
Data_Structure_42186
I
[ "find", "union", "dynamic_island_tracker" ]
3
[ [ "dynamic_island_tracker", "union" ], [ "union", "find" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5ff298e561f9e9344e3a7a99226a3475e945483f
880d6d584666d64f5a7b018baaf6cca2bfe0a985
v1.0
instruct
Data_Structure
Data_Structure_42221_I
### Question: Implement Secure Key Exchange using Extended GCD #### Context In modern cryptographic systems, especially those using RSA, it's critical to compute the modular inverse of large numbers for secure key exchange. To test your understanding of number theory and the Euclidean algorithm, you need to implement ...
from typing import Tuple def extended_euclid(a: int, b: int) -> Tuple[int, int, int]: if b == 0: return (1, 0, a) else: x1, y1, gcd = extended_euclid(b, a % b) x = y1 y = x1 - (a // b) * y1 return (x, y, gcd) def mod_inverse(a: int, m: int) -> int: x, y, gcd = exten...
import pytest from solution import extended_euclid, mod_inverse, secure_key_exchange def test_extended_euclid(): assert extended_euclid(1, 0) == (1, 0, 1) assert extended_euclid(25, 5) == (-1, 5, 5) or extended_euclid(25, 5) == (0, 1, 5) assert extended_euclid(240, 46) == (-9, 47, 2) or extended_euclid(240...
[ { "docstring": null, "function_declaration": "def extended_euclid(a, b):", "function_name": "extended_euclid", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def mod_inverse(a, m):", "function_name": "mod_inverse", "parameter_list": "(a, m)" }, { ...
[ 0, 0, 0, 0, 1, 0, 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": "from typing import Tuple\n\ndef extended_euclid(a: int, b: int) -> Tuple[int, int, int]:\n \"\"\"\n Computes the greatest common divisor of a and b.\n ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00042221", "row_id": 42221, "seed_ids": "[161]" }
0.507578
Data_Structure_42221
I
[ "extended_euclid", "mod_inverse", "secure_key_exchange" ]
3
[ [ "mod_inverse", "extended_euclid" ], [ "secure_key_exchange", "mod_inverse" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a8a3e04145f9d326b26b70b03e3608be2d9debd3
6c5744d5bf04be7fab847ff2c07e723925248c7a
v1.0
instruct
Data_Structure
Data_Structure_42236_I
### Scenario: You are implementing a basic recommender system using the Nearest Neighbor algorithm. Your task involves working with high-dimensional user preference vectors and a known set of content vectors to recommend the closest content to a user. Given a user vector and a set of content vectors, the goal is to ide...
import math def euclidean_distance(vector1, vector2): """ Compute the Euclidean distance between two vectors. """ return math.sqrt(sum((a - b) ** 2 for a, b in zip(vector1, vector2))) def nearest_neighbor(user_vector: tuple, content_set: dict) -> str: """ Finds and returns the content identifi...
from solution import nearest_neighbor def test_nearest_neighbor_basic(): user_vector = (3, 5, 1) content_set = { (1, 4, 2): 'Video A', (3, 5, 6): 'Video B', (4, 5, 1): 'Video C' } assert nearest_neighbor(user_vector, content_set) == 'Video C' def test_nearest_neighbor_edge_case...
[ { "docstring": "Compute the Euclidean distance between two vectors.", "function_declaration": "def euclidean_distance(vector1, vector2):", "function_name": "euclidean_distance", "parameter_list": "(vector1, vector2)" }, { "docstring": "Finds and returns the content identifier/name most simil...
[ 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 math\n\ndef euclidean_distance(vec1, vec2):\n \"\"\" Calculate the Euclidean distance between two vectors \"\"\"\n return math.sqrt(sum((a - b) *...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042236", "row_id": 42236, "seed_ids": "[260]" }
0.609568
Data_Structure_42236
I
[ "euclidean_distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
39566b1cf76e830dd844f999aa67ab516e91a106
874fd987af28186e96d865a778836ef48d50beed
v1.0
instruct
Data_Structure
Data_Structure_42279_I
### Tree Structure Printing #### Scenario: You are working on a project to visualize hierarchical data in the form of organizational or directory structures. You have been provided with a nested dictionary, where keys represent node names and their values are lists of strings or sub-elements (children of the nodes). Y...
def flatten_list(lst): flattened = [] for item in lst: if isinstance(item, list): flattened.extend(flatten_list(item)) else: flattened.append(item) return flattened def tree_print(tree): for key, values in tree.items(): flattened_values = flatten_list(val...
from solution import tree_print def test_tree_print_simple(): tree = { 'a': ['Adam', 'Book', 4], 'b': ['Bill'] } tree_print(tree) # Output should be: # a -> Adam -> Book -> 4 # b -> Bill def test_tree_print_with_nested_lists(): tree = { 'a': ['Adam', 'Book', 4], ...
[ { "docstring": null, "function_declaration": "def flatten_list(lst):", "function_name": "flatten_list", "parameter_list": "(lst)" }, { "docstring": null, "function_declaration": "def tree_print(tree):", "function_name": "tree_print", "parameter_list": "(tree)" } ]
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def tree_print(tree: dict) -> None:\n def flatten_and_print(prefix, items):\n children = []\n for i in items:\n if isinstance(i, l...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00042279", "row_id": 42279, "seed_ids": "[303]" }
0.557003
Data_Structure_42279
I
[ "flatten_list", "tree_print" ]
2
[ [ "tree_print", "flatten_list" ] ]
1
[]
false
[]
false
pytest
true
[]
true
894f1c299277dc08246b16875bdf444f9bde80f9
2eb4cb1d2b20e49ce4e150e587c5454330886e7b
v1.0
instruct
Data_Structure
Data_Structure_42310_I
### Graph Traversal and Node Count You are provided an unweighted, undirected graph represented as an adjacency list where the nodes are identified by strings. Your task is to implement both Depth First Search (DFS) and Breadth First Search (BFS) traversals and calculate the number of connected components in the graph...
from typing import Dict, List, Tuple, Set def dfs(graph: Dict[str, List[str]], start: str, visited: Set[str]): stack = [start] while stack: node = stack.pop() if node not in visited: visited.add(node) for neighbor in graph[node]: if neighbor not in visite...
import pytest from solution import traverse_and_count_components def test_traverse_and_count_components_example(): graph = { "A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B"], "E": ["B", "F"], "F": ["C", "E"], "G": ["H"], "H": ["G"] ...
[ { "docstring": null, "function_declaration": "def dfs(graph, start, visited):", "function_name": "dfs", "parameter_list": "(graph, start, visited)" }, { "docstring": null, "function_declaration": "def bfs(graph, start, visited):", "function_name": "bfs", "parameter_list": "(graph...
[ 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 Dict, List, Tuple, Set\n\ndef traverse_and_count_components(graph: Dict[str, List[str]], start: str) -> Tuple[Set[str], Set[str], int]:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042310", "row_id": 42310, "seed_ids": "[224]" }
0.634763
Data_Structure_42310
I
[ "dfs", "bfs", "count_connected_components", "traverse_and_count_components" ]
4
[ [ "count_connected_components", "dfs" ], [ "traverse_and_count_components", "bfs" ], [ "traverse_and_count_components", "count_connected_components" ], [ "traverse_and_count_components", "dfs" ] ]
4
[]
false
[]
false
pytest
true
[]
true
bab1a5e50f1de17899df9f5bedbc28c2a896a5e6
3c0ad44ed3f8890cfd428071961f29a6b11e1f32
v1.0
instruct
Data_Structure
Data_Structure_42325_I
You are given a positive integer `n` and another integer `a` such that \(\text{gcd}(a, n) = 1\). The order of `a` modulo `n` is the smallest positive integer `k` such that \(a^k \equiv 1 \pmod{n}\). Write a function that computes this order or returns -1 if it does not exist. ### Function Signature ```python def find...
import math def gcd(a, b): while b: a, b = b, a % b return a def find_order(a: int, n: int) -> int: """ Finds the smallest positive integer k such that a^k ≡ 1 (mod n). If no such k exists, returns -1. """ # If gcd(a, n) != 1, then no such k exists. if gcd(a, n) != 1: r...
from solution import find_order def test_find_order_basic(): assert find_order(2, 5) == 4 assert find_order(3, 7) == 6 def test_find_order_non_coprime(): assert find_order(2, 4) == -1 assert find_order(12, 15) == -1 def test_find_order_other_cases(): assert find_order(2, 9) == 6 assert find_o...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Finds the smallest positive integer k such that a^k ≡ 1 (mod n).\nIf no such k exists, returns -1.", "function_declaration": "def find_order(a, n):", "...
[ 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 gcd(x, y):\n \"\"\"\n Helper function to compute the greatest common divisor of x and y.\n \"\"\"\n while(y):\n x, y = y, x % y\n re...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00042325", "row_id": 42325, "seed_ids": "[150]" }
0.565625
Data_Structure_42325
I
[ "gcd", "find_order" ]
2
[ [ "find_order", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
aef36124198adabe6bc1fd639f25c36761e4e931
52e347c45e88be11f2ea398cf1b736445374f1d2
v1.0
instruct
Data_Structure
Data_Structure_42336_I
You are provided with a list of floating point numbers. Your task is to write a function called `bucket_sort` that sorts these numbers using the bucket sort algorithm. Additionally, make improvements to handle poor distributions efficiently. Ensure that the bucket sort is not only competitive in best-case scenarios but...
from typing import List import math def insertion_sort(bucket): """ Helper function to sort an individual bucket using insertion sort, which is efficient for small datasets. """ for i in range(1, len(bucket)): key = bucket[i] j = i - 1 while j >= 0 and bucket[j] > key: ...
from solution import bucket_sort def test_bucket_sort_unsorted(): assert bucket_sort([0.45, 0.12, 0.89, 0.39, 0.71]) == [0.12, 0.39, 0.45, 0.71, 0.89] def test_bucket_sort_mixed(): assert bucket_sort([0.23, 0.56, 0.22, 0.78, 0.35]) == [0.22, 0.23, 0.35, 0.56, 0.78] def test_bucket_sort_empty(): assert bu...
[ { "docstring": "Helper function to sort an individual bucket using insertion sort,\nwhich is efficient for small datasets.", "function_declaration": "def insertion_sort(bucket):", "function_name": "insertion_sort", "parameter_list": "(bucket)" }, { "docstring": "Sorts a list of floating poin...
[ 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 insertion_sort(arr: List[float]) -> List[float]]:\n \"\"\"\n Helper function to sort an individual bucket using insertion...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042336", "row_id": 42336, "seed_ids": "[26]" }
0.655818
Data_Structure_42336
I
[ "insertion_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
99e33bfaac7df4fe90d55fe9f852f7d2a84fb57e
6ac5d9a057d7564870adf5c625eed89533537c03
v1.0
instruct
Data_Structure
Data_Structure_42357_I
### Rabin-Miller Primality Test Function Implementation As a programming student, your task is to implement the Rabin-Miller primality test that determines if a given number \( n \) is a prime. The test is probabilistic with a tunable parameter \( k \) determining the number of iterations to increase confidence in the...
import random def pow2_factor(num): """ Factoring out the power of 2 from the number """ r = 0 d = num while d % 2 == 0: d //= 2 r += 1 return r, d def valid_witness(a, n, r, d): """ Check if a is a witness to the compositeness of n """ x = pow(a, d, n) if x == 1 or x =...
from solution import is_prime def test_small_primes(): assert is_prime(2, 5) == True assert is_prime(3, 5) == True def test_small_composites(): assert is_prime(4, 5) == False assert is_prime(6, 5) == False def test_large_primes(): # Using known large primes for testing assert is_prime(101, 5)...
[ { "docstring": "Factoring out the power of 2 from the number ", "function_declaration": "def pow2_factor(num):", "function_name": "pow2_factor", "parameter_list": "(num)" }, { "docstring": "Check if a is a witness to the compositeness of n ", "function_declaration": "def valid_witness(a,...
[ 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 pow2_factor(num: int) -> (int, int):\n \"\"\"Factor out powers of 2 from num such that num = 2^r * d with d odd.\"\"\"\n r = 0\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042357", "row_id": 42357, "seed_ids": "[136]" }
0.730951
Data_Structure_42357
I
[ "pow2_factor", "valid_witness", "is_prime" ]
3
[ [ "is_prime", "pow2_factor" ], [ "is_prime", "valid_witness" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a394656464c54d2a8c09e17f0584128d9d3f9098
9443c79906e1b60391e592fa2c2cf17582ede222
v1.0
instruct
Data_Structure
Data_Structure_42370_I
## Matrix Exponentiation Challenge ### Problem Statement You are given a square matrix `mat` of size `d x d` and a positive integer `power`. Write a function `fast_matrix_exponentiation` to compute the matrix raised to the given power using repeated squaring method. ### Function Signature ```python def fast_matrix_ex...
def matrix_mult(A, B): """ Multiplies two matrices A and B. Assumes that A and B are square matrices of same dimensions. """ n = len(A) result = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): for k in range(n): result[i][j] += A[i][k] * ...
import pytest from solution import fast_matrix_exponentiation def test_case_1(): mat = [[1, 2], [3, 4]] power = 2 expected = [[7, 10], [15, 22]] assert fast_matrix_exponentiation(mat, power) == expected def test_case_2(): mat = [[2]] power = 3 expected = [[8]] assert fast_matrix_expone...
[ { "docstring": "Multiplies two matrices A and B.\nAssumes that A and B are square matrices of same dimensions.", "function_declaration": "def matrix_mult(A, B):", "function_name": "matrix_mult", "parameter_list": "(A, B)" }, { "docstring": "Creates an identity matrix of the given size.", ...
[ 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 matrix_multiply(A, B):\n d = len(A)\n result = [[0] * d for _ in range(d)]\n for i in range(d):\n for j in range(d):\n for k in...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042370", "row_id": 42370, "seed_ids": "[340]" }
0.520516
Data_Structure_42370
I
[ "matrix_mult", "matrix_identity", "fast_matrix_exponentiation" ]
3
[ [ "fast_matrix_exponentiation", "matrix_identity" ], [ "fast_matrix_exponentiation", "matrix_mult" ] ]
2
[]
false
[]
false
pytest
true
[]
true
33a0d6450313f52f0c01fda5b92e49db5ee77f27
21bf1bbe2ceb8cf8bdd913aef9a7dc8aec25ef9b
v1.0
instruct
Data_Structure
Data_Structure_42375_I
### Diffie-Hellman Key Exchange Simulation Implement a simplified version of the Diffie-Hellman key exchange as follows: #### Function Signatures: ```python def diffie_hellman_key_exchange(a: int, p: int, print_keys: bool = False) -> bool: """ Perform Diffie-Hellman key exchange. :param a: An integer, th...
import sympy def prime_check(p): return sympy.isprime(p) def find_primitive_root(p): if not prime_check(p): return -1 for a in range(2, p): powers = set(pow(a, i, p) for i in range(1, p)) if len(powers) == p - 1: return a return -1 def diffie_hellman_key_excha...
from solution import diffie_hellman_key_exchange def test_diffie_hellman_valid(): a = 5 p = 23 assert diffie_hellman_key_exchange(a, p, print_keys=True) == True def test_diffie_hellman_invalid_p(): a = 5 p = 24 assert diffie_hellman_key_exchange(a, p, print_keys=False) == False def test_diffi...
[ { "docstring": null, "function_declaration": "def prime_check(p):", "function_name": "prime_check", "parameter_list": "(p)" }, { "docstring": null, "function_declaration": "def find_primitive_root(p):", "function_name": "find_primitive_root", "parameter_list": "(p)" }, { ...
[ 0, 0, 0, 0, 1, 0, 1, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def prime_check(n: int) -> bool:\n \"\"\" Helper function to check if a number is prime. \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00042375", "row_id": 42375, "seed_ids": "[146]" }
0.494887
Data_Structure_42375
I
[ "prime_check", "find_primitive_root", "diffie_hellman_key_exchange" ]
3
[ [ "diffie_hellman_key_exchange", "find_primitive_root" ], [ "diffie_hellman_key_exchange", "prime_check" ], [ "find_primitive_root", "prime_check" ] ]
3
[]
false
[]
false
pytest
true
[ "sympy" ]
false
f3af0c77efef9feb570025ebd6e7e9c924b8b595
643e415affb03fd2cdc3f9187fd27640e96409d5
v1.0
instruct
Data_Structure
Data_Structure_42425_I
### Question You are required to implement a system that can efficiently manage prefix sum queries and updates on an array using a Fenwick Tree (also known as a Binary Indexed Tree). ### Task 1. **Function 1**: `construct(arr)`: - Constructs and returns a Binary Indexed Tree (BIT) from a given integer array `arr...
def construct(arr): """ Constructs and returns a Binary Indexed Tree (BIT) from a given integer array `arr`. """ n = len(arr) bit_tree = [0] * (n + 1) for i in range(n): update_bit(bit_tree, i, arr[i]) return bit_tree def get_sum(bit_tree, index): """ Returns the sum of el...
from solution import construct, get_sum, update_bit def test_construct_empty_array(): arr = [] bit_tree = construct(arr) assert bit_tree == [0] def test_construct(): arr = [1, 2, 3, 4, 5] bit_tree = construct(arr) assert bit_tree == [0, 1, 3, 3, 10, 5] def test_get_sum(): arr = [1, 2, 3, ...
[ { "docstring": "Constructs and returns a Binary Indexed Tree (BIT) from a given integer array `arr`.", "function_declaration": "def construct(arr):", "function_name": "construct", "parameter_list": "(arr)" }, { "docstring": "Returns the sum of elements from the start of the array to the give...
[ 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 construct(arr):\n \"\"\"\n Constructs and returns a Binary Indexed Tree (BIT) from a given integer array `arr`.\n \"\"\"\n n = len(arr)\n b...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00042425", "row_id": 42425, "seed_ids": "[305]" }
0.510307
Data_Structure_42425
I
[ "construct", "get_sum", "update_bit" ]
3
[ [ "construct", "update_bit" ] ]
1
[]
false
[]
false
pytest
true
[]
true
94fa0099ce97bd57ca1f5da37d9ab847044415f7
5dd87a08c33f617a924e031c9151309c3f3d52d8
v1.0
instruct
Data_Structure
Data_Structure_42434_I
### Merge Sort Implementation You are tasked with implementing the `merge_sort` function designed to sort an array of integers using the merge sort algorithm. ### Function Signature ```python def merge_sort(arr: List[int]) -> List[int]: pass ``` ### Expected Input and Output * **Input**: A list of integers `arr`...
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts an array 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_half,...
from solution import merge_sort def test_merge_sort_example_1(): assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] def test_merge_sort_example_2(): assert merge_sort([1, 3, 2, 4, 2]) == [1, 2, 2, 3, 4] def test_merge_sort_empty_array(): assert merge_sort([]) == [] def test_merg...
[ { "docstring": "Sorts an array 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 mid = len(arr) // 2\n left_ha...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042434", "row_id": 42434, "seed_ids": "[12]" }
0.666226
Data_Structure_42434
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8778e4eb7327b49ea4979812a913e53803409756
5765b24c331c4215f0bc08a1a86679a0ed47bcc9
v1.0
instruct
Data_Structure
Data_Structure_42437_I
### Dot Product of Sparse Vectors #### Problem Statement You are provided with a function to convert a list representing a vector into a compressed format (index-value pairs). The main task is to implement a new function that calculates the dot product of two such compressed vectors efficiently. This will include util...
from typing import List, Tuple def compress_vector(vector: List[float]) -> List[Tuple[int, float]]: """ Compresses a vector into a list of index-value pairs, excluding zeros. """ compressed = [] for i, value in enumerate(vector): if value != 0.0: compressed.append((i, value)) ...
def test_optimized_dot_product_all_zeros(): vector1 = [0.0, 0.0, 0.0] vector2 = [0.0, 0.0, 0.0] assert optimized_dot_product(vector1, vector2) == 0.0 def test_optimized_dot_product_mixed_values(): vector1 = [1.0, 0.0, 3.0, 0.0, 4.0] vector2 = [0.0, 2.0, 1.0, 0.0, 5.0] assert optimized_dot_produ...
[ { "docstring": "Compresses a vector into a list of index-value pairs, excluding zeros.", "function_declaration": "def compress_vector(vector):", "function_name": "compress_vector", "parameter_list": "(vector)" }, { "docstring": "Computes the dot product of two sparse vectors represented as l...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 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 List, Tuple\n\ndef compress_vector(vector: List[float]) -> List[Tuple[int, float]]:\n \"\"\"\n Converts a sparse vector into a compre...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00042437", "row_id": 42437, "seed_ids": "[341]" }
0.491366
Data_Structure_42437
I
[ "compress_vector", "optimized_dot_product" ]
2
[ [ "optimized_dot_product", "compress_vector" ] ]
1
[]
false
[]
false
pytest
false
[]
true
883c05e4e4dd407626d1ddef1b273272da696e5a
062873e8b35fb89be13d48dd42cc68b309d85717
v1.0
instruct
Data_Structure
Data_Structure_42438_I
Advanced Search Implementation You are part of a team building a high-performance search tool for large, sorted databases where the distribution of elements can vary. The current search functionality is built using binary search, but your team needs to optimize this for cases where the data is uniformly distributed. Y...
from typing import List def interpolation_search(array: List[int], search_key: int) -> int: lo, hi = 0, len(array) - 1 while lo <= hi and search_key >= array[lo] and search_key <= array[hi]: if lo == hi: if array[lo] == search_key: return lo return -1 ...
from solution import adaptive_search def test_adaptive_search_found(): assert adaptive_search([-25, -12, -1, 10, 12, 15, 20, 41, 55], -1) == 2 assert adaptive_search([5, 10, 12, 14, 17, 20, 21], 14) == 3 assert adaptive_search([5, 10, 12, 14, 17, 20, 21], 5) == 0 def test_adaptive_search_not_found(): ...
[ { "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, 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 adaptive_search(array: List[int], search_key: int) -> int:\n \"\"\"\n Performs adaptive search using Interpolation Search...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00042438", "row_id": 42438, "seed_ids": "[192]" }
0.585659
Data_Structure_42438
I
[ "interpolation_search", "binary_search", "adaptive_search" ]
3
[ [ "adaptive_search", "binary_search" ], [ "adaptive_search", "interpolation_search" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ca17b485b4ecca99ef5f47d365047cbb5e7331be
3ef2f7c177f67431d15ae1aab8bf400139254240
v1.0
instruct
Data_Structure
Data_Structure_42466_I
### Post-order Traversal Challenge You are given a binary tree, represented by the `Node` class below: ```python class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right ``` #### Task Write a function `postorder_traversal` that perform...
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def recursive_postorder(root, result): if root is not None: recursive_postorder(root.left, result) recursive_postorder(root.right, result) result.append...
from solution import Node, postorder_traversal def test_empty_tree(): assert postorder_traversal(None) == {"iterative": [], "recursive": []} def test_single_node_tree(): root = Node(1) expected = [1] assert postorder_traversal(root) == {"iterative": expected, "recursive": expected} def test_simple_tr...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef postorde...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042466", "row_id": 42466, "seed_ids": "[308]" }
0.588295
Data_Structure_42466
I
[ "recursive_postorder", "iterative_postorder", "postorder_traversal" ]
3
[ [ "postorder_traversal", "iterative_postorder" ], [ "postorder_traversal", "recursive_postorder" ] ]
2
[]
false
[ "Node" ]
true
pytest
true
[]
true
cc4899d0124b41389383406a4a57d83cb1f8a2f3
a57e0442f1c32182b93f0aedfc780333b035f546
v1.0
instruct
Data_Structure
Data_Structure_42494_I
Given the implementations of functions to convert integers to byte arrays and back in both big-endian and little-endian formats, write a new function that takes a list of integers and returns a tuple: 1. A byte array representation of their concatenation (all integers joined together) in big-endian format. 2. The tota...
def int_to_bytes_be(integer): """ Converts an integer to a byte array in big-endian format. """ if integer == 0: return bytes([0]) byte_length = (integer.bit_length() + 7) // 8 return integer.to_bytes(byte_length, byteorder='big') def bytes_to_int_be(byte_array): """ Converts a...
from solution import concat_and_convert_to_int def test_concat_and_convert_to_int_single_element(): assert concat_and_convert_to_int([1]) == (b'\x01', 1) assert concat_and_convert_to_int([256]) == (b'\x01\x00', 256) assert concat_and_convert_to_int([65536]) == (b'\x01\x00\x00', 65536) def test_concat_and_...
[ { "docstring": "Converts an integer to a byte array in big-endian format.", "function_declaration": "def int_to_bytes_be(integer):", "function_name": "int_to_bytes_be", "parameter_list": "(integer)" }, { "docstring": "Converts a big-endian byte array to an integer.", "function_declaratio...
[ 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 int_to_bytes_big_endian(value):\n \"\"\"\n Converts an integer to a byte array in big-endian format\n \"\"\"\n return value.to_bytes((value.bi...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042494", "row_id": 42494, "seed_ids": "[216]" }
0.592551
Data_Structure_42494
I
[ "int_to_bytes_be", "bytes_to_int_be", "concat_and_convert_to_int" ]
3
[ [ "concat_and_convert_to_int", "bytes_to_int_be" ], [ "concat_and_convert_to_int", "int_to_bytes_be" ] ]
2
[]
false
[]
false
pytest
true
[]
true
75df299d1731c914291fb182f61574654e773540
a9099aaae0805a0d8030c8a14d8d8d04da78e289
v1.0
instruct
Data_Structure
Data_Structure_42497_I
#### Scenario You are a software engineer working on a project that involves processing and analyzing hierarchical data structures. One task requires determining if a specific configuration (represented as a smaller binary tree) is present within a larger dataset structure (represented as a larger binary tree). #### ...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_same_tree(tree1, tree2): if not tree1 and not tree2: return True if not tree1 or not tree2: return False return (tree1.val == tree2.val and...
from solution import TreeNode, is_subtree def test_subtree_exists(): # Creating nodes for the larger tree n1 = TreeNode(3) n2 = TreeNode(4) n3 = TreeNode(5) n4 = TreeNode(1) n5 = TreeNode(2) n1.left = n2 n1.right = n3 n2.left = n4 n2.right = n5 # Creating nodes for the smal...
[]
[ 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": "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": "00042497", "row_id": 42497, "seed_ids": "[288]" }
0.547067
Data_Structure_42497
I
[ "is_same_tree", "is_subtree" ]
2
[ [ "is_subtree", "is_same_tree" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
da78944b60ddc2afe3f267e83dc6c639a282ca99
341ff9f85060e22af0be4b27fa2700fa14272329
v1.0
instruct
Data_Structure
Data_Structure_42549_I
### Problem: Implement In-Place Merge Sort The provided `merge_sort` function sorts an array using the Merge Sort algorithm. However, it uses additional memory which increases space complexity. Your task is to implement an in-place merge sort to reduce the space complexity. **Function Signature:** ```python def in_pl...
def in_place_merge(arr, start, mid, end): if arr[mid] <= arr[mid + 1]: # If the halves are already sorted return l, r = start, mid + 1 while l <= mid and r <= end: if arr[l] <= arr[r]: l += 1 # l is already in correct place else: temp = arr[r] ...
from solution import in_place_merge_sort def test_in_place_merge_sort_empty(): assert in_place_merge_sort([]) == [] def test_in_place_merge_sort_single_element(): assert in_place_merge_sort([1]) == [1] def test_in_place_merge_sort_multiple_elements(): assert in_place_merge_sort([38, 27, 43, 3, 9, 82, 10]...
[ { "docstring": null, "function_declaration": "def in_place_merge(arr, start, mid, end):", "function_name": "in_place_merge", "parameter_list": "(arr, start, mid, end)" }, { "docstring": null, "function_declaration": "def in_place_merge_sort(arr):", "function_name": "in_place_merge_so...
[ 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 in_place_merge_sort(arr):\n def merge(arr, l, m, r):\n # Merging two halves in place\n n1, n2 = m - l + 1, r - m\n for i in range(...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042549", "row_id": 42549, "seed_ids": "[12]" }
0.647735
Data_Structure_42549
I
[ "in_place_merge", "in_place_merge_sort" ]
2
[ [ "in_place_merge_sort", "in_place_merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d5933427209a7f30359a371b2647b151fcb627a7
a195b678ceaf526a1d868fef0635663eef7cc975
v1.0
instruct
Data_Structure
Data_Structure_42588_I
#### Scenario You are developing a program that sorts employee performance scores stored in an array. To ensure the results are consistent, you have chosen to use Heap Sort since it guarantees O(n log(n)) time complexity and sorts in place. #### Problem You need to implement a function that sorts an array in ascending...
def heapify(arr, n, i): """ To heapify a subtree rooted with node i which is an index in arr[]. n is size of 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 child of root exists and is greater than root...
from solution import heap_sort def test_heap_sort_basic(): assert heap_sort([4, 10, 3, 5, 1]) == [1, 3, 4, 5, 10] def test_heap_sort_negative(): assert heap_sort([0, -5, 3, 7, 2]) == [-5, 0, 2, 3, 7] def test_heap_sort_duplicate_values(): assert heap_sort([2, 2, 2, 2, 2]) == [2, 2, 2, 2, 2] def test_hea...
[ { "docstring": "To heapify a subtree rooted with node i which is an index in arr[].\nn is size of heap.", "function_declaration": "def heapify(arr, n, i):", "function_name": "heapify", "parameter_list": "(arr, n, i)" }, { "docstring": "Sorts the given list of integers in ascending order usin...
[ 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 heapify(arr, n, i):\n \"\"\"\n Helper function to maintain the heap property of a subtree rooted at index i,\n assuming that the subtrees are alr...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042588", "row_id": 42588, "seed_ids": "[8]" }
0.736097
Data_Structure_42588
I
[ "heapify", "heap_sort" ]
2
[ [ "heap_sort", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f429faad0e5084ff5b03cc84746656d5332dbe8d
82219c4395b72a3c6b25eda23931af7ba4932144
v1.0
instruct
Data_Structure
Data_Structure_42734_I
### Diffie-Hellman Key Exchange Implementation You are to implement a secure key exchange using the Diffie-Hellman protocol. Given a large prime number \( p \) and its primitive root \( a \), write a function that simulates the key exchange process between two parties, Alice and Bob. Your implementation should adhere ...
import math from random import randint def prime_check(num): if num <= 1: return False if num == 2 or num == 3: return True if num % 2 == 0 or num % 3 == 0: return False j = 5 while j * j <= num: if num % j == 0 or num % (j + 2) == 0: return False ...
from solution import diffie_hellman_key_exchange def test_diffie_hellman_key_exchange_valid(): # This is a simple valid test case assert diffie_hellman_key_exchange(5, 23) == True def test_diffie_hellman_key_exchange_non_prime(): # Test with a non-prime number assert diffie_hellman_key_exchange(5, 24)...
[ { "docstring": null, "function_declaration": "def prime_check(num):", "function_name": "prime_check", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def euler_totient(n):", "function_name": "euler_totient", "parameter_list": "(n)" }, { "docstri...
[ 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\nfrom random import randint\n\ndef prime_check(num):\n if num <= 1:\n return False\n if num == 2 or num == 3:\n return True\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042734", "row_id": 42734, "seed_ids": "[146]" }
0.493668
Data_Structure_42734
I
[ "prime_check", "euler_totient", "find_order", "find_primitive_root", "diffie_hellman_key_exchange" ]
5
[ [ "diffie_hellman_key_exchange", "find_primitive_root" ], [ "diffie_hellman_key_exchange", "prime_check" ], [ "find_primitive_root", "euler_totient" ], [ "find_primitive_root", "find_order" ] ]
4
[]
false
[]
false
pytest
true
[]
true
3d7d5320a98095d04588501622d790fae249855e
16bd3cead291ec681754085f1d7f85772e5e2667
v1.0
instruct
Data_Structure
Data_Structure_42822_I
### Pancake Sort Implementation You are provided with a partially implemented sorting algorithm called **Pancake Sort**. Your task is to complete this implementation ensuring it sorts the array correctly by repeatedly reversing sections of the array. #### Problem Description Implement the function `pancake_sort(arr)`...
from typing import List def flip(arr: List[int], k: int) -> None: """ Reverses the order of the first k elements in the array. """ arr[:k] = arr[:k][::-1] def find_max(arr: List[int], n: int) -> int: """ Returns the index of the maximum value in the first n elements of the array. """ m...
from solution import pancake_sort def test_pancake_sort_example1(): assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4] def test_pancake_sort_example2(): assert pancake_sort([1, 2, 3]) == [1, 2, 3] def test_pancake_sort_example3(): assert pancake_sort([9, 3, 5, 1, 7]) == [1, 3, 5, 7, 9] def test_pancake_s...
[ { "docstring": "Reverses the order of the first k elements in the array.", "function_declaration": "def flip(arr, k):", "function_name": "flip", "parameter_list": "(arr, k)" }, { "docstring": "Returns the index of the maximum value in the first n elements of the array.", "function_declar...
[ 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 pancake_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array using the Pancake Sort algorithm.\n \n Args:\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042822", "row_id": 42822, "seed_ids": "[9]" }
0.723941
Data_Structure_42822
I
[ "flip", "find_max", "pancake_sort" ]
3
[ [ "pancake_sort", "find_max" ], [ "pancake_sort", "flip" ] ]
2
[]
false
[]
false
pytest
true
[]
true
86cd86caba24b1a4ed96d5df989dc24f01f47846
40e401ff7bb1689d3ee65098def4303b08f3fc47
v1.0
instruct
Data_Structure
Data_Structure_42841_I
#### Task Write a function, `is_same_inorder(tree1: Node, tree2: Node) -> bool`, that takes two binary trees and checks if they have the same in-order traversal. #### Description Given two binary trees, determine if the sequence of values in their in-order traversal is identical. The function should be efficient in ...
class Node: def __init__(self, key): self.left = None self.right = None self.val = key def inorder_traversal(root): if root is None: return [] return inorder_traversal(root.left) + [root.val] + inorder_traversal(root.right) def is_same_inorder(tree1: Node, tree2: Node) -> b...
from solution import Node, is_same_inorder def test_identical_trees(): # Tree 1 n1 = Node(100) n2 = Node(50) n3 = Node(150) n4 = Node(25) n5 = Node(75) n6 = Node(125) n7 = Node(175) n1.left, n1.right = n2, n3 n2.left, n2.right = n4, n5 n3.left, n3.right = n6, n7 # Tree ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, value: int):\n self.value = value\n self.left = None\n self.right = None\n\ndef is_same_inorder(tree1...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042841", "row_id": 42841, "seed_ids": "[310]" }
0.547252
Data_Structure_42841
I
[ "inorder_traversal", "is_same_inorder" ]
2
[ [ "is_same_inorder", "inorder_traversal" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
b58c6e9916857e77a71f72b476d57174e9cf22dc
891510019fb1f44c1bd133568ac09975eac18ff8
v1.0
instruct
Data_Structure
Data_Structure_42849_I
You are given a square, invertible matrix represented as a list of lists in Python. Write a function `invert_matrix` that computes and returns the inverse of the matrix using the matrix inversion algorithm outlined below. ### Algorithm Steps 1. Compute the **matrix of minors**: For each element in the matrix, calculat...
def determinant(matrix): if len(matrix) == 1: return matrix[0][0] if len(matrix) == 2: return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0] det = 0 for c in range(len(matrix)): det += ((-1)**c) * matrix[0][c] * determinant(minor(matrix, 0, c)) return det def minor(ma...
from solution import invert_matrix def test_invert_matrix(): assert invert_matrix(123) == [[-1]] def test_invert_matrix_not_a_square(): assert invert_matrix([[1, 2, 3], [4, 5, 6]]) == [[-2]] def test_invert_matrix_size_less_than_2(): assert invert_matrix([[5]]) == [[-3]] def test_invert_matrix_singular_...
[ { "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, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef invert_matrix(matrix):\n if not isinstance(matrix, list) or not all(isinstance(row, list) for row in matrix):\n return [[-...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00042849", "row_id": 42849, "seed_ids": "[347]" }
0.565446
Data_Structure_42849
I
[ "determinant", "minor", "matrix_of_minors", "matrix_of_cofactors", "transpose", "invert_matrix" ]
6
[ [ "determinant", "minor" ], [ "invert_matrix", "determinant" ], [ "invert_matrix", "matrix_of_cofactors" ], [ "invert_matrix", "matrix_of_minors" ], [ "invert_matrix", "transpose" ], [ "matrix_of_minors", "determinant" ], [ "matrix_of_minor...
7
[]
false
[]
false
pytest
true
[]
true
8d55e00e20b80ca02975d39514aae3fc257df09c
d4e2961da115932a20519870923666a931522baa
v1.0
instruct
Data_Structure
Data_Structure_42888_I
### RSA Encryption Design & Implementation As a new encryption expert, you've been tasked with developing a secure communication channel for a company's internal systems, using RSA encryption. **Objective**: Implement an RSA encryption-decryption system tailored for small data messages. You need to: 1. Write a funct...
import random from sympy import isprime, mod_inverse def generate_prime(bits, seed=None): if seed is not None: random.seed(seed) while True: num = random.getrandbits(bits) if isprime(num): return num def generate_rsa_keys(bits, seed=None): if bits <= 1: raise Va...
from solution import generate_rsa_keys, rsa_encrypt, rsa_decrypt def test_generate_rsa_keys(): n, e, d = generate_rsa_keys(16, seed=42) assert n > 0 assert e > 0 assert d > 0 def test_rsa_encrypt_decrypt(): n, e, d = generate_rsa_keys(16, seed=42) data = 123 encrypted_data = rsa_encrypt(da...
[ { "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_rsa_keys(bits, seed=None):", "function_name": "generate_rsa_keys...
[ 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 sympy import isprime, gcd\n\ndef generate_large_prime(bits, seed=None):\n if seed is not None:\n random.seed(seed)\n while Tr...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00042888", "row_id": 42888, "seed_ids": "[154]" }
0.588692
Data_Structure_42888
I
[ "generate_prime", "generate_rsa_keys", "rsa_encrypt", "rsa_decrypt" ]
4
[ [ "generate_rsa_keys", "generate_prime" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
95a6db6418f020b8382dc4bc92c9e2e15e5e72e6
acae23b28166404dd9fc67269fd4bd786a9fe9d8
v1.0
instruct
Data_Structure
Data_Structure_42927_I
### Question: Implement a Function to Find the Kth Largest Element Using Bitonic Sort You are given an array of integers whose length is guaranteed to be a power of two and a positive integer `k`. Your task is to find the `k`th largest element in the array using the bitonic sort algorithm. ### Function Signature ```p...
from typing import List def bitonic_sort(arr: List[int], up: bool) -> List[int]: """ Helper function to sort an array using the bitonic sort. If `up` is True, the array is sorted in ascending order. If `up` is False, the array is sorted in descending order. """ def compare_and_swap(arr: List[in...
import pytest from solution import kth_largest_element def test_kth_largest_element_example(): arr = [3, 2, 1, 5, 6, 4] k = 2 assert kth_largest_element(arr, k) == 5 def test_kth_largest_element_smallest(): arr = [1, 2] k = 1 assert kth_largest_element(arr, k) == 2 def test_kth_largest_elemen...
[ { "docstring": "Helper function to sort an array using the bitonic sort.\nIf `up` is True, the array is sorted in ascending order.\nIf `up` is False, the array is sorted in descending order.", "function_declaration": "def bitonic_sort(arr, up):", "function_name": "bitonic_sort", "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": "from typing import List\n\ndef bitonic_sort(arr, up=True):\n \"\"\" Helper function to perform bitonic sort on the array \"\"\"\n def bitonic_merge(arr,...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00042927", "row_id": 42927, "seed_ids": "[17]" }
0.669628
Data_Structure_42927
I
[ "bitonic_sort", "kth_largest_element" ]
2
[ [ "kth_largest_element", "bitonic_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
de4b250ce9dca6c84b45c966c23a7e8b89e1522a
6ade7e2cfd26625b74743d61eb1227a1312eeaa6
v1.0
instruct
Data_Structure
Data_Structure_42934_I
### Radix Sort Implementation: Large Dataset Sorting ##### Background You are tasked with implementing a highly efficient sorting algorithm to handle a vast dataset comprising non-negative integers. Your solution must leverage the Radix Sort algorithm to sort these integers. This sorting method prioritizes digit-wise...
def enhanced_radix_sort(arr: list[int]) -> list[int]: """ This function sorts a list of non-negative integers using Radix Sort. """ if not arr: return arr # Find the maximum number in the array to determine the number of digits max_num = max(arr) exp = 1 # Start with the least...
from solution import enhanced_radix_sort def test_enhanced_radix_sort_example_1(): assert enhanced_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_enhanced_radix_sort_example_2(): assert enhanced_radix_sort([1, 4, 1, 2, 7, 5, 2]) == [1, 1, 2, 2, 4, 5, 7] def test_e...
[ { "docstring": "This function sorts a list of non-negative integers using Radix Sort.", "function_declaration": "def enhanced_radix_sort(arr):", "function_name": "enhanced_radix_sort", "parameter_list": "(arr)" }, { "docstring": "A utility function to perform counting sort on arr[] according...
[ 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 enhanced_radix_sort(arr: list[int]) -> list[int]:\n def counting_sort(arr: list[int], exp: int) -> list[int]:\n n = len(arr)\n output = [...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042934", "row_id": 42934, "seed_ids": "[15]" }
0.654989
Data_Structure_42934
I
[ "enhanced_radix_sort", "counting_sort" ]
2
[ [ "enhanced_radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
56eeefc14c85bae2af3363e8987a8093c6eacb5d
ade26ba70c3364efffabb1e04547993369a6df20
v1.0
instruct
Data_Structure
Data_Structure_42942_I
You are provided with the implementation of the Rabin-Karp algorithm for substring searching within a main string. Your task is to extend and optimize this algorithm to handle multiple patterns efficiently and reduce the likelihood of hash collisions. ### Objective Implement a function `multi_pattern_search(patterns,...
def rabin_karp_search(pattern, text, base=256, mod=101): """ Searches for occurrences of a pattern in the text using Rabin-Karp algorithm. Returns a list of starting indices where the pattern is found. """ m, n = len(pattern), len(text) if m > n: return [] # Compute the hash val...
from solution import multi_pattern_search def test_multi_pattern_search_basic(): patterns = ["abc", "bc", "a"] text = "abcabcabc" expected = { "abc": [0, 3, 6], "bc": [1, 4, 7], "a": [0, 3, 6] } assert multi_pattern_search(patterns, text) == expected def test_multi_pattern_...
[ { "docstring": "Searches for occurrences of a pattern in the text using Rabin-Karp algorithm.\nReturns a list of starting indices where the pattern is found.", "function_declaration": "def rabin_karp_search(pattern, text, base=256, mod=101):", "function_name": "rabin_karp_search", "parameter_list": ...
[ 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 rabin_karp_search(pattern, text, base=256, mod=101):\n \"\"\"\n Searches for occurrences of a pattern in the text using Rabin-Karp algorithm.\n R...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00042942", "row_id": 42942, "seed_ids": "[72]" }
0.568733
Data_Structure_42942
I
[ "rabin_karp_search", "multi_pattern_search" ]
2
[ [ "multi_pattern_search", "rabin_karp_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cc241b8a21bb86b9884d47314d840e38756ddf0e
e7fcb416d6665987aaeb33861610bd5557824948
v1.0
instruct
Data_Structure
Data_Structure_42961_I
## Objective Implement a custom hybrid sorting algorithm that combines Heap Sort with another sorting algorithm like Quick Sort to optimize sorting performance. This algorithm should dynamically decide which sorting technique to use based on the characteristics of the sub-array being sorted. ## Problem Statement Write...
def hybrid_sort(arr, threshold): """ Sorts an array of integers using a hybrid of Heap Sort and Quick Sort. :param arr: List of integers to be sorted. :param threshold: Size threshold for switching between Heap Sort and Quick Sort. For sub-arrays larger than this threshold, use He...
from solution import hybrid_sort def test_hybrid_sort_small_array(): assert hybrid_sort([3, 1, 2], 2) == [1, 2, 3] def test_hybrid_sort_with_duplicates(): assert hybrid_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], 5) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] def test_hybrid_sort_large_threshold(): assert hybrid_so...
[ { "docstring": "Sorts an array of integers using a hybrid of Heap Sort and Quick Sort.\n\n:param arr: List of integers to be sorted.\n:param threshold: Size threshold for switching between Heap Sort and Quick Sort.\n For sub-arrays larger than this threshold, use Heap Sort.\n 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": "def quick_sort(arr):\n \"\"\"\n Quick Sort implementation\n \"\"\"\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n le...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042961", "row_id": 42961, "seed_ids": "[8]" }
0.610894
Data_Structure_42961
I
[ "hybrid_sort", "quick_sort", "heap_sort" ]
3
[ [ "hybrid_sort", "heap_sort" ], [ "hybrid_sort", "quick_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2b75aa54ac930cd4af4377e399ce165a71412680
4856c1c07695e814e3d0eb3ce7353b0698196480
v1.0
instruct
Data_Structure
Data_Structure_43001_I
### Max Flow in a Transport Network You are working as a traffic engineer, and you need to determine the maximum flow of vehicles from a starting location to a destination in a transportation network, which is modeled as a directed graph. Each node represents a junction, and each directed edge represents a one-way roa...
from collections import deque, defaultdict def bfs(source, sink, parent, capacity_graph): visited = set() queue = deque([source]) visited.add(source) while queue: current = queue.popleft() for neighbor, capacity in capacity_graph[current].items(): if neighbor n...
from solution import max_flow def test_max_flow_example_case(): V = 4 edges = [(0, 1, 100), (0, 2, 100), (1, 2, 1), (1, 3, 100), (2, 3, 100)] source = 0 sink = 3 assert max_flow(V, edges, source, sink) == 200 def test_max_flow_no_flow(): V = 4 edges = [(0, 1, 100), (2, 3, 100)] source ...
[ { "docstring": null, "function_declaration": "def bfs(source, sink, parent, capacity_graph):", "function_name": "bfs", "parameter_list": "(source, sink, parent, capacity_graph)" }, { "docstring": null, "function_declaration": "def max_flow(V, edges, source, sink):", "function_name": ...
[ 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 collections import deque\n\ndef bfs(C, F, source, sink, parent):\n visited = [False] * len(C)\n queue = deque([source])\n visited[source] = True...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043001", "row_id": 43001, "seed_ids": "[240]" }
0.63624
Data_Structure_43001
I
[ "bfs", "max_flow" ]
2
[ [ "max_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1f7fdf917e6c69c13d888c96734893c86db5d5d1
18026c7e60fce03ef22da6a4f0961e29e18a10dd
v1.0
instruct
Data_Structure
Data_Structure_43065_I
### Question: Implement Efficient Sorting Algorithm #### Scenario You are working on improving a legacy system where a highly inefficient Bogo Sort algorithm was previously used. Your task is to replace it with a more efficient sorting algorithm while ensuring it meets certain performance constraints. #### Task * Wri...
from typing import List def efficient_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers in non-decreasing order using Merge Sort. Parameters: arr (List[int]): List of integers to sort. Returns: List[int]: Sorted list of integers in non-decreasing order. """ if le...
from solution import efficient_sort def test_sorted_list(): assert efficient_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_list(): assert efficient_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_unsorted_list(): assert efficient_sort([4, 2, 5, 1, 3]) == [1, 2, 3, 4, 5] def test_lis...
[ { "docstring": "Sorts a list of integers in non-decreasing order using Merge Sort.\n\nParameters:\narr (List[int]): List of integers to sort.\n\nReturns:\nList[int]: Sorted list of integers in non-decreasing order.", "function_declaration": "def efficient_sort(arr):", "function_name": "efficient_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": "from typing import List\n\ndef efficient_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of integers in non-decreasing order using Merge Sort...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043065", "row_id": 43065, "seed_ids": "[16]" }
0.621459
Data_Structure_43065
I
[ "efficient_sort", "merge" ]
2
[ [ "efficient_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5d2b9355b2ded93f216b43064dbba521f20bbb03
4f1e561e34e6451d5caf7169c91d7bfcb29967fc
v1.0
instruct
Data_Structure
Data_Structure_43090_I
#### Problem Statement: Implement a function that uses the Max-Heap Sort algorithm to sort an array of integers in ascending order, but with a twist. You should also integrate a feature to find and return the kth largest element in the array during the sorting process. #### Detailed Requirements: - Implement a functio...
from typing import List, Tuple def heapify(arr: List[int], n: int, i: int): """ Helper function to maintain the max-heap property. """ largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[largest] < arr[left]: largest = left if right < n and arr[largest] ...
from solution import heap_sort_kth_largest def test_heap_sort_kth_largest_case1(): arr = [3, 2, 3, 1, 2, 4, 5, 5, 6] k = 4 sorted_arr, kth_largest = heap_sort_kth_largest(arr, k) assert sorted_arr == [1, 2, 2, 3, 3, 4, 5, 5, 6] assert kth_largest == 4 def test_heap_sort_kth_largest_case2(): ar...
[ { "docstring": "Helper function to maintain the max-heap property.", "function_declaration": "def heapify(arr, n, i):", "function_name": "heapify", "parameter_list": "(arr, n, i)" }, { "docstring": "Function to sort the array using max-heap sort and return the sorted array \nalong with the k...
[ 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, Tuple\n\ndef heapify(arr: List[int], n: int, i: int):\n \"\"\"\n Helper function to maintain max heap property.\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043090", "row_id": 43090, "seed_ids": "[8]" }
0.71483
Data_Structure_43090
I
[ "heapify", "heap_sort_kth_largest" ]
2
[ [ "heap_sort_kth_largest", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9f5f407d5478f0930cb0d5a0f069f01267f89b72
bae8cd8f8e26f0da6340ee5c41da8c4a3abe8123
v1.0
instruct
Data_Structure
Data_Structure_43145_I
### Bitonic Sort Challenge You are tasked to implement the Bitonic Sort algorithm in Python, a parallel sorting algorithm designed for sorting sequences efficiently where the sequence length is a power of 2. This algorithm constructs a bitonic sequence and recursively sorts and merges these sequences. A bitonic sequen...
from typing import List def bitonic_merge(arr: List[int], low: int, cnt: int, reverse: bool): if cnt > 1: k = cnt // 2 for i in range(low, low + k): if (arr[i] > arr[i + k]) == (not reverse): arr[i], arr[i + k] = arr[i + k], arr[i] bitonic_merge(arr, low, k, reve...
from solution import bitonic_sort def test_bitonic_sort_ascending(): assert bitonic_sort([4, 2, 7, 1], False) == [1, 2, 4, 7] assert bitonic_sort([10, -1, 3, 7, 5, 4, 6, 2], False) == [-1, 2, 3, 4, 5, 6, 7, 10] assert bitonic_sort([], False) == [] assert bitonic_sort([1], False) == [1] def test_bitoni...
[ { "docstring": null, "function_declaration": "def bitonic_merge(arr, low, cnt, reverse):", "function_name": "bitonic_merge", "parameter_list": "(arr, low, cnt, reverse)" }, { "docstring": null, "function_declaration": "def bitonic_sort_rec(arr, low, cnt, reverse):", "function_name": ...
[ 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 bitonic_sort(arr: List[int], reverse: bool = False) -> List[int]:\n def compare_and_swap(arr, i, j, direction):\n if ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00043145", "row_id": 43145, "seed_ids": "[17]" }
0.633642
Data_Structure_43145
I
[ "bitonic_merge", "bitonic_sort_rec", "bitonic_sort" ]
3
[ [ "bitonic_sort", "bitonic_sort_rec" ], [ "bitonic_sort_rec", "bitonic_merge" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e805bdd80d6d10f3343ace10249472a05dcd75ef
48b85991fe07464db7854a6f8b679dc2c0e05863
v1.0
instruct
Data_Structure
Data_Structure_43173_I
#### Background You work as a software engineer at a company that develops tools for mathematical computations, and you need to implement a utility that computes the greatest common divisor (GCD) using Euclid's Algorithm and the least common multiple (LCM) of two integers. Given two non-negative integers `a` and `b`,...
def gcd(a: int, b: int) -> int: """ Computes the greatest common divisor (GCD) of two integers using Euclid's Algorithm. """ while b: a, b = b, a % b return a def lcm(a: int, b: int) -> int: """ Computes the least common multiple (LCM) of two integers using the relationship betw...
from solution import gcd, lcm def test_gcd(): assert gcd(48, 18) == 6 assert gcd(0, 18) == 18 assert gcd(48, 0) == 48 assert gcd(13, 13) == 13 assert gcd(7, 3) == 1 def test_lcm(): assert lcm(48, 18) == 144 assert lcm(0, 18) == 0 assert lcm(48, 0) == 0 assert lcm(13, 13) == 13 ...
[ { "docstring": "Computes the greatest common divisor (GCD) of two integers using Euclid's Algorithm.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Computes the least common multiple (LCM) of two integers using the relationsh...
[ 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 gcd(a: int, b: int) -> int:\n while b:\n a, b = b, a % b\n return a\n\ndef lcm(a: int, b: int) -> int:\n if a == 0 or b == 0:\n ret...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043173", "row_id": 43173, "seed_ids": "[166]" }
0.691601
Data_Structure_43173
I
[ "gcd", "lcm" ]
2
[ [ "lcm", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1f3808eea750401264ce1ae886d5041043f33eae
7accfb9056573bdce6efaf53abe1934b89335007
v1.0
instruct
Data_Structure
Data_Structure_43221_I
### Matrix Inversion Coding Challenge #### Introduction Matrix inversion is a fundamental concept in linear algebra, where the goal is to find a matrix B that serves as the inverse of a given matrix A. When multiplied by A, matrix B yields the identity matrix. #### Task Implement a function `invert_matrix(m: List[Lis...
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 for c in range(n): submatrix = [[matrix[i][j] for j in range(n) if j != c]...
from solution import invert_matrix def test_invert_2x2_matrix(): matrix = [ [4, 7], [2, 6] ] expected = [ [0.6, -0.7], [-0.2, 0.4] ] result = invert_matrix(matrix) assert all(abs(result[i][j] - expected[i][j]) < 1e-9 for i in range(2) for j in range(2)) def test...
[ { "docstring": null, "function_declaration": "def determinant(matrix, n):", "function_name": "determinant", "parameter_list": "(matrix, n)" }, { "docstring": null, "function_declaration": "def get_matrix_minor(matrix, i, j):", "function_name": "get_matrix_minor", "parameter_list"...
[ 0, 0, 0, 0, 1, 0, 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": "from typing import List\n\ndef invert_matrix(m: List[List[float]]) -> List[List[float]]:\n def transpose(matrix: List[List[float]]) -> List[List[float]]:\n...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00043221", "row_id": 43221, "seed_ids": "[347]" }
0.597487
Data_Structure_43221
I
[ "determinant", "get_matrix_minor", "invert_matrix" ]
3
[ [ "invert_matrix", "determinant" ], [ "invert_matrix", "get_matrix_minor" ] ]
2
[]
false
[]
false
pytest
true
[]
true
fc7e9f27808000f74c849d27c66cef3641c72ac9
2a6ff3248677c7f17834daf5e3015d616642c8ee
v1.0
instruct
Data_Structure
Data_Structure_43226_I
### Maximum Flow Network Problem with Hidden Nodes You are tasked with designing a flow network where each node represents a server, and each edge represents a direct connection between two servers with specific bandwidth limits. Given an adjacency matrix of a flow network where `graph[i][j]` represents the capacity o...
from typing import List def bfs(graph: List[List[int]], s: int, t: int, parent: List[int]) -> bool: visited = [False] * len(graph) queue = [] queue.append(s) visited[s] = True while queue: u = queue.pop(0) for ind, val in enumerate(graph[u]): if visited[ind...
from solution import maximum_flow_bfs def test_maximum_flow_bfs_example(): 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_...
[ { "docstring": null, "function_declaration": "def bfs(graph, s, t, parent):", "function_name": "bfs", "parameter_list": "(graph, s, t, parent)" }, { "docstring": null, "function_declaration": "def maximum_flow_bfs(adjacency_matrix):", "function_name": "maximum_flow_bfs", "paramet...
[ 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 List\n\ndef bfs(rGraph, s, t, parent):\n visited = [False] * len(rGraph)\n queue = []\n queue.append(s)\n visited[s] = True\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00043226", "row_id": 43226, "seed_ids": "[229]" }
0.658492
Data_Structure_43226
I
[ "bfs", "maximum_flow_bfs" ]
2
[ [ "maximum_flow_bfs", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0d7ef158feafe5ce2d82b474e18ec07e26438299
af259c698248dc667fe119ec76fd1d9e8f9fad31
v1.0
instruct
Data_Structure
Data_Structure_43303_I
### RSA Key Generation and Encryption/Decryption #### Objective: Write a Python function that generates RSA keys, encrypts, and decrypts a given message using the generated keys. Your implementation should correctly handle prime generation, modular arithmetic, and ensure valid encryption and decryption procedures. ##...
import random from sympy import isprime, mod_inverse def generate_large_prime(bits: int, seed: int = None) -> int: if seed is not None: random.seed(seed) while True: candidate = random.getrandbits(bits) candidate |= (1 << bits - 1) | 1 if isprime(candidate): return c...
from solution import rsa_keygen_encrypt_decrypt def test_rsa_encrypt_decrypt_with_seed(): result = rsa_keygen_encrypt_decrypt(16, 42, seed=12345) assert result['decrypted'] == 42 assert result['n'] > 0 assert result['e'] == 65537 assert result['d'] > 0 assert result['encrypted'] != 42 def test...
[ { "docstring": null, "function_declaration": "def generate_large_prime(bits, seed=None):", "function_name": "generate_large_prime", "parameter_list": "(bits, seed=None)" }, { "docstring": null, "function_declaration": "def rsa_keygen_encrypt_decrypt(k, data, seed=None):", "function_n...
[ 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\nfrom sympy import isprime, nextprime\nfrom math import gcd\n\ndef modinv(a, m):\n \"\"\"\n Compute the modular inverse of a under modulo ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043303", "row_id": 43303, "seed_ids": "[154]" }
0.691186
Data_Structure_43303
I
[ "generate_large_prime", "rsa_keygen_encrypt_decrypt", "gcd" ]
3
[ [ "rsa_keygen_encrypt_decrypt", "gcd" ], [ "rsa_keygen_encrypt_decrypt", "generate_large_prime" ] ]
2
[]
false
[]
false
pytest
true
[ "sympy" ]
false
7fbd9eb4cbc0dccce27c0b36f02c823da501f8a2
e6fdca8101fc89802414141204d1775d7cc6dadf
v1.0
instruct
Data_Structure
Data_Structure_43305_I
### Bucket Sort Implementation Challenge Implement a function `optimized_bucket_sort` in Python that sorts an array of integers using the bucket sort technique. You should improve upon the given code to ensure better performance and reliability while considering edge cases and potential bottlenecks. Your implementati...
from typing import List def insertion_sort(bucket: List[int]) -> List[int]: for i in range(1, len(bucket)): up = bucket[i] j = i - 1 while j >= 0 and bucket[j] > up: bucket[j + 1] = bucket[j] j -= 1 bucket[j + 1] = up return bucket def optimized_bucket_s...
from solution import optimized_bucket_sort def test_empty_array(): assert optimized_bucket_sort([]) == [] def test_single_element_array(): assert optimized_bucket_sort([1]) == [1] def test_sorted_array(): assert optimized_bucket_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): ...
[ { "docstring": null, "function_declaration": "def insertion_sort(bucket):", "function_name": "insertion_sort", "parameter_list": "(bucket)" }, { "docstring": null, "function_declaration": "def optimized_bucket_sort(arr):", "function_name": "optimized_bucket_sort", "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": "from typing import List\n\ndef optimized_bucket_sort(arr: List[int]) -> List[int]:\n if len(arr) == 0:\n return arr\n\n min_value = min(arr)\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043305", "row_id": 43305, "seed_ids": "[26]" }
0.633782
Data_Structure_43305
I
[ "insertion_sort", "optimized_bucket_sort" ]
2
[ [ "optimized_bucket_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7e6b6760cc31030bee7b8115417a03a31d707c0d
c1dfe0a9fa0b732b45534b657a59b86b3ce103ce
v1.0
instruct
Data_Structure
Data_Structure_43334_I
Enhanced Primality Check Function #### Background As part of a cybersecurity module, you are to implement a function that verifies the primality of a number and further extends the functionality by checking a range of numbers. Given the importance of prime numbers in encryption algorithms, understanding and implementi...
from typing import List def is_prime(n: int) -> bool: """ Check if a number is prime. """ 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: retur...
from solution import range_prime_check def test_range_prime_check_simple_range(): assert range_prime_check(10, 20) == [11, 13, 17, 19] def test_range_prime_check_no_primes(): assert range_prime_check(14, 16) == [] def test_range_prime_check_single_prime(): assert range_prime_check(23, 23) == [23] def te...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of all prime numbers between `start` and `end` (inclusive).", "function_declaration": "def range_prime_check(st...
[ 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 is_prime(n: int) -> bool:\n \"\"\"\n Checks if a number is a prime number.\n \"\"\"\n if n <= 1:\n return Fa...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043334", "row_id": 43334, "seed_ids": "[143]" }
0.639299
Data_Structure_43334
I
[ "is_prime", "range_prime_check" ]
2
[ [ "range_prime_check", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
95ff84f4718cfee17fb9e2cc2315a215ede9e8b0
a9dc2cfe91325ff43a625d9b0705ed1941a0cf2e
v1.0
instruct
Data_Structure
Data_Structure_43384_I
### Scenario You are maintaining a list of scores for a game that must always be sorted in ascending order. Players constantly obtain new scores, and you need to efficiently insert each new score into the sorted list. ### Problem Statement Write a function `insert_sorted_score(scores, new_score)` that takes in: - `sco...
def search_insert(array, val): low = 0 high = len(array) - 1 while low <= high: mid = low + (high - low) // 2 if val > array[mid]: low = mid + 1 else: high = mid - 1 return low def insert_sorted_score(scores, new_score): position = search_insert(score...
from solution import insert_sorted_score def test_insert_sorted_score_middle(): scores = [55, 78, 89, 92] new_score = 85 assert insert_sorted_score(scores, new_score) == [55, 78, 85, 89, 92] def test_insert_sorted_score_start(): scores = [55, 78, 89, 92] new_score = 50 assert insert_sorted_sco...
[ { "docstring": null, "function_declaration": "def search_insert(array, val):", "function_name": "search_insert", "parameter_list": "(array, val)" }, { "docstring": null, "function_declaration": "def insert_sorted_score(scores, new_score):", "function_name": "insert_sorted_score", ...
[ 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 low = 0\n high = len(array) - 1\n while low <= high:\n mid = low + (high - low) // 2\n if val > array[...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043384", "row_id": 43384, "seed_ids": "[199]" }
0.584724
Data_Structure_43384
I
[ "search_insert", "insert_sorted_score" ]
2
[ [ "insert_sorted_score", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
79dc3359aa189ffed1493d96555d4dd098810cec
64d839bd3d062c1d8873ee21bd71414b8e263ae8
v1.0
instruct
Data_Structure
Data_Structure_43435_I
### Task Write a function `lcm_bitwise(a: int, b: int) -> int` that calculates the least common multiple (LCM) of two non-negative integers using bitwise operations for the GCD calculation. The function should handle edge cases and invalid inputs appropriately. ### Input - Two non-negative integers \( a \) and \( b \)...
def gcd_bitwise(a: int, b: int) -> int: """ Calculate the GCD using the bitwise method. """ if a == 0: return b if b == 0: return a # Remove all common factors of 2 using bitwise operations shift = 0 while ((a | b) & 1) == 0: a >>= 1 b >>= 1 shift...
from solution import lcm_bitwise def test_lcm_bitwise_normal_cases(): assert lcm_bitwise(12, 15) == 60 assert lcm_bitwise(7, 5) == 35 assert lcm_bitwise(21, 6) == 42 def test_lcm_bitwise_with_zero(): assert lcm_bitwise(0, 5) == 0 assert lcm_bitwise(10, 0) == 0 def test_lcm_bitwise_with_both_zero(...
[ { "docstring": "Calculate the GCD using the bitwise method.", "function_declaration": "def gcd_bitwise(a, b):", "function_name": "gcd_bitwise", "parameter_list": "(a, b)" }, { "docstring": "Calculate the LCM using bitwise GCD calculation.", "function_declaration": "def lcm_bitwise(a, b):...
[ 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 gcd_bitwise(a: int, b: int) -> int:\n \"\"\"\n Calculate the GCD using the bitwise method.\n \"\"\"\n if a == 0:\n return b\n if b =...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00043435", "row_id": 43435, "seed_ids": "[166]" }
0.669655
Data_Structure_43435
I
[ "gcd_bitwise", "lcm_bitwise" ]
2
[ [ "lcm_bitwise", "gcd_bitwise" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f05c97428cc0ef98bad51b06808fe1a5e864e942
15a2ffe6d96bf75f7a2140c3f4511ea49ec70e37
v1.0
instruct
Data_Structure
Data_Structure_43436_I
Comb Sort Enhancement You are tasked with enhancing the Comb Sort algorithm to handle large datasets more efficiently by integrating an alternative approach for smaller gaps to optimize performance. Implement a modified version of the Comb Sort algorithm that switches to Insertion Sort when the gap becomes less or equ...
from typing import List def insertion_sort(arr: List[int], start: int, end: int) -> None: for i in range(start + 1, end + 1): key = arr[i] j = i - 1 while j >= start and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def enhanced_comb_sort(arr: Li...
from solution import enhanced_comb_sort def test_sorted_list(): assert enhanced_comb_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_order_list(): assert enhanced_comb_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_mixed_order_list(): assert enhanced_comb_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr, start, end):", "function_name": "insertion_sort", "parameter_list": "(arr, start, end)" }, { "docstring": null, "function_declaration": "def enhanced_comb_sort(arr):", "function_name": "enhanced_comb_sort", "pa...
[ 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 insertion_sort(arr: List[int], start: int, end: int) -> None:\n for i in range(start+1, end+1):\n key = arr[i]\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00043436", "row_id": 43436, "seed_ids": "[21]" }
0.624757
Data_Structure_43436
I
[ "insertion_sort", "enhanced_comb_sort" ]
2
[ [ "enhanced_comb_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0346f249ff90289e14ed6771f4096fd0455ccf70
c92995b4c29fe4db7cc90fba17423ffd30e9b0b6
v1.0
instruct
Data_Structure
Data_Structure_43440_I
Bit Manipulator You have been given a series of functions that allow you to manipulate individual bits of an integer. Your task is to implement a function that uses these bit manipulation functions to perform complex bit-wise operations on a list of integers. #### Function Specifications You need to implement the fo...
def get_bit(num, i): return (num & (1 << i)) != 0 def set_bit(num, i): return num | (1 << i) def clear_bit(num, i): mask = ~(1 << i) return num & mask def update_bit(num, i, bit): mask = ~(1 << i) return (num & mask) | (bit << i) def bit_manipulator(nums, operations): for operation in op...
def test_get_bit(): assert get_bit(5, 0) == True assert get_bit(5, 1) == False assert get_bit(5, 2) == True def test_set_bit(): assert set_bit(5, 1) == 7 assert set_bit(5, 3) == 13 assert set_bit(0, 0) == 1 def test_clear_bit(): assert clear_bit(7, 0) == 6 assert clear_bit(7, 1) == 5 ...
[ { "docstring": null, "function_declaration": "def get_bit(num, i):", "function_name": "get_bit", "parameter_list": "(num, i)" }, { "docstring": null, "function_declaration": "def set_bit(num, i):", "function_name": "set_bit", "parameter_list": "(num, i)" }, { "docstring":...
[ 0, 0, 0, 1, 1, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "# Provided helper functions\ndef get_bit(num, i):\n return (num & (1 << i)) != 0\n\ndef set_bit(num, i):\n return num | (1 << i)\n\ndef clear_bit(num, i...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00043440", "row_id": 43440, "seed_ids": "[212]" }
0.642527
Data_Structure_43440
I
[ "get_bit", "set_bit", "clear_bit", "update_bit", "bit_manipulator" ]
5
[ [ "bit_manipulator", "clear_bit" ], [ "bit_manipulator", "set_bit" ], [ "bit_manipulator", "update_bit" ] ]
3
[]
false
[]
false
pytest
false
[]
true
b4dd891129a848b3fc0c0f1f25f5edd31885fed9
fea6e34efc0daa9c01217674758e5b145e6fd5a7
v1.0
instruct
Data_Structure
Data_Structure_43474_I
### RSA Key Generation and Encryption/Decryption Implementation Using the principles of the RSA algorithm, implement a solution to generate an RSA key pair based on provided bit length `k`. Then, develop functions to encrypt and decrypt messages. #### Input: 1. `k` (int): The bit length for the modulus \(n\). 2. `dat...
import random from sympy import isprime, mod_inverse def generate_prime_candidate(k): """ Generate an odd integer randomly """ p = random.getrandbits(k) # Apply a mask to set MSB and LSB to 1 p |= (1 << k - 1) | 1 return p def generate_prime_number(k): """ Generate a prime number of k bits """...
from solution import generate_key, encrypt, decrypt, rsa_operations def test_generate_key(): n, e, d = generate_key(8) assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) def test_encrypt_decrypt(): n, e, d = generate_key(8) original_data = 45 encrypted_data = enc...
[ { "docstring": "Generate an odd integer randomly ", "function_declaration": "def generate_prime_candidate(k):", "function_name": "generate_prime_candidate", "parameter_list": "(k)" }, { "docstring": "Generate a prime number of k bits ", "function_declaration": "def generate_prime_number(...
[ 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\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime_candidate(k):\n \"\"\" Generate an odd integer randomly \"\"\"\n p = random....
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00043474", "row_id": 43474, "seed_ids": "[154]" }
0.630568
Data_Structure_43474
I
[ "generate_prime_candidate", "generate_prime_number", "generate_key", "encrypt", "decrypt", "rsa_operations" ]
6
[ [ "generate_key", "generate_prime_number" ], [ "generate_prime_number", "generate_prime_candidate" ], [ "rsa_operations", "decrypt" ], [ "rsa_operations", "encrypt" ], [ "rsa_operations", "generate_key" ] ]
5
[]
false
[]
false
pytest
true
[ "sympy" ]
false
449f45cd741e0eac5643dba48e10c7e6303893aa
d0cad3096ca82c2c9b8f9c7cb31cfef21d295709
v1.0
instruct
Data_Structure
Data_Structure_43503_I
**Title**: Optimized Prime Counting in a Range **Objective**: Write a function that counts the number of prime numbers in a given range `[a, b]`. **Function Signature**: ```python def count_primes_in_range(a: int, b: int) -> int: """ Returns the number of prime numbers between a and b (inclusive). Parame...
import math def is_prime(n): """ Check if a number is prime. """ 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 ...
from solution import count_primes_in_range def test_primes_in_small_range(): assert count_primes_in_range(10, 20) == 4 # Primes are: 11, 13, 17, 19 def test_primes_in_range_starting_from_zero(): assert count_primes_in_range(0, 10) == 4 # Primes are: 2, 3, 5, 7 def test_no_primes_in_single_number_range(): ...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns the number of prime numbers between a and b (inclusive).", "function_declaration": "def count_primes_in_range(a, 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 count_primes_in_range(a: int, b: int) -> int:\n \"\"\"\n Returns the number of prime numbers between a and b (inclusive).\n \n Using the Sieve...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00043503", "row_id": 43503, "seed_ids": "[143]" }
0.668669
Data_Structure_43503
I
[ "is_prime", "count_primes_in_range" ]
2
[ [ "count_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ba822d31e9d7db35fa6d8aab6271dc23faf61d78
6a0ab202cd8c90d548cc75550f333d70ba953a44
v1.0
instruct
Data_Structure
Data_Structure_43573_I
### Programming Challenge: Bogo Sort Simulation with Edge Case Handling #### Context Bogo Sort is a highly inefficient sorting algorithm that randomly shuffles the given array until it gets sorted. Although impractical, Bogo Sort is an interesting concept to demonstrate the implications of using randomness in algorith...
import random from typing import List def is_sorted(arr: List[int]) -> bool: """ Helper function to check if the array is sorted. """ return all(arr[i] <= arr[i+1] for i in range(len(arr)-1)) def bogo_sort(arr: List[int], simulation: bool = False) -> List[int]: """ Sorts the array using Bogo S...
from solution import bogo_sort def test_bogo_sort_empty_array(): assert bogo_sort([]) == [] def test_bogo_sort_already_sorted(): assert bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_bogo_sort_identical_elements(): assert bogo_sort([2, 2, 2]) == [2, 2, 2] def test_bogo_sort_unsorted_array(): ...
[ { "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 array using Bogo Sort.\n\nArgs:\n- arr (List[int]): The array of integers to sort.\n- simulat...
[ 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 is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to check if the array is sorted.\n \"\"\"...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00043573", "row_id": 43573, "seed_ids": "[16]" }
0.58993
Data_Structure_43573
I
[ "is_sorted", "bogo_sort" ]
2
[ [ "bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1cebf082c4c5d58cf364cfe9551815a02ec30134
f42ce652887ded959cba26f5748ffa9a1b658d4b
v1.0
instruct
Data_Structure
Data_Structure_43647_I
### Question: Optimize GCD and LCM Calculation with Additional Error Handling You are given a task to implement optimized and robust functions that compute the Greatest Common Divisor (GCD) and the Least Common Multiple (LCM) of two integers. You are also supposed to handle all potential error scenarios effectively, p...
def optimized_gcd(a, b): """ Computes the GCD of two integers a and b using bitwise operations. Includes error handling for non-integer and invalid inputs. """ if not isinstance(a, int) or not isinstance(b, int): raise ValueError("Input values must be integers.") if a == 0 and b == 0: ...
from solution import optimized_gcd, optimized_lcm def test_optimized_gcd_positive_numbers(): assert optimized_gcd(8, 12) == 4 assert optimized_gcd(54, 24) == 6 def test_optimized_gcd_negative_numbers(): assert optimized_gcd(-8, 12) == 4 assert optimized_gcd(8, -12) == 4 assert optimized_gcd(-54, -...
[ { "docstring": "Computes the GCD of two integers a and b using bitwise operations.\nIncludes error handling for non-integer and invalid inputs.", "function_declaration": "def optimized_gcd(a, b):", "function_name": "optimized_gcd", "parameter_list": "(a, b)" }, { "docstring": "Computes the L...
[ 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 optimized_gcd(a, b):\n \"\"\"\n Computes the GCD of two integers using bitwise operations and handles errors.\n \"\"\"\n # Validate inputs\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043647", "row_id": 43647, "seed_ids": "[166]" }
0.637369
Data_Structure_43647
I
[ "optimized_gcd", "optimized_lcm" ]
2
[ [ "optimized_lcm", "optimized_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
69c13cb1dba1313eb93d779acb319f41440c7e24
ec0ab8e945309c7bb920119b734d2e2bd233bca0
v1.0
instruct
Data_Structure
Data_Structure_43649_I
### Matrix Exponentiation Problem You are tasked with implementing a function to compute the matrix exponentiation of a given square matrix to a specified power. #### Function Signature ```python def matrix_power(matrix: list, power: int) -> list: ``` #### Input * `matrix` (list of list of int): A square matrix repr...
def identity_matrix(n): """Generate an identity matrix of size n x n.""" return [[1 if i == j else 0 for j in range(n)] for i in range(n)] def matrix_multiply(A, B): """Multiplies two square matrices A and B.""" n = len(A) result = [[0] * n for _ in range(n)] for i in range(n): for...
from solution import matrix_power def test_identity_matrix_power(): matrix = [ [1, 0], [0, 1] ] power = 5 expected = [ [1, 0], [0, 1] ] assert matrix_power(matrix, power) == expected def test_zero_power(): matrix = [ [3, 4], [5, 6] ] ...
[ { "docstring": "Generate an identity matrix of size n x n.", "function_declaration": "def identity_matrix(n):", "function_name": "identity_matrix", "parameter_list": "(n)" }, { "docstring": "Multiplies two square matrices A and B.", "function_declaration": "def matrix_multiply(A, B):", ...
[ 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 matrix_multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B.\n \"\"\"\n n = len(A)\n C = [[0] * n for _ in range(n)]\n for i in ra...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043649", "row_id": 43649, "seed_ids": "[340]" }
0.577352
Data_Structure_43649
I
[ "identity_matrix", "matrix_multiply", "matrix_power" ]
3
[ [ "matrix_power", "identity_matrix" ], [ "matrix_power", "matrix_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7b9853fb10a206f8d4d0612a72435b8da192f745
944fbfd17c67be489c8ca2882553de069cb3a938
v1.0
instruct
Data_Structure
Data_Structure_43748_I
You are provided with functions to compute the GCD using both Euclid's Algorithm and bitwise operations, compute the LCM, and find the number of trailing zeroes in the binary representation of an integer. Based on these functions, implement a function to determine the least common multiple (LCM) of a list of integers. ...
from math import gcd from functools import reduce def lcm(x, y): """ Computes the Least Common Multiple (LCM) of two positive integers. """ return x * y // gcd(x, y) def list_lcm(nums): """ Given a list of positive integers, computes the least common multiple (LCM) of all the integers in the l...
from solution import list_lcm def test_list_lcm_two_numbers(): assert list_lcm([4, 6]) == 12 def test_list_lcm_multiple_numbers(): assert list_lcm([2, 7, 3, 9, 4]) == 252 def test_list_lcm_with_one(): assert list_lcm([1, 4, 5, 6]) == 60 def test_list_lcm_large_numbers(): assert list_lcm([1000000, 99...
[ { "docstring": "Computes the Least Common Multiple (LCM) of two positive integers.", "function_declaration": "def lcm(x, y):", "function_name": "lcm", "parameter_list": "(x, y)" }, { "docstring": "Given a list of positive integers, computes the least common multiple (LCM) of all the integers...
[ 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 math import gcd\nfrom functools import reduce\n\ndef list_lcm(nums):\n \"\"\"\n Given a list of positive integers, computes the least common multip...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043748", "row_id": 43748, "seed_ids": "[166]" }
0.644912
Data_Structure_43748
I
[ "lcm", "list_lcm" ]
2
[ [ "list_lcm", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0a1196d6e7f82ad9da0e3f0f527add7a1f5c56e3
bd17c86768b602656017786652bec1cd0673f451
v1.0
instruct
Data_Structure
Data_Structure_43765_I
### Context Imagine you're building a predictive text engine that uses a Markov Chain to suggest the next word in a sentence. The engine has to generate the next word based on the current word, considering the probability distribution of possible subsequent words. You need to implement the functions to handle this oper...
import random def predict_next_word(chain, current_word): """ Predict the next word based on the given Markov Chain and the current word. Args: chain (dict): A dictionary representing the Markov Chain. current_word (str): The current word whose next word needs to be predicted. Returns...
from solution import predict_next_word, generate_sentence def test_predict_next_word(): chain = { 'hello': {'world': 0.5, 'there': 0.5}, 'world': {'hello': 1.0}, 'there': {'world': 1.0} } assert predict_next_word(chain, 'hello') in ['world', 'there'] assert predict_next_wor...
[ { "docstring": "Predict the next word based on the given Markov Chain and the current word.\n\nArgs:\nchain (dict): A dictionary representing the Markov Chain.\ncurrent_word (str): The current word whose next word needs to be predicted.\n\nReturns:\nstr: The next word based on the transition probabilities. Retu...
[ 0, 0, 0, 1, 0, 1, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef predict_next_word(chain, current_word):\n \"\"\"\n Given a word transition dictionary (Markov Chain) and the current word,\n thi...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00043765", "row_id": 43765, "seed_ids": "[232]" }
0.536082
Data_Structure_43765
I
[ "predict_next_word", "generate_sentence" ]
2
[ [ "generate_sentence", "predict_next_word" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b71c21e74b8e62d4ccdbdd8f4d200f22b7e9c8ea
2fe90f4a356537558d54f76cb1d477d424ff719c
v1.0
instruct
Data_Structure
Data_Structure_43867_I
### Scenario In a low-level network protocol, each packet consists of a 32-bit header where different fields are represented by specific bits. You need to write functions to manipulate these fields accurately within the header. The header fields include information such as flags and numerical values encoded in specific...
def get_field(header, i): """ Extract the bit at the `i`-th position of `header`. """ return (header >> i) & 1 def set_field(header, i): """ Set the bit at the `i`-th position of `header` to 1. """ return header | (1 << i) def clear_field(header, i): """ Clear the bit at the `i...
def test_get_field(): assert get_field(0b10101010, 3) == 1 assert get_field(0b10101010, 2) == 0 assert get_field(0b11111111, 7) == 1 assert get_field(0b00000000, 0) == 0 def test_set_field(): assert set_field(0b10101010, 5) == 0b10101010 assert set_field(0b10101010, 6) == 0b11101010 assert ...
[ { "docstring": "Extract the bit at the `i`-th position of `header`.", "function_declaration": "def get_field(header, i):", "function_name": "get_field", "parameter_list": "(header, i)" }, { "docstring": "Set the bit at the `i`-th position of `header` to 1.", "function_declaration": "def ...
[ 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 get_field(header, i):\n \"\"\"\n Returns the bit at the i-th position of the header.\n \"\"\"\n return (header >> i) & 1\n\ndef set_field(head...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043867", "row_id": 43867, "seed_ids": "[212]" }
0.502178
Data_Structure_43867
I
[ "get_field", "set_field", "clear_field", "update_field" ]
4
[ [ "update_field", "clear_field" ], [ "update_field", "set_field" ] ]
2
[]
false
[]
false
pytest
false
[]
true
78ab1fb500729861dcbe207f341288e581b8dbb4
f5c3496e9fc3fcbc27f0585747bc7c98f538fa2f
v1.0
instruct
Data_Structure
Data_Structure_43882_I
### Secure Communication Using Diffie-Hellman Key Exchange In modern secure communication systems, two parties need to exchange cryptographic keys securely over an insecure channel. The Diffie-Hellman Key Exchange algorithm allows two parties to generate a shared secret key over such a channel without directly transmi...
import random def is_prime(n): """Check if a number is prime using a simple method.""" 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 ...
from solution import diffie_hellman_secure_exchange, is_prime, is_primitive_root def test_diffie_hellman_basic(): p = 23 g = 5 shared_key = diffie_hellman_secure_exchange(p, g) assert isinstance(shared_key, int) or shared_key == False def test_diffie_hellman_large_prime(): p = 7919 g = 7 s...
[ { "docstring": "Check if a number is prime using a simple method.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Check if g is a primitive root modulo p.", "function_declaration": "def is_primitive_root(g, p):", "...
[ 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 is_prime(n):\n \"\"\"Check if a number is prime using a simple method.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00043882", "row_id": 43882, "seed_ids": "[146]" }
0.522171
Data_Structure_43882
I
[ "is_prime", "is_primitive_root", "diffie_hellman_secure_exchange", "gcd" ]
4
[ [ "diffie_hellman_secure_exchange", "is_prime" ], [ "diffie_hellman_secure_exchange", "is_primitive_root" ], [ "is_primitive_root", "gcd" ], [ "is_primitive_root", "is_prime" ] ]
4
[]
false
[]
false
pytest
true
[]
true
a455d0c8f9f5f5684bf336f015266a2c5867b6c7
325c0b69d5d2c7dc3138c76c37009783eada89fe
v1.0
instruct
Data_Structure
Data_Structure_43912_I
#### Background You are working on an urban planning project, and you need to assess the connectivity of one part of the city grid. The city is represented as a 2D grid where: - '1' denotes buildings, - '0' denotes empty plots, - '2' denotes obstacles. Your task is to determine the shortest distance from all building...
import collections from typing import List def bfs(grid, start_x, start_y, distance, reach, buildings): rows, cols = len(grid), len(grid[0]) queue = collections.deque([(start_x, start_y, 0)]) visited = set([(start_x, start_y)]) while queue: x, y, dist = queue.popleft() for...
from solution import shortest_distance def test_example_case(): grid = [ [1, 0, 2, 0, 1], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0] ] assert shortest_distance(grid) == 7 def test_no_empty_plot(): grid = [ [1, 2, 1], [2, 2, 2], [1, 2, 1] ] assert shortest_...
[ { "docstring": null, "function_declaration": "def bfs(grid, start_x, start_y, distance, reach, buildings):", "function_name": "bfs", "parameter_list": "(grid, start_x, start_y, distance, reach, buildings)" }, { "docstring": null, "function_declaration": "def shortest_distance(grid):", ...
[ 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 collections import deque\nfrom typing import List\n\ndef shortest_distance(grid: List[List[int]]) -> int:\n if not grid or not grid[0]:\n retur...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043912", "row_id": 43912, "seed_ids": "[185]" }
0.653354
Data_Structure_43912
I
[ "bfs", "shortest_distance" ]
2
[ [ "shortest_distance", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f0f1b826b9074e6767f1696d4466e3e96d20a205
11dcae4f0347ac914f716d53906454eea40f70bb
v1.0
instruct
Data_Structure
Data_Structure_43915_I
Given two binary trees `s` and `t`, determine if `t` is a subtree of `s`. A subtree of `s` is a tree consisting of a node in `s` and all of that node's descendants. ### Function Signature ```python def is_subtree(big: TreeNode, small: TreeNode) -> bool: ``` ### Input - `big` (TreeNode): The root of the binary tree `...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def comp(p: TreeNode, q: TreeNode) -> bool: if p is None and q is None: return True if p is not None and q is not None: return p.val == q.val and comp(p.left, q.left) and comp(p.ri...
def test_is_subtree(): # Helper function to create a TreeNode from list def create_tree(values): if not values: return None nodes = [TreeNode(val) if val is not None else None for val in values] for i in range(len(nodes)): if nodes[i] is not None: ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "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\n\ndef is_subtree(big: TreeNode, smal...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043915", "row_id": 43915, "seed_ids": "[288]" }
0.527112
Data_Structure_43915
I
[ "comp", "is_subtree" ]
2
[ [ "is_subtree", "comp" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
false
[]
true
4254f526679ec0ca378141732c8253fdf3ca61b2
72a3f6a2a456b73f17202305297e2fbc252f9487
v1.0
instruct
Data_Structure
Data_Structure_43917_I
#### Context: You have been presented with an intentionally inefficient sorting algorithm, Bogo Sort. Despite its impractical nature, it can be useful for understanding fundamental concepts about algorithm analysis and probabilistic methods. The following question tests your understanding of Bogo Sort by asking you to ...
from typing import List import random def is_sorted(arr: List[int]) -> bool: """ Returns True if the given array is sorted in ascending order, False otherwise. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def safe_bogo_sort(arr: List[int], ...
from solution import safe_bogo_sort def test_sorted_array(): assert safe_bogo_sort([1, 2, 3], 1) == [1, 2, 3] def test_sort_small_array(): result = safe_bogo_sort([3, 2, 1], 100) assert result == [1, 2, 3] def test_large_iterations_needed(): result = safe_bogo_sort([5, 4, 3, 2, 1], 1000) assert r...
[ { "docstring": "Returns True if the given array is sorted in ascending order, False otherwise.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Function to sort an array using Bogo Sort with enforced iteration limit.\...
[ 0, 0, 0, 1, 0, 0, 1, 0, 1, 1 ]
4
medium
0.4
{ "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 is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Checks if an array is sorted in non-decreasing order.\n \...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00043917", "row_id": 43917, "seed_ids": "[16]" }
0.535586
Data_Structure_43917
I
[ "is_sorted", "safe_bogo_sort" ]
2
[ [ "safe_bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3e61217fba89dc425d76e1b3f3fb66e6a1a45f83
9f508ce7440e9c5e8348e31afe54bd0227d26c1d
v1.0
instruct
Data_Structure
Data_Structure_43936_I
### Coding Challenge: Cosine Similarity Extension **Objective**: Given the function `cosine_similarity` that calculates the cosine similarity between two vectors, enhance it to handle edge cases more gracefully and to add the capability to compare multiple vectors against a single reference vector. **Function Definit...
from typing import List import math def dot_product(vec1, vec2): return sum(x * y for x, y in zip(vec1, vec2)) def magnitude(vec): return math.sqrt(sum(x * x for x in vec)) def cosine_similarity_calculator(vec1, vec2): mag1 = magnitude(vec1) mag2 = magnitude(vec2) if mag1 == 0: raise...
from solution import enhanced_cosine_similarity, cosine_similarity_calculator import pytest def test_enhanced_cosine_similarity_normal_case(): vec1 = [1, 1, 1] vec2s = [[1, 2, -1], [0, 0, 0], [3, 3, 3]] result = enhanced_cosine_similarity(vec1, vec2s) assert result == [0.47140452079103173, None, 1.0] ...
[ { "docstring": null, "function_declaration": "def dot_product(vec1, vec2):", "function_name": "dot_product", "parameter_list": "(vec1, vec2)" }, { "docstring": null, "function_declaration": "def magnitude(vec):", "function_name": "magnitude", "parameter_list": "(vec)" }, { ...
[ 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": "import math\n\ndef enhanced_cosine_similarity(vec1: list, vec2s: list) -> list:\n def vector_norm(vec):\n return math.sqrt(sum(x ** 2 for x in vec))...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00043936", "row_id": 43936, "seed_ids": "[149]" }
0.607291
Data_Structure_43936
I
[ "dot_product", "magnitude", "cosine_similarity_calculator", "enhanced_cosine_similarity" ]
4
[ [ "cosine_similarity_calculator", "dot_product" ], [ "cosine_similarity_calculator", "magnitude" ], [ "enhanced_cosine_similarity", "cosine_similarity_calculator" ] ]
3
[]
false
[]
false
pytest
true
[]
true
9e65ae27843300a73844f62eba96458ddb2d0836
d0eec7110530cf7b29c63ac3dd02afb72f9fd4a0
v1.0
instruct
Data_Structure
Data_Structure_43957_I
### Matrix Power Calculation **Context**: You are developing a library of linear algebra utilities for scientific computing. One of the necessary functions is efficient computation of the power of a square matrix. Your task is to implement a function that computes the power of a matrix using matrix exponentiation. **...
def matrix_multiply(mat1, mat2): """ Multiplies two matrices mat1 and mat2. """ d = len(mat1) 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] += mat1[i][k] * mat2[k][j] return result def matrix_id...
from solution import matrix_power def test_matrix_power_zero_exp(): mat = [ [2, 0], [0, 2] ] result = matrix_power(mat, 0) expected = [ [1, 0], [0, 1] ] assert result == expected def test_matrix_power_identity_matrix(): mat = [ [2, 0], [0, 2]...
[ { "docstring": "Multiplies two matrices mat1 and mat2.", "function_declaration": "def matrix_multiply(mat1, mat2):", "function_name": "matrix_multiply", "parameter_list": "(mat1, mat2)" }, { "docstring": "Returns the identity matrix of dimension d x d.", "function_declaration": "def matr...
[ 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 matrix_power(mat, n):\n \"\"\"\n Computes the power n of a square matrix mat.\n \"\"\"\n\n def identity_matrix(size):\n \"\"\"Creates a...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043957", "row_id": 43957, "seed_ids": "[340]" }
0.51414
Data_Structure_43957
I
[ "matrix_multiply", "matrix_identity", "matrix_power" ]
3
[ [ "matrix_power", "matrix_identity" ], [ "matrix_power", "matrix_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e4a2ee86d82dcb823917f4e8c715af2629966de1
523bb04b667418c7e78b23c6a2fc9dfe3e56974b
v1.0
instruct
Data_Structure
Data_Structure_43958_I
### Bogo Sort Challenge Bogo Sort, also known as permutation sort or stupid sort, is a highly inefficient sorting algorithm based on generating random permutations of its input until it finds one that is sorted. Although it is not used in practice, understanding the algorithm can highlight the importance of efficient ...
import random import time from typing import List, Tuple def is_sorted(arr: List[int]) -> bool: """ Helper function to check if a list is sorted. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort(arr: List[int]) -> Tuple[List[int],...
from solution import bogo_sort def test_bogo_sort_empty_list(): sorted_list, permutations, time_taken = bogo_sort([]) assert sorted_list == [] assert permutations == 0 assert time_taken >= 0 def test_bogo_sort_single_element(): sorted_list, permutations, time_taken = bogo_sort([1]) assert sort...
[ { "docstring": "Helper function to check if a list is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts an input list using Bogo Sort and returns a tuple consisting of the sorted list, \nthe number of per...
[ 0, 0, 0, 0, 1, 1, 1, 1, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport time\nfrom typing import List, Tuple\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to check if the list is ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00043958", "row_id": 43958, "seed_ids": "[16]" }
0.570501
Data_Structure_43958
I
[ "is_sorted", "bogo_sort" ]
2
[ [ "bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3aa81c5cace04df32c9b3d3b16ecf8a97b9ea64c
f0e4dd8c123471df6690e26b269151c23103e2a1
v1.0
instruct
Data_Structure
Data_Structure_43960_I
### Coding Problem: Advanced Interpolation Search Implementation #### Problem Description: You are tasked with implementing an enhanced version of the interpolation search algorithm that can handle non-uniform distributions efficiently. Your algorithm should still aim to maintain O(log log n) efficiency in the average...
def enhanced_interpolation_search(array, search_key): """ Returns the index of search_key in the sorted array if found, otherwise -1. """ if not array: return -1 low = 0 high = len(array) - 1 while low <= high and search_key >= array[low] and search_key <= array[high]: if l...
def test_enhanced_interpolation_search(): array = [5, 10, 12, 14, 17, 20, 21] assert enhanced_interpolation_search(array, 14) == 3 assert enhanced_interpolation_search(array, 55) == -1 assert enhanced_interpolation_search(array, 5) == 0 assert enhanced_interpolation_search([], 1) == -1 # E...
[ { "docstring": "Returns the index of search_key in the sorted array if found, otherwise -1.", "function_declaration": "def enhanced_interpolation_search(array, search_key):", "function_name": "enhanced_interpolation_search", "parameter_list": "(array, search_key)" }, { "docstring": null, ...
[ 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 enhanced_interpolation_search(array: List[int], search_key: int) -> int:\n \"\"\"\n Implements an enhanced interpolation ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043960", "row_id": 43960, "seed_ids": "[192]" }
0.557944
Data_Structure_43960
I
[ "enhanced_interpolation_search", "binary_search" ]
2
[ [ "enhanced_interpolation_search", "binary_search" ] ]
1
[]
false
[]
false
pytest
false
[]
true
3c479d6c8ef059d248d2dac610bdd150c41e23c2
06349b4a2196c34ba91659e94b292fd540171f7a
v1.0
instruct
Data_Structure
Data_Structure_43969_I
Implement a Multi-Commodity Max Flow Algorithm #### Scenario You work for a logistics company that optimizes the movement of goods through a network of warehouses and transport routes. Each path between warehouses has a certain capacity, and you need to compute the maximum number of different types of goods (commoditi...
from collections import deque def bfs(capacities, source, sink, parent): """ Returns True if there is a path from source to sink in the residual graph. Also fills parent[] to store the path. """ visited = [False] * len(capacities) queue = deque([source]) visited[source] = True whil...
from solution import multi_commodity_max_flow def test_single_commodity(): capacities = [ [0, 10, 10, 0, 0, 0], [0, 0, 2, 4, 8, 0], [0, 0, 0, 0, 9, 0], [0, 0, 0, 0, 0, 10], [0, 0, 0, 6, 0, 10], [0, 0, 0, 0, 0, 0] ] sources = [0] sinks = [5] assert mul...
[ { "docstring": "Returns True if there is a path from source to sink in the residual graph.\nAlso fills parent[] to store the path.", "function_declaration": "def bfs(capacities, source, sink, parent):", "function_name": "bfs", "parameter_list": "(capacities, source, sink, parent)" }, { "docs...
[ 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\nclass FlowNetwork:\n def __init__(self, size):\n self.size = size\n self.capacity = [[0] * size for _ in ran...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00043969", "row_id": 43969, "seed_ids": "[240]" }
0.616673
Data_Structure_43969
I
[ "bfs", "edmonds_karp", "multi_commodity_max_flow" ]
3
[ [ "edmonds_karp", "bfs" ], [ "multi_commodity_max_flow", "edmonds_karp" ] ]
2
[]
false
[]
false
pytest
true
[]
true
186ece955d228a31f0a0cfc70b1c51e8a636e50d
6324fb5f2a73881a1f8cc7dda78703099fbbffa7
v1.0
instruct
Data_Structure
Data_Structure_43979_I
### Roman Numeral Dependency Checker You are tasked with creating a utility that analyzes a list of Roman numeral dependencies in a project. Each projection module is represented by a Roman numeral and has dependencies on other modules (also represented by Roman numerals). A projection module cannot be installed unles...
from typing import List, Tuple def roman_to_int(s: str) -> int: roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} result = 0 prev_value = 0 for char in reversed(s): value = roman[char] if value < prev_value: result -= value else: r...
from solution import can_install_all_particles def test_simple_case(): modules = ["I", "II", "III", "IV"] dependencies = [("II", "I"), ("III", "II"), ("IV", "III")] assert can_install_all_particles(modules, dependencies) == ["I", "II", "III", "IV"] def test_cycle_case(): modules = ["I", "II", "III", "...
[ { "docstring": null, "function_declaration": "def roman_to_int(s):", "function_name": "roman_to_int", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def can_install_all_particles(modules, dependencies):", "function_name": "can_install_all_particles", "pa...
[ 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 roman_to_int(s):\n \"\"\"\n Converts a Roman numeral to an integer.\n \"\"\"\n roman_numerals = {\n 'I': 1, 'V': 5, 'X': 10, 'L': 50,\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00043979", "row_id": 43979, "seed_ids": "[63]" }
0.47807
Data_Structure_43979
I
[ "roman_to_int", "can_install_all_particles" ]
2
[ [ "can_install_all_particles", "roman_to_int" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2f7737cc90bdc9db4a48869a1804c32f692c0226
aa4e3b41bfdc714b08184324ffb2270d50365f9a
v1.0
instruct
Data_Structure
Data_Structure_44064_I
### Diffie-Hellman with Improved Primality Check Implement a function `secure_diffie_hellman_key_exchange(a: int, p: int) -> bool` that performs the Diffie-Hellman key exchange protocol with improved security checks. Your implementation should include the following: 1. **Function**: `secure_diffie_hellman_key_exchang...
def prime_check(num: int) -> bool: """ Check if a number is prime. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return Fals...
from solution import secure_diffie_hellman_key_exchange, prime_check, find_primitive_root def test_prime_check(): assert prime_check(2) == True assert prime_check(3) == True assert prime_check(4) == False assert prime_check(11) == True assert prime_check(18) == False assert prime_check(23) == T...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def prime_check(num):", "function_name": "prime_check", "parameter_list": "(num)" }, { "docstring": "Finds all primitive roots of n.", "function_declaration": "def find_primitive_root(n):", "function_name": "find_...
[ 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 prime_check(n: int) -> bool:\n \"\"\"\n Checks if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n retu...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044064", "row_id": 44064, "seed_ids": "[146]" }
0.470611
Data_Structure_44064
I
[ "prime_check", "find_primitive_root", "secure_diffie_hellman_key_exchange" ]
3
[ [ "find_primitive_root", "prime_check" ], [ "secure_diffie_hellman_key_exchange", "find_primitive_root" ], [ "secure_diffie_hellman_key_exchange", "prime_check" ] ]
3
[]
false
[]
false
pytest
true
[]
true
d960cba9dfe51ce97dfc9a06fab9332682c9bd02
a8fb2347c134fd48ed89b8f48794082df6c70c76
v1.0
instruct
Data_Structure
Data_Structure_44100_I
You are given a class `Graph` that models a directed graph and includes methods to determine if the graph is strongly connected. The code includes methods for adding edges, performing a Depth First Search (DFS), reversing the graph, and checking strong connectivity. ### Problem Statement Write a function `add_multiple...
class Graph: def __init__(self, vertices): self.vertices = vertices self.graph = [[] for _ in range(vertices)] def add_edge(self, u, v): self.graph[u].append(v) def _dfs(self, v, visited): visited[v] = True for i in self.graph[v]: if not visited[i]: ...
from solution import Graph, add_multiple_edges, check_strong_connectivity def test_add_multiple_edges(): graph = Graph(4) edges = [(0, 1), (1, 2), (2, 3), (3, 0)] add_multiple_edges(graph, edges) assert graph.graph == [[1], [2], [3], [0]] def test_check_strong_connectivity_true(): vertex_count = 5...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Graph:\n def __init__(self, vertices):\n self.V = vertices\n self.graph = [[] for _ in range(vertices)]\n self.rev_graph = [[] f...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044100", "row_id": 44100, "seed_ids": "[225]" }
0.594202
Data_Structure_44100
I
[ "add_multiple_edges", "check_strong_connectivity" ]
2
[ [ "check_strong_connectivity", "add_multiple_edges" ] ]
1
[]
false
[ "Graph" ]
true
pytest
true
[]
true
dc18528558333161337d42ae99cd4779fb53d4e9
da6bb7d6a814ebc410defea707007ed27d78c147
v1.0
instruct
Data_Structure
Data_Structure_44192_I
**Extended GCD Function Implementation and Application** **Context**: In cryptography, particularly in RSA algorithm, it is often required to compute Bézout's coefficients as part of the key generation and decryption processes. Bézout's coefficients are the integers \( s \) and \( t \) for two given integers \( num1 ...
def extended_gcd(num1, num2): """ Returns the Bézout's coefficients and GCD of num1 and num2. """ if num1 == 0: return (0, 1, num2) else: s, t, g = extended_gcd(num2 % num1, num1) return (t - (num2 // num1) * s, s, g) def solve_for_linear_combination(num1, num2, target): ...
from solution import extended_gcd, solve_for_linear_combination def test_extended_gcd(): s, t, g = extended_gcd(56, 15) assert g == 1 assert 56 * s + 15 * t == g s, t, g = extended_gcd(101, 10) assert g == 1 assert 101 * s + 10 * t == g s, t, g = extended_gcd(48, 18) assert g == 6 ...
[ { "docstring": "Returns the Bézout's coefficients and GCD of num1 and num2.", "function_declaration": "def extended_gcd(num1, num2):", "function_name": "extended_gcd", "parameter_list": "(num1, num2)" }, { "docstring": "Solves for the coefficients s' and t' such that:\nnum1 * s' + num2 * 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 extended_gcd(num1: int, num2: int) -> (int, int, int):\n \"\"\"\n Computes the extended GCD of num1 and num2.\n Returns a tuple (s, t, g) where s...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00044192", "row_id": 44192, "seed_ids": "[156]" }
0.586018
Data_Structure_44192
I
[ "extended_gcd", "solve_for_linear_combination" ]
2
[ [ "solve_for_linear_combination", "extended_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5b2a3fa4d6de2e2d0e7181c9a8284444cbd151cc
1598fe44e81a7356016932ce7c66844dfab8afbb
v1.0
instruct
Data_Structure
Data_Structure_44194_I
### Problem Description You are given a series of operations that manipulate specific bits within a given integer. Your task is to implement a function that will process a list of these operations and return the final modified integer. ### Function Signature ```python def bit_manipulation(start_num: int, operations: L...
from typing import List, Tuple, Optional def get_bit(num: int, bit_index: int) -> int: """ Get the value of the bit at the specified index. """ return (num >> bit_index) & 1 def set_bit(num: int, bit_index: int) -> int: """ Set the bit at the specified index to 1. """ return num | (1 <...
from solution import bit_manipulation def test_bit_manipulation(): start_num = 0b0101 # 5 in decimal operations = [ ('set', 1), # Set bit at index 1: Result -> 0b0111 (7 in decimal) ('clear', 2), # Clear bit at index 2: Result -> 0b0011 (3 in decimal) ('update', 0, 1) # Update ...
[ { "docstring": "Get the value of the bit at the specified index.", "function_declaration": "def get_bit(num, bit_index):", "function_name": "get_bit", "parameter_list": "(num, bit_index)" }, { "docstring": "Set the bit at the specified index to 1.", "function_declaration": "def set_bit(n...
[ 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, Tuple, Optional\n\ndef get_bit(num: int, bit_index: int) -> int:\n \"\"\"Returns the value of the bit at the given index.\"\"\"\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00044194", "row_id": 44194, "seed_ids": "[212]" }
0.610636
Data_Structure_44194
I
[ "get_bit", "set_bit", "clear_bit", "update_bit", "bit_manipulation" ]
5
[ [ "bit_manipulation", "clear_bit" ], [ "bit_manipulation", "get_bit" ], [ "bit_manipulation", "set_bit" ], [ "bit_manipulation", "update_bit" ] ]
4
[]
false
[]
false
pytest
true
[]
true
0213b1d4e6cb3dafa3014ab02c22561d41210d0e
95fb3c4c2d2726925df1d7441eb0bc6d4d6fa4af
v1.0
instruct
Data_Structure
Data_Structure_44262_I
### Description You are implementing a system that needs to efficiently check if numbers are prime as part of its operation. Your task is to write a function that determines whether a given number is prime. Additionally, you will write a utility function to list all prime numbers up to a given value using the prime ch...
def is_prime(n): """ Returns True if n is a prime number, False otherwise. """ 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 ...
from solution import is_prime, list_primes_up_to def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(10) == False assert is_prime(11) == True assert is_prime(1) == False assert is_prime(0) == F...
[ { "docstring": "Returns True if n is a prime number, False otherwise.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of all prime numbers from 2 to m.", "function_declaration": "def list_primes_up_to(m)...
[ 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 math\n\ndef is_prime(n):\n \"\"\"\n Returns True if n is a prime number, otherwise returns False.\n \"\"\"\n if n <= 1:\n return Fal...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00044262", "row_id": 44262, "seed_ids": "[143]" }
0.737443
Data_Structure_44262
I
[ "is_prime", "list_primes_up_to" ]
2
[ [ "list_primes_up_to", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
38c6727345aaf37c59571490eb190c68d4276951
ecc08c89869f1cbb4b2532781989430f3fb736f7