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
complete
Data_Structure
Data_Structure_9079_C
def rotate_array(array: List[int], k: int) -> List[int]: """ Rotates the array to the right by k steps. :param array: List[int] - the array to be rotated. :param k: int - the number of steps to rotate the array. :return: List[int] - the rotated array. Example: >>> rotate_array([1, ...
from typing import List def rotate_array(array: List[int], k: int) -> List[int]: """ Rotates the array to the right by k steps. :param array: List[int] - the array to be rotated. :param k: int - the number of steps to rotate the array. :return: List[int] - the rotated array. """ if not...
from solution import rotate_array def test_rotate_array_basic(): assert rotate_array([1, 2, 3, 4, 5, 6, 7], 3) == [5, 6, 7, 1, 2, 3, 4] def test_rotate_array_no_rotation(): assert rotate_array([1], 0) == [1] assert rotate_array([], 5) == [] def test_rotate_array_single_element(): assert rotate_array(...
[ { "docstring": "Rotates the array to the right by k steps.\n\n:param array: List[int] - the array to be rotated.\n:param k: int - the number of steps to rotate the array.\n:return: List[int] - the rotated array.", "function_declaration": "def rotate_array(array, k):", "function_name": "rotate_array", ...
[ 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 rotate_array(array: List[int], k: int) -> List[int]:\n \"\"\"\n Rotates the array to the right by k steps.\n \n :pa...
trial_gpt4o_2
{ "original_instruction": "### Array Rotation Problem\n\nSuppose you are an engineer working on a new feature for a data streaming service. One of the functionalities involves manipulating a circular buffer where data is constantly being rotated. You need to implement an efficient array rotation algorithm to meet the...
0.675548
Data_Structure_9079
C
[ "rotate_array", "reverse" ]
2
[ [ "rotate_array", "reverse" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8bb1047dc4e372c561cb47e6cbc967789f42e425
f87a5326c57edae91ccf734c3dd4eecad076f84f
v1.0
complete
Data_Structure
Data_Structure_6606_C
def compute_max_flow(capacity: List[List[int]], source: int, sink: int) -> int: """ Given a capacity matrix, source node, and sink node, compute the maximum possible flow using Dinic's algorithm. :param capacity: A list of lists where each list represents capacities between nodes. :param source...
from collections import deque from typing import List def bfs_level_graph(capacity: List[List[int]], source: int, sink: int, level: List[int]) -> bool: n = len(capacity) for i in range(n): level[i] = -1 level[source] = 0 q = deque([source]) while q: u = q.popleft() for ...
from solution import compute_max_flow def test_compute_max_flow_example1(): capacity = [ [0, 10, 0, 10, 0, 0], [0, 0, 4, 2, 8, 0], [0, 0, 0, 0, 0, 10], [0, 0, 0, 0, 9, 0], [0, 0, 6, 0, 0, 10], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert compute_ma...
[ { "docstring": null, "function_declaration": "def bfs_level_graph(capacity, source, sink, level):", "function_name": "bfs_level_graph", "parameter_list": "(capacity, source, sink, level)" }, { "docstring": null, "function_declaration": "def dfs_flow(u, flow, sink, capacity, level, start)...
[ 0, 0, 0, 1, 0, 1, 1, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\nfrom typing import List\n\ndef bfs_level_graph(capacity, flow, source, sink):\n level = [-1] * len(capacity)\n level[sour...
trial_gpt4o_8
{ "original_instruction": "### Maximum Flow Problem in Social Network Connections\n\nYou are working on a project for a social media application where users can send messages to each other. The application server must handle the maximum possible flow of messages between users. Given the following algorithms to solve ...
0.53302
Data_Structure_6606
C
[ "bfs_level_graph", "dfs_flow", "compute_max_flow" ]
3
[ [ "compute_max_flow", "bfs_level_graph" ], [ "compute_max_flow", "dfs_flow" ] ]
2
[]
false
[]
false
pytest
true
[]
true
badc5d8584bd33a6e2b271ecca6d6e331fe58218
695107837e579067108eb0e9ba344ba667892d9a
v1.0
complete
Data_Structure
Data_Structure_7947_C
class RBNode: def __init__(self, value, color, left=None, right=None, parent=None): self.value = value self.color = color self.left = left self.right = right self.parent = parent class RBTree: def __init__(self): self.TNULL = RBNode(0, 0) self.root = self...
class RBNode: def __init__(self, value, color, left=None, right=None, parent=None): self.value = value self.color = color self.left = left self.right = right self.parent = parent class RBTree: def __init__(self): self.TNULL = RBNode(0, 0) self.root = self...
from solution import RBNode, RBTree, find_kth_smallest def test_find_kth_smallest(): tree = RBTree() nodes = [7, 3, 18, 10, 22, 8, 11, 26] for val in nodes: tree.insert(val) # Testing kth smallest elements assert find_kth_smallest(tree, 1) == 3 assert find_kth_smallest(tree, 2) == ...
[]
[ 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 RBNode:\n def __init__(self, value, color, left=None, right=None, parent=None):\n self.value = value\n self.color = color\n self...
trial_gpt4o_0
{ "original_instruction": "### Objective\nYou are tasked with implementing a key functionality for a Red-Black Tree data structure. Specifically, you'll focus on adding a feature to find the kth smallest element in the tree. \n\n### Problem Description\nImplement the method `find_kth_smallest(tree: RBTree, k: int) ->...
0.529853
Data_Structure_7947
C
[ "inorder_traversal", "find_kth_smallest" ]
2
[ [ "find_kth_smallest", "inorder_traversal" ] ]
1
[]
false
[ "RBNode", "RBTree" ]
true
pytest
true
[]
true
a4211a887397b3ac411227b283c96bb5b08f0a38
21d348d5df89e713dabac94d4f8ac14d3a56afc5
v1.0
complete
Data_Structure
Data_Structure_7328_C
from typing import List def search_insert(arr: List[int], target: int) -> int: """ A helper function that finds the index where the target should be inserted in the sorted subarray. Assuming `arr` is sorted in non-decreasing order up to the point of insertion. """ left, right = 0, len(arr) whil...
from typing import List def search_insert(arr: List[int], target: int) -> int: """ A helper function that finds the index where the target should be inserted in the sorted subarray. Assuming `arr` is sorted in non-decreasing order up to the point of insertion. """ left, right = 0, len(arr) whil...
from solution import insertion_sort_with_helper def test_insertion_sort_basic(): assert insertion_sort_with_helper([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9] assert insertion_sort_with_helper([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12] def test_insertion_sort_empty(): assert insertion_sort_wi...
[ { "docstring": "A helper function that finds the index where the target should be inserted in the sorted subarray.\nAssuming `arr` is sorted in non-decreasing order up to the point of insertion.", "function_declaration": "def search_insert(arr, target):", "function_name": "search_insert", "parameter...
[ 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 search_insert(arr: List[int], target: int) -> int:\n \"\"\"\n Perform binary search to find the index where target should...
trial_gpt4o_1
{ "original_instruction": "Implement a function `insertion_sort_with_helper` that sorts an array of integers using the insertion sort algorithm. The function should use the provided `search_insert` method to determine the correct insertion index for each element effectively.\n\n#### Input\n- A list of integers `arr`....
0.671113
Data_Structure_7328
C
[ "search_insert", "insertion_sort_with_helper" ]
2
[ [ "insertion_sort_with_helper", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e31544812115c18157827050ea3b9d5589e2627d
cdd373356beabc526ea61a83ea2a6e29287f543a
v1.0
complete
Data_Structure
Data_Structure_8414_C
from typing import List def search_insert(lst: List[int], val: int) -> int: """ Helper function to find the insertion point using binary search. """ lo, hi = 0, len(lst) while lo < hi: mid = (lo + hi) // 2 if lst[mid] < val: lo = mid + 1 else: hi = mi...
from typing import List def search_insert(lst: List[int], val: int) -> int: """ Helper function to find the insertion point using binary search. """ lo, hi = 0, len(lst) while lo < hi: mid = (lo + hi) // 2 if lst[mid] < val: lo = mid + 1 else: hi = mi...
from solution import sorted_insertion def test_sorted_insertion_simple(): assert sorted_insertion([1, 3, 5, 6], 2) == [1, 2, 3, 5, 6] def test_sorted_insertion_middle(): assert sorted_insertion([1, 2, 4, 5, 6], 3) == [1, 2, 3, 4, 5, 6] def test_sorted_insertion_empty_list(): assert sorted_insertion([], 1...
[ { "docstring": "Helper function to find the insertion point using binary search.", "function_declaration": "def search_insert(lst, val):", "function_name": "search_insert", "parameter_list": "(lst, val)" }, { "docstring": "Inserts val into the sorted list lst while maintaining the order.", ...
[ 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 sorted_insertion(lst: List[int], val: int) -> List[int]:\n \"\"\"\n Inserts val into the sorted lst such that lst remains...
trial_gpt4o_2
{ "original_instruction": "#### Scenario\nYou are tasked with implementing a sorted insertion method that utilizes binary search to ensure efficiency. This method will help in dynamically building a sorted list by repeatedly inserting new elements while maintaining the list order.\n\n#### Problem Statement\nImplement...
0.640776
Data_Structure_8414
C
[ "search_insert", "sorted_insertion" ]
2
[ [ "sorted_insertion", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ef5c2e420a6f604ece42f8652a5ba098e9b48626
010f9f61dbe5a9407760be965fa5c2fb74330aac
v1.0
complete
Data_Structure
Data_Structure_6993_C
from typing import List def max_heap_sort(arr: List[int], simulation: bool=False) -> List[int]: """Sort the given array in ascending order using Max Heap Sort. If simulation is set to True, the function outputs the array state after each operation involving a swap or a change in the heap structure. >>> max...
from typing import List def max_heapify(arr, n, i, simulation): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[i] < arr[left]: largest = left if right < n and arr[largest] < arr[right]: largest = right if largest != i: arr[i], arr[largest] = arr[la...
from solution import max_heap_sort, min_heap_sort def test_max_heap_sort(): assert max_heap_sort([3, 2, 1, 5, 4]) == [1, 2, 3, 4, 5] assert max_heap_sort([0, -1, 3, 2, 4]) == [-1, 0, 2, 3, 4] assert max_heap_sort([]) == [] assert max_heap_sort([5]) == [5] assert max_heap_sort([5, 5, 5, 5, 5]) == [5...
[ { "docstring": null, "function_declaration": "def max_heapify(arr, n, i, simulation):", "function_name": "max_heapify", "parameter_list": "(arr, n, i, simulation)" }, { "docstring": null, "function_declaration": "def max_heap_sort(arr, simulation=False):", "function_name": "max_heap_...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef max_heapify(arr, n, i, simulation):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n and arr[le...
trial_gpt4o_8
{ "original_instruction": "You are given an array of integers, and you must implement a sorting algorithm using heap sort in Python. You need to implement both Max Heap Sort and Min Heap Sort functions that sort the array in ascending order.\n\n### Function Signature:\n```python\ndef max_heap_sort(arr: List[int], sim...
0.652588
Data_Structure_6993
C
[ "max_heapify", "max_heap_sort", "min_heapify", "min_heap_sort" ]
4
[ [ "max_heap_sort", "max_heapify" ], [ "min_heap_sort", "min_heapify" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9c978c6c8b4e5aed440e4cf02c7e4517c5fd61d8
02796a14857c2e2fe3bb23b97b66efd05bc6a05e
v1.0
complete
Data_Structure
Data_Structure_9397_C
from typing import List def optimized_shell_sort(arr: List[int]) -> List[int]: """ Sorts an array using Shell Sort with Sedgewick's gap sequence. >>> optimized_shell_sort([12, 34, 54, 2, 3]) [2, 3, 12, 34, 54] >>> optimized_shell_sort([4, 3, 2, 1]) [1, 2, 3, 4] >>> optimized_shell_sort([]) ...
from typing import List def sedgewick_gaps(size): """Generate Sedgewick's gap sequence for a given list size.""" k = 0 gaps = [] while True: gap = (4**k + 3 * 2**(k-1) + 1) if k > 0 else 1 if gap > size: break gaps.insert(0, gap) k += 1 return gaps def o...
from solution import optimized_shell_sort def test_optimized_shell_sort_example_cases(): assert optimized_shell_sort([12, 34, 54, 2, 3]) == [2, 3, 12, 34, 54] assert optimized_shell_sort([4, 3, 2, 1]) == [1, 2, 3, 4] assert optimized_shell_sort([]) == [] assert optimized_shell_sort([5]) == [5] def tes...
[ { "docstring": "Generate Sedgewick's gap sequence for a given list size.", "function_declaration": "def sedgewick_gaps(size):", "function_name": "sedgewick_gaps", "parameter_list": "(size)" }, { "docstring": "Sorts an array using Shell Sort with Sedgewick's gap sequence.", "function_decl...
[ 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 optimized_shell_sort(arr: List[int]) -> List[int]:\n def generate_sedgewick_gaps(n):\n gaps = []\n k = 1\n ...
trial_gpt4o_1
{ "original_instruction": "### Shell Sort Enhancement\nYour task is to implement a function following the principles of Shell Sort, but with an optimized gap sequence. One such sequence is Sedgewick's gap sequence: gaps chosen as 4^k + 3*2^(k-1) + 1 for `k >= 1`. This should improve performance over the simple halvin...
0.628125
Data_Structure_9397
C
[ "sedgewick_gaps", "optimized_shell_sort" ]
2
[ [ "optimized_shell_sort", "sedgewick_gaps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8e21abfbc7551673ff594bd2fbd86fcd53833666
0922183d0881296dc51add382abdc0a40fab96d4
v1.0
complete
Data_Structure
Data_Structure_7884_C
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_bst(root: TreeNode) -> bool: """ Determine if a binary tree satisfies the properties of a Binary Search Tree (BST). >>> root = TreeNode(2, TreeNode(1), Tr...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_bst_helper(node, lower=float('-inf'), upper=float('inf')): if not node: return True val = node.val if val <= lower or val >= upper: return ...
from solution import TreeNode, is_bst def test_empty_tree(): assert is_bst(None) == True def test_single_node_tree(): root = TreeNode(10) assert is_bst(root) == True def test_valid_bst_simple(): root = TreeNode(2) root.left = TreeNode(1) root.right = TreeNode(3) assert is_bst(root) == Tru...
[]
[ 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, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is...
trial_gpt4o_2
{ "original_instruction": "## Problem Statement\nYou are given a binary tree where each node contains an integer value. Your task is to determine if this tree satisfies the properties of a Binary Search Tree (BST). For a tree to be considered a BST, it must satisfy the following conditions:\n\n1. The left subtree of ...
0.600801
Data_Structure_7884
C
[ "is_bst_helper", "is_bst" ]
2
[ [ "is_bst", "is_bst_helper" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
932b58f9ac16c4798632cebba8cd18611610609e
d53eaa1c67c04df6a46e6d97dd8e1c6e5f425b32
v1.0
complete
Data_Structure
Data_Structure_8915_C
from typing import List import time def stoogesort(arr: List[int], l: int, h: int) -> None: """ Perform Stooge Sort on the array from index l to h. >>> arr = [5, 4, 3, 2, 1] >>> stoogesort(arr, 0, 4) >>> arr [1, 2, 3, 4, 5] """ pass def insertion_sort(arr: List[int]) -> List[int]: """ ...
import time from typing import List def stoogesort(arr: List[int], l: int, h: int) -> None: if l >= h: return if arr[l] > arr[h]: arr[l], arr[h] = arr[h], arr[l] if h - l + 1 > 2: t = (h - l + 1) // 3 stoogesort(arr, l, h - t) stoogesort(arr, l + t, h) stooge...
from solution import stoogesort, insertion_sort, compare_sorts import time def test_stoogesort(): arr = [5, 4, 3, 2, 1] expected = [1, 2, 3, 4, 5] stoogesort(arr, 0, len(arr) - 1) assert arr == expected def test_insertion_sort(): arr = [5, 4, 3, 2, 1] expected = [1, 2, 3, 4, 5] assert inse...
[ { "docstring": null, "function_declaration": "def stoogesort(arr, l, h):", "function_name": "stoogesort", "parameter_list": "(arr, l, h)" }, { "docstring": null, "function_declaration": "def insertion_sort(arr):", "function_name": "insertion_sort", "parameter_list": "(arr)" }, ...
[ 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 time\nfrom typing import List\n\ndef stoogesort(arr: List[int], l: int, h: int) -> None:\n if l >= h:\n return\n if arr[l] > arr[h]:\n ...
trial_gpt4o_0
{ "original_instruction": "### Question: Implement and Compare Sorting Algorithms\n\n#### Context:\nSorting is a fundamental operation in many applications, and understanding different sorting algorithms helps in choosing the most efficient one for a given context. You've seen Stooge Sort, an inefficient sorting algo...
0.589437
Data_Structure_8915
C
[ "stoogesort", "insertion_sort", "compare_sorts" ]
3
[ [ "compare_sorts", "insertion_sort" ], [ "compare_sorts", "stoogesort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d001a1453150621144c283379a01fedb66d06d5e
81edc4e9cf7fee8e0a4799a59df8836f695695f6
v1.0
complete
Data_Structure
Data_Structure_8587_C
from typing import List def gcd_multiple(numbers: List[int]) -> int: """ Returns the greatest common divisor of a list of numbers. >>> gcd_multiple([45, 90, 120]) 15 >>> gcd_multiple([81, 243]) 81 """ pass def trailing_zeros_array(numbers: List[int]) -> List[int]: """ Retu...
from functools import reduce def gcd(a, b): while b != 0: a, b = b, a % b return a def gcd_multiple(numbers): """ Returns the greatest common divisor of a list of numbers. """ return reduce(gcd, numbers) def trailing_zero(x): """ Returns the number of trailing zeros in the bin...
from solution import gcd_multiple, trailing_zeros_array def test_gcd_multiple(): assert gcd_multiple([45, 90, 120]) == 15 assert gcd_multiple([81, 243]) == 81 assert gcd_multiple([12, 15, 21]) == 3 assert gcd_multiple([10, 20, 30, 40]) == 10 assert gcd_multiple([5, 7, 11]) == 1 def test_trailing_z...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the greatest common divisor of a list of numbers.", "function_declaration": "def gcd_multiple(numbers):", "function_name": "gcd_multiple", ...
[ 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 functools import reduce\nimport math\n\ndef gcd(a, b):\n \"\"\"\n Returns the greatest common divisor (GCD) of a and b.\n \"\"\"\n while b !=...
trial_gpt4o_2
{ "original_instruction": "You are given two tasks:\n\n1. **Enhance GCD Algorithm**: Modify the standard GCD algorithm to accept multiple integers and compute their GCD. You should handle any number of integers greater than two efficiently.\n\n2. **Efficient Trailing Zero Calculation**: Implement a function to comput...
0.630521
Data_Structure_8587
C
[ "gcd", "gcd_multiple", "trailing_zero", "trailing_zeros_array" ]
4
[ [ "gcd_multiple", "gcd" ], [ "trailing_zeros_array", "trailing_zero" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9ac5ff2001e0042b44a298cae54547e8a2be5193
ffa1f0b30ab75527cd57092c50e22b3d5426de6a
v1.0
complete
Data_Structure
Data_Structure_8682_C
def search_range(nums, target): """ Returns the starting and ending positions of the given target in the list. If the target is not found, returns [-1, -1]. :param nums: List of sorted integers. :param target: Integer to search for in nums. :return: List of two integers [start, end] >>> se...
def binary_search(nums, target, find_first): left, right = 0, len(nums) - 1 result = -1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: result = mid if find_first: right = mid - 1 else: left = mid + 1 ...
from solution import search_range def test_search_range_found(): assert search_range([5, 7, 7, 8, 8, 8, 10], 8) == [3, 5] def test_search_range_not_found(): assert search_range([5, 7, 7, 8, 8, 8, 10], 11) == [-1, -1] assert search_range([], 1) == [-1, -1] assert search_range([1], 0) == [-1, -1] def t...
[ { "docstring": null, "function_declaration": "def binary_search(nums, target, find_first):", "function_name": "binary_search", "parameter_list": "(nums, target, find_first)" }, { "docstring": "Returns the starting and ending positions of the given target in the list.\nIf the target is not fo...
[ 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_range(nums, target):\n \"\"\"\n Returns the starting and ending positions of the target in a sorted array.\n If the target is not found, r...
trial_gpt4o_2
{ "original_instruction": "**Context**: In data processing and search systems, it is often required to quickly find ranges of elements matching certain criteria. For example, consider a sorted array of integers where you frequently need to determine the range of indices where a specific number appears. This can have ...
0.626914
Data_Structure_8682
C
[ "binary_search", "search_range" ]
2
[ [ "search_range", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4f2fa51d5e1c5bba3a7ac9645c1d8672a2f2bdf8
8f3cb6f6ca0a7b65689be679cfff999316e5d595
v1.0
complete
Data_Structure
Data_Structure_7927_C
from typing import List def max_flow(capacity: List[List[int]], source: int, sink: int) -> int: """ Calculate the maximum flow in a given flow network using Ford-Fulkerson, Edmonds-Karp, or Dinic's algorithm based on network properties. Args: capacity (List[List[int]]): A 2D list where capacity[i][j] r...
from collections import deque def bfs(capacity, source, sink, parent): """ Breadth-First Search to find an augmenting path in the residual graph. """ visited = [False] * len(capacity) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() for v,...
from solution import max_flow def test_example_case(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert max_flow(capacity, source, si...
[ { "docstring": "Breadth-First Search to find an augmenting path in the residual graph.", "function_declaration": "def bfs(capacity, source, sink, parent):", "function_name": "bfs", "parameter_list": "(capacity, source, sink, parent)" }, { "docstring": "Function to calculate maximum flow in a...
[ 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(capacity, source, sink, parent):\n visited = [False] * len(capacity)\n queue = deque([source])\n visited[sou...
trial_gpt4o_2
{ "original_instruction": "Design and implement an efficient algorithm for calculating the maximum flow in a given flow network using the Ford-Fulkerson, Edmonds-Karp, or Dinic's algorithm. The input will consist of the capacity matrix, source node, and sink node. You are required to handle edge cases, optimize for p...
0.580284
Data_Structure_7927
C
[ "bfs", "max_flow" ]
2
[ [ "max_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9616ebbe6d6627a9e49d877146f0c831e89933a5
c01425e1b585389d547d560c8a788ef3e62d2f4d
v1.0
complete
Data_Structure
Data_Structure_9594_C
def reverse_words(sentence: str) -> str: """ Reverses the order of words in a single sentence. >>> reverse_words("Hello world") == "world Hello" >>> reverse_words("I love coding") == "coding love I" >>> reverse_words("") == "" """ pass def reverse_sentences(sentences: List[str]) -> List[str...
def reverse_words(sentence): """ Reverses the order of words in a single sentence. """ words = sentence.split() reversed_words = words[::-1] return ' '.join(reversed_words) def reverse_sentences(sentences): """ Reverses the order of words in each sentence in a list of sentences. """...
from solution import reverse_words, reverse_sentences # Unit tests for reverse_words function def test_reverse_words_single_word(): assert reverse_words("Hello") == "Hello" def test_reverse_words_two_words(): assert reverse_words("Hello world") == "world Hello" def test_reverse_words_multiple_words(): as...
[ { "docstring": "Reverses the order of words in a single sentence.", "function_declaration": "def reverse_words(sentence):", "function_name": "reverse_words", "parameter_list": "(sentence)" }, { "docstring": "Reverses the order of words in each sentence in a list of sentences.", "function...
[ 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 reverse_words(sentence):\n \"\"\"\n Reverse the order of words in a single sentence.\n \n Args:\n sentence (str): A sentence containing wor...
trial_gpt4o_2
{ "original_instruction": "### Reversing the Order of Words in a Sentence\n\nYou are given a list of sentences, and you need to reverse the order of words in each sentence. Words are defined as sequences of characters separated by spaces.\n\nWrite a function `reverse_sentences(sentences)` that accepts a list of strin...
0.679171
Data_Structure_9594
C
[ "reverse_words", "reverse_sentences" ]
2
[ [ "reverse_sentences", "reverse_words" ] ]
1
[]
false
[]
false
pytest
true
[]
true
13551e08aff0827d7ed3348ba3be790a77ba6728
1701416334e0ae09d303f3af62dca6f9ba684147
v1.0
complete
Data_Structure
Data_Structure_9703_C
class RBNode: def __init__(self, value, color, parent=None, left=None, right=None): self.value = value self.color = color # 0 for black and 1 for red self.parent = parent self.left = left self.right = right def red_black_insert(root, value): """ Insert a new node with t...
class RBNode: def __init__(self, value, color, parent=None, left=None, right=None): self.value = value self.color = color # 0 for black and 1 for red self.parent = parent self.left = left self.right = right def left_rotate(root, x): y = x.right x.right = y.left ...
from solution import RBNode, red_black_insert def is_red_black_tree_valid(root): if root is None: return True, 1 if root.color == 1 and ((root.left and root.left.color == 1) or (root.right and root.right.color == 1)): return False, 0 is_left_valid, left_black_height = is_red_black_tree_va...
[]
[ 0, 0, 0, 1, 1, 0, 0, 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": "class RBNode:\n def __init__(self, value, color=1, parent=None, left=None, right=None):\n self.value = value\n self.color = color # 0 for bla...
trial_gpt4o_3
{ "original_instruction": "### Red-Black Tree Insert Validation\n\nAs a part of maintaining a large dataset, you need to ensure that the Red-Black Tree properties are never violated when inserting new elements. You are tasked with implementing a function that inserts a new value into a Red-Black tree and ensures all ...
0.42677
Data_Structure_9703
C
[ "left_rotate", "right_rotate", "insert_fixup", "red_black_insert" ]
4
[ [ "insert_fixup", "left_rotate" ], [ "insert_fixup", "right_rotate" ], [ "red_black_insert", "insert_fixup" ] ]
3
[]
false
[ "RBNode" ]
true
pytest
true
[]
true
c768f82e19059920b063575c7401ceb669f9c803
b1d650a2d90a8984bf42d3b672331f769e30c360
v1.0
complete
Data_Structure
Data_Structure_8206_C
import random def optimized_quick_sort(arr: list, simulation: bool = False) -> list: """Sort an array using an optimized version of Quick Sort with randomized pivot selection and insertion sort for small sub-arrays. >>> optimized_quick_sort([12, 4, 5, 6, 7, 3, 1, 15], True) # Output should show it...
import random def insertion_sort(arr, left, right): for i in range(left + 1, right + 1): key = arr[i] j = i - 1 while j >= left and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def partition(arr, low, high): pivot_index = random.randint(low,...
import random import pytest from solution import quick_sort def test_sorted_array(): assert quick_sort([]) == [] assert quick_sort([1]) == [1] assert quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] assert quick_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_random_array(): arr = [12, 4, 5, 6, 7,...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr, left, right):", "function_name": "insertion_sort", "parameter_list": "(arr, left, right)" }, { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "paramet...
[ 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 insertion_sort(arr, left, right):\n for i in range(left + 1, right + 1):\n key = arr[i]\n j = i - 1\n while j >= ...
trial_gpt4o_1
{ "original_instruction": "### Question: Implement an Optimized Quick Sort Algorithm\n\n**Scenario**: You are provided with a dataset consisting of numerical elements that need to be sorted. You have identified that the classical Quick Sort may not handle certain edge cases efficiently.\n\nWrite a function `optimized...
0.531811
Data_Structure_8206
C
[ "insertion_sort", "partition", "optimized_quick_sort", "quick_sort" ]
4
[ [ "optimized_quick_sort", "insertion_sort" ], [ "optimized_quick_sort", "partition" ], [ "quick_sort", "optimized_quick_sort" ] ]
3
[]
false
[]
false
pytest
true
[]
true
23bb84d3a281cbe86377f0728e57835dcfd2eb40
c07315c0b08538c9c1c8350fc7c4119e07d3a33b
v1.0
complete
Data_Structure
Data_Structure_9423_C
import random def generate_large_prime(bits: int) -> int: """Generates a large prime number with the specified number of bits using the Miller-Rabin primality test. """ def find_primitive_root(n: int) -> int: """Finds a primitive root modulo n. """ def optimized_diffie_hellman(bits: int) -> str: ...
import random def miller_rabin_pass(a, s, d, n): """Performs one iteration of the Miller-Rabin Primality Test""" a_to_power = pow(a, d, n) if a_to_power == 1: return True for i in range(s - 1): if a_to_power == n - 1: return True a_to_power = (a_to_power * a_to_power...
from solution import generate_large_prime, find_primitive_root, optimized_diffie_hellman def test_generate_large_prime(): prime = generate_large_prime(16) assert is_prime(prime) assert prime.bit_length() == 16 def test_find_primitive_root(): prime = generate_large_prime(16) primitive_root = find_p...
[ { "docstring": "Performs one iteration of the Miller-Rabin Primality Test", "function_declaration": "def miller_rabin_pass(a, s, d, n):", "function_name": "miller_rabin_pass", "parameter_list": "(a, s, d, n)" }, { "docstring": "Uses the Miller-Rabin Primality Test to check if a number is pri...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef miller_rabin_pass(a, s, d, n):\n \"\"\"Performs one iteration of the Miller-Rabin Primality Test\"\"\"\n a_to_power = pow(a, d, n)\...
trial_gpt4o_0
{ "original_instruction": "### Question: Implement an Enhanced Diffie-Hellman Key Exchange with Optimized Prime Generation\n\n#### Problem Statement:\nIn this task, you are required to optimize the Diffie-Hellman key exchange algorithm by implementing your own prime number generator using the Miller-Rabin primality t...
0.545061
Data_Structure_9423
C
[ "miller_rabin_pass", "is_prime", "generate_large_prime", "find_primitive_root", "optimized_diffie_hellman" ]
5
[ [ "find_primitive_root", "is_prime" ], [ "generate_large_prime", "is_prime" ], [ "is_prime", "miller_rabin_pass" ], [ "optimized_diffie_hellman", "find_primitive_root" ], [ "optimized_diffie_hellman", "generate_large_prime" ] ]
5
[]
false
[]
false
pytest
true
[]
true
521da887ae6e5e315d113e2642b5397a8b74b845
75bf7505a0a393ab780713823f0aef76a3e95783
v1.0
complete
Data_Structure
Data_Structure_5409_C
from typing import List def sudoku_solver(board: List[List[str]]) -> bool: """ Solves the Sudoku puzzle using depth-first search (DFS) and backtracking. Parameters: board : List[List[str]] - A 9x9 list of lists containing digits '1'-'9' and '.' for empty spaces. Returns: bool - True i...
from typing import List def is_valid(board: List[List[str]], row: int, col: int, num: str) -> bool: # Check if num is not in the current row/column/subgrid # Check row for i in range(9): if board[row][i] == num: return False # Check column for i in range(9): if board[i]...
from solution import sudoku_solver def test_sudoku_solver(): board1 = [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ...
[ { "docstring": null, "function_declaration": "def is_valid(board, row, col, num):", "function_name": "is_valid", "parameter_list": "(board, row, col, num)" }, { "docstring": null, "function_declaration": "def find_empty(board):", "function_name": "find_empty", "parameter_list": "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def sudoku_solver(board):\n def is_valid(num, row, col):\n # Check if the number is not repeated in the row, column and 3x3 subgrid\n for i i...
trial_gpt4o_2
{ "original_instruction": "### Sudoku Solver Implementation\n\n#### Context\nYou are tasked with implementing a Sudoku solver. Sudoku is a number puzzle game played on a 9x9 grid, divided into 3x3 subgrids. The objective is to fill the grid with numbers from 1 to 9 such that each row, each column, and each 3x3 subgri...
0.523554
Data_Structure_5409
C
[ "is_valid", "find_empty", "sudoku_solver" ]
3
[ [ "sudoku_solver", "find_empty" ], [ "sudoku_solver", "is_valid" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5844685f6db36e3cfecc5d4c5b3d2767e7b53d92
4a6415d2e539a563d4063f79c3e6064cf6ddace2
v1.0
complete
Data_Structure
Data_Structure_9282_C
from typing import List def insertion_sort(bucket: List[float]) -> List[float]: """ Sorts a given bucket of floating-point numbers using the Insertion Sort algorithm. """ pass def optimized_bucket_sort(arr: List[float]) -> List[float]: """ Sorts an array of floating-point numbers in the range [0, 1) u...
from typing import List def insertion_sort(bucket: List[float]) -> List[float]: for i in range(1, len(bucket)): key = bucket[i] j = i - 1 while j >= 0 and key < bucket[j]: bucket[j + 1] = bucket[j] j -= 1 bucket[j + 1] = key return bucket def optimized_b...
from solution import optimized_bucket_sort def test_bucket_sort_normal_case(): assert optimized_bucket_sort([0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12]) == [0.12, 0.17, 0.21, 0.26, 0.39, 0.72, 0.78, 0.94] def test_bucket_sort_different_case(): assert optimized_bucket_sort([0.42, 0.32, 0.97, 0.13, 0.58, 0...
[ { "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 insertion_sort(arr: List[float]) -> List[float]:\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n ...
trial_gpt4o_2
{ "original_instruction": "You are given an array of floating-point numbers in the range [0, 1). Implement a function `optimized_bucket_sort` that sorts this array using the Bucket Sort algorithm. Each bucket should be sorted using the Insertion Sort algorithm.\n\n### Expected Input and Output\n- **Input**: \n ```py...
0.638719
Data_Structure_9282
C
[ "insertion_sort", "optimized_bucket_sort" ]
2
[ [ "optimized_bucket_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5188a0c26b587e127865216b3061b1f6ada20439
7dcab94feef8c3d824ed58bddf0dd4ce8fd9d500
v1.0
complete
Data_Structure
Data_Structure_8690_C
from typing import List, Tuple, Optional def manipulate_bits(num: int, commands: List[Tuple[str, int, Optional[int]]]) -> int: """ Performs a series of bit manipulation commands on num and returns the resulting integer. Commands can be: - "get": gets the bit value at a given position. - "set":...
from typing import List, Tuple, Optional def get_bit(num: int, i: int) -> int: """ Returns the bit value at position i. """ return (num >> i) & 1 def set_bit(num: int, i: int) -> int: """ Sets the bit at position i to 1. """ return num | (1 << i) def clear_bit(num: int, i: int) -> int...
from solution import manipulate_bits def test_set_command(): assert manipulate_bits(73, [("set", 1)]) == 75 # 1001001 -> 1001011 def test_clear_command(): assert manipulate_bits(75, [("clear", 6)]) == 11 # 1001011 -> 0001011 def test_update_command(): assert manipulate_bits(11, [("update", 2, 1)]) ==...
[ { "docstring": "Returns the bit value at position i.", "function_declaration": "def get_bit(num, i):", "function_name": "get_bit", "parameter_list": "(num, i)" }, { "docstring": "Sets the bit at position i to 1.", "function_declaration": "def set_bit(num, i):", "function_name": "set_...
[ 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, Tuple, Optional\n\ndef manipulate_bits(num: int, commands: List[Tuple[str, int, Optional[int]]]) -> int:\n def get_bit(number: int...
trial_gpt4o_2
{ "original_instruction": "### Bit Manipulation Challenge\n\n**Objective**:\nWrite a function that takes a non-negative integer, a list of bit manipulation commands, and returns the resulting integer after applying all the commands sequentially.\n\n**Function Signature**:\n```python\ndef manipulate_bits(num: int, com...
0.645296
Data_Structure_8690
C
[ "get_bit", "set_bit", "clear_bit", "update_bit", "manipulate_bits" ]
5
[ [ "manipulate_bits", "clear_bit" ], [ "manipulate_bits", "set_bit" ], [ "manipulate_bits", "update_bit" ] ]
3
[]
false
[]
false
pytest
true
[]
true
99da9ca4c3c5bd6fcb15224467ec94df15f301a6
adcfc0f4bb8a70e003a135d177576d59870f6132
v1.0
complete
Data_Structure
Data_Structure_9307_C
def compute_max_flow(capacity: List[List[int]], source: int, sink: int) -> int: """ Calculate the maximum flow from source to sink in a given flow network graph using Dinic's algorithm. Args: capacity (List[List[int]]): A two-dimensional list representing the capacity of each edge in the graph. ...
from collections import deque def bfs(level, capacity, source, sink, n): visited = [False] * n queue = deque([source]) visited[source] = True level[source] = 0 while queue: node = queue.popleft() for i in range(n): if not visited[i] and capacity[node][i]: ...
def test_compute_max_flow_simple(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert compute_max_flow(capacity...
[ { "docstring": null, "function_declaration": "def bfs(level, capacity, source, sink, n):", "function_name": "bfs", "parameter_list": "(level, capacity, source, sink, n)" }, { "docstring": null, "function_declaration": "def dfs(flow, capacity, level, start, sink, n):", "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 collections import deque\nfrom typing import List\n\ndef compute_max_flow(capacity: List[List[int]], source: int, sink: int) -> int:\n n = len(capacit...
trial_gpt4o_1
{ "original_instruction": "## Maximum Flow Problem: Advanced Implementation with Edge Cases Handling\n\n### Context\nYou are a software engineer tasked with optimizing traffic flow in a city’s road network. You need to model the flow of traffic using a graph, where intersections are represented by vertices, roads by ...
0.540024
Data_Structure_9307
C
[ "bfs", "dfs", "compute_max_flow" ]
3
[ [ "compute_max_flow", "bfs" ], [ "compute_max_flow", "dfs" ] ]
2
[]
false
[]
false
pytest
false
[]
true
a74a89aded983c90ffbb507294c529b1d7cdfc86
892d42bc1c32ef2c99d2ba2e45b67db5b86c9248
v1.0
complete
Data_Structure
Data_Structure_8171_C
import random from typing import List, Tuple def is_sorted(arr: List[int]) -> bool: """ Check if the array is sorted in ascending order. """ return all(arr[i] <= arr[i+1] for i in range(len(arr)-1)) def bogo_sort_simulated(arr: List[int]) -> Tuple[List[int], int]: """ Simulate the Bogo Sort algorithm...
import random def is_sorted(arr): """ Check if the array is sorted in ascending order. """ return all(arr[i] <= arr[i+1] for i in range(len(arr)-1)) def bogo_sort_simulated(arr): """ Simulate the Bogo Sort algorithm. Return the sorted list and the number of iterations it took to sort the array...
from solution import bogo_sort_simulated def test_bogo_sort_simulated_already_sorted(): arr = [1, 2, 3, 4, 5] sorted_arr, iterations = bogo_sort_simulated(arr) assert sorted_arr == [1, 2, 3, 4, 5] assert iterations == 0 # If already sorted, no shuffle needed def test_bogo_sort_simulated_reverse_order...
[ { "docstring": "Check if the array is sorted in ascending order.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Simulate the Bogo Sort algorithm. Return the sorted list and the number of iterations it took to sort 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\n\ndef is_sorted(arr):\n \"\"\" Helper function to check if the list is sorted \"\"\"\n for i in range(len(arr) - 1):\n if arr[i] >...
trial_gpt4o_1
{ "original_instruction": "### Bogo Sort Simulation Challenge\n\nBogo Sort is a highly inefficient sorting algorithm that generates random permutations of a list until it happens to find one that is sorted. Despite its impracticality, it is a great educational tool to understand sorting and randomness.\n\n#### Task\n...
0.610141
Data_Structure_8171
C
[ "is_sorted", "bogo_sort_simulated" ]
2
[ [ "bogo_sort_simulated", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3f0885878867e980a4fd91884a1b785580bda3b3
c2ae4eebcc58da16c29a2cba8393029c414ede98
v1.0
complete
Data_Structure
Data_Structure_9781_C
from typing import List def bucket_sort(arr: List[int]) -> List[int]: """ Enhance the bucket sort algorithm by using a more efficient sorting algorithm for sorting individual buckets. >>> bucket_sort([29, 25, 3, 49, 9, 37, 21, 43]) [3, 9, 21, 25, 29, 37, 43, 49] >>> bucket_sort([]) [] >>> ...
from typing import List def quick_sort(arr: List[int]) -> List[int]: if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quick_sort(left) + middle + quick_sort(r...
from solution import bucket_sort def test_bucket_sort_normal_case(): assert bucket_sort([29, 25, 3, 49, 9, 37, 21, 43]) == [3, 9, 21, 25, 29, 37, 43, 49] def test_bucket_sort_empty_array(): assert bucket_sort([]) == [] def test_bucket_sort_single_element(): assert bucket_sort([1]) == [1] def test_bucket...
[ { "docstring": null, "function_declaration": "def quick_sort(arr):", "function_name": "quick_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def bucket_sort(arr):", "function_name": "bucket_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": "from typing import List\nimport math\n\n# Using Python's built-in Timsort which is very efficient\ndef efficient_sort(arr: List[int]) -> List[int]:\n \"\"\...
trial_gpt4o_2
{ "original_instruction": "### Bucket Sort Enhancement Challenge\n\n#### Background\nBucket sort is excellent for sorting datasets that are uniformly distributed over a range. The basic bucket sort implementation provided uses insertion sort for sorting individual buckets, which can be inefficient in some scenarios, ...
0.563176
Data_Structure_9781
C
[ "quick_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "quick_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
32d536c8e182856f69ace25e7f6b54b851e78041
08112473b81c37bf4b6021a53ec400b65532fe01
v1.0
complete
Data_Structure
Data_Structure_6882_C
def validate_markov_chain(chain): """ Validates the given Markov chain dictionary. Parameters: - chain (dict): A dictionary representing the Markov chain. Returns: - bool: True if the chain is valid, False otherwise. >>> validate_markov_chain({ ... 'A': {'A': 0.6, 'E': 0.4}, ...
import random def validate_markov_chain(chain): """ Validates the given Markov chain dictionary. Parameters: - chain (dict): A dictionary representing the Markov chain. Returns: - bool: True if the chain is valid, False otherwise. """ for state, transitions in chain.items(): ...
import pytest from solution import validate_markov_chain, generate_sequence def test_validate_markov_chain(): chain_valid = { 'A': {'A': 0.6, 'E': 0.4}, 'E': {'A': 0.7, 'E': 0.3} } chain_invalid = { 'A': {'A': 0.5, 'E': 0.4}, 'E': {'A': 0.7, 'E': 0.3} } ass...
[ { "docstring": "Validates the given Markov chain dictionary.\n\nParameters:\n- chain (dict): A dictionary representing the Markov chain.\n\nReturns:\n- bool: True if the chain is valid, False otherwise.", "function_declaration": "def validate_markov_chain(chain):", "function_name": "validate_markov_chai...
[ 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 validate_markov_chain(chain):\n \"\"\"\n Validates the given Markov chain.\n \n Parameters:\n chain (dict): A dictionary r...
trial_gpt4o_1
{ "original_instruction": "You are tasked with simulating a Markov chain using the provided Probabilistic Model implementation. Given a Markov chain represented as a dictionary and an initial state, you are to extend the current implementation to include methods for:\n\n1. **Validating the Markov Chain**: Ensure that...
0.465467
Data_Structure_6882
C
[ "validate_markov_chain", "generate_sequence", "next_state", "__choose_state" ]
4
[ [ "generate_sequence", "next_state" ], [ "next_state", "__choose_state" ] ]
2
[]
false
[]
false
pytest
true
[]
true
bab89491af9fcf7a6821c6f5bcdf0cde2004cc00
ae7fd3b672590310ec9adb38dddbd389b4fc479a
v1.0
complete
Data_Structure
Data_Structure_8477_C
def is_strongly_connected(vertex_count: int, edges: List[Tuple[int, int]]) -> bool: """Determines if a directed graph is strongly connected. Args: vertex_count (int): The number of vertices in the graph. edges (List[Tuple[int, int]]): A list of tuples where each tuple represents a directed edge fro...
from typing import List, Tuple def dfs(graph, start, visited): stack = [start] while stack: vertex = stack.pop() if not visited[vertex]: visited[vertex] = True stack.extend(graph[vertex]) def is_strongly_connected(vertex_count: int, edges: List[Tuple[int, int]]) -> bool...
from solution import is_strongly_connected def test_single_vertex(): assert is_strongly_connected(1, []) == True def test_no_edges(): assert is_strongly_connected(3, []) == False def test_simple_strongly_connected(): assert is_strongly_connected(3, [(0, 1), (1, 2), (2, 0)]) == True def test_not_strongly...
[ { "docstring": null, "function_declaration": "def dfs(graph, start, visited):", "function_name": "dfs", "parameter_list": "(graph, start, visited)" }, { "docstring": null, "function_declaration": "def is_strongly_connected(vertex_count, edges):", "function_name": "is_strongly_connect...
[ 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\n\ndef dfs(graph, start, visited):\n stack = [start]\n while stack:\n vertex = stack.pop()\n if not visited...
trial_gpt4o_0
{ "original_instruction": "Determining Strong Connectivity in a Directed Graph\n\nYou are tasked with determining if a directed graph is strongly connected. A strongly connected graph is one where there is a path between any pair of vertices in both directions. To solve this problem, you will utilize Depth-First Sear...
0.535949
Data_Structure_8477
C
[ "dfs", "is_strongly_connected" ]
2
[ [ "is_strongly_connected", "dfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1bf85a637833d003f36063a8f517b47e6bb7fe4d
d3fa706dc8526827dea1c44c4378853b258c39be
v1.0
complete
Data_Structure
Data_Structure_9454_C
from typing import Dict, Tuple, Any def preprocess_training_set(tSet: Dict[Tuple[float, float], Any]) -> Dict[Tuple[float, float], Any]: """ Normalizes the vectors in the training set by adjusting each feature to [0, 1] scale. """ pass def normalize_vector(x: Tuple[float, float], mins: np.ndarray, max...
import numpy as np def preprocess_training_set(tSet: dict) -> dict: """ Normalizes the vectors in the training set by adjusting each feature to [0, 1] scale. """ flattened_tSet = np.array(list(tSet.keys())) mins = np.min(flattened_tSet, axis=0) maxs = np.max(flattened_tSet, axis=0) nor...
from solution import preprocess_training_set, optimized_nearest_neighbor def test_preprocess_training_set(): tSet = { (1.0, 2.0): 'A', (3.0, 4.0): 'B' } normalized = preprocess_training_set(tSet) expected = { (0.0, 0.0): 'A', (1.0, 1.0): 'B' } assert normalized =...
[ { "docstring": "Normalizes the vectors in the training set by adjusting each feature to [0, 1] scale.", "function_declaration": "def preprocess_training_set(tSet):", "function_name": "preprocess_training_set", "parameter_list": "(tSet)" }, { "docstring": "Normalizes the input vector x by the...
[ 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": "import numpy as np\n\ndef normalize_vector(v):\n \"\"\"\n Normalize a vector to the range [0, 1]\n \"\"\"\n arr = np.array(v)\n min_val = np.mi...
trial_gpt4o_9
{ "original_instruction": "### Nearest Neighbor with Optimized Search\n\n#### Context\nYou are tasked with implementing an optimized version of the nearest neighbor search algorithm for a machine learning project. This implementation should be efficient and handle typical edge cases well. Your goal is to provide a fa...
0.633673
Data_Structure_9454
C
[ "preprocess_training_set", "normalize_vector", "optimized_nearest_neighbor" ]
3
[ [ "optimized_nearest_neighbor", "normalize_vector" ], [ "optimized_nearest_neighbor", "preprocess_training_set" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
8fcfc6c22d7d49c45b56d7ba6821aec456ace015
60a1ec6bff0c55151d3ed2711acdc85533ea054f
v1.0
complete
Data_Structure
Data_Structure_8716_C
def compress_data(input_file_path: str, output_file_path: str) -> None: """ Compresses the data from the input file and writes the compressed data to the output file using Huffman coding. :param input_file_path: Path to the input text file. :param output_file_path: Path to the output file where com...
import heapq import os from collections import defaultdict, Counter import struct class HuffmanNode: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def build_hu...
import os import pytest from solution import compress_data, decompress_data # Helper function to create test files def create_test_file(file_path, content): with open(file_path, 'w') as file: file.write(content) def test_huffman_compression_decompression(): input_path = 'test_input.txt' compressed...
[]
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\nfrom collections import defaultdict, Counter\nimport os\n\nclass HuffmanNode:\n def __init__(self, char=None, freq=0):\n self.char = c...
trial_gpt4o_5
{ "original_instruction": "### Huffman Coding Question\n\n#### Context\nHuffman coding is a well-known method for compressing data without losing information. The algorithm assigns shorter binary codes to more frequent characters and longer codes to less frequent ones, thus reducing the overall size of the data.\n\n#...
0.60659
Data_Structure_8716
C
[ "build_huffman_tree", "build_codes", "compress_data", "encode_huffman_tree", "decode_huffman_tree", "decode_huffman_tree_helper", "decompress_data" ]
7
[ [ "compress_data", "build_codes" ], [ "compress_data", "build_huffman_tree" ], [ "compress_data", "encode_huffman_tree" ], [ "decode_huffman_tree", "decode_huffman_tree_helper" ], [ "decompress_data", "decode_huffman_tree" ] ]
5
[]
false
[ "HuffmanNode" ]
true
pytest
true
[]
true
9e39a9a851a7bec9687e74b20851f48159f15f09
449f6696efe3b3c36b87e0232075d77298a2632c
v1.0
complete
Data_Structure
Data_Structure_9739_C
def prime_candidates(candidates: List[int], k: int) -> List[bool]: """ Determine the primality of each number in the list of candidates using a variation of the Rabin-Miller Primality Test. >>> prime_candidates([5, 7, 8, 23], 40) [True, True, False, True] >>> prime_candidates([25, 17, 35],...
import random def is_probably_prime(n, k): """ Rabin-Miller Primality Test to check if a number is probably prime. """ # Base cases if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0: return False # Decompose n-1 as d * 2^r r, d = 0, n - ...
from solution import prime_candidates def test_single_prime_low_k(): assert prime_candidates([2], 5) == [True] assert prime_candidates([3], 5) == [True] def test_single_composite_low_k(): assert prime_candidates([4], 5) == [False] assert prime_candidates([9], 5) == [False] def test_mixed_candidates()...
[ { "docstring": "Rabin-Miller Primality Test to check if a number is probably prime.", "function_declaration": "def is_probably_prime(n, k):", "function_name": "is_probably_prime", "parameter_list": "(n, k)" }, { "docstring": "Determine the primality of each number in the list of candidates u...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_prime(n, k):\n \"\"\"Use the Rabin-Miller algorithm to return True if n is probably prime, and False if it is guaranteed composite....
trial_gpt4o_6
{ "original_instruction": "### Coding Assessment: Implement a Modified Primality Test\n\nYou are tasked with implementing a variation of the Rabin-Miller Primality Test algorithm. This variation requires you to consider a list of prime candidates and return a list of results indicating whether each candidate is proba...
0.711565
Data_Structure_9739
C
[ "is_probably_prime", "prime_candidates" ]
2
[ [ "prime_candidates", "is_probably_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c373125b8827d03dbe4c28aa39036f45517e0c4f
ea508c29e21d74538b33724f3df954c0b5ed2bc8
v1.0
complete
Data_Structure
Data_Structure_8086_C
import random from typing import Tuple def generate_key(k: int, seed: int = None) -> Tuple[int, int, int]: """ Generates RSA public and private keys. Args: k (int): number of bits for the keys seed (int, optional): random seed for reproducibility Returns: Tuple[int, int, int]: (n, ...
import random from sympy import isprime, mod_inverse def generate_prime(bits, seed=None): if seed is not None: random.seed(seed) while True: p = random.getrandbits(bits) if isprime(p): return p def generate_key(k, seed=None): p = generate_prime(k // 2, seed) q = gen...
from solution import generate_key, encrypt, decrypt def test_key_generation(): n, e, d = generate_key(16, seed=42) assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) assert n > 0 assert e > 0 assert d > 0 def test_encryption_decryption(): n, e, d = generate_k...
[ { "docstring": null, "function_declaration": "def generate_prime(bits, seed=None):", "function_name": "generate_prime", "parameter_list": "(bits, seed=None)" }, { "docstring": null, "function_declaration": "def generate_key(k, seed=None):", "function_name": "generate_key", "param...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_key(k, seed=None):\n \"\"\"\n Generates an RSA key pair with k-bit primes.\n \n...
trial_gpt4o_2
{ "original_instruction": "### RSA Encryption Implementation and Analysis\n\n#### Problem Statement\n\nYou are tasked with implementing a secure messaging system using the RSA encryption algorithm. Your program will include key generation, encryption, and decryption mechanisms. You must also write tests verifying the...
0.742638
Data_Structure_8086
C
[ "generate_prime", "generate_key", "encrypt", "decrypt" ]
4
[ [ "generate_key", "generate_prime" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
307c3c28901ea18cb13720c052969f3d599cf905
a96677103b5efef1e6ee207702efb74ebf41ab57
v1.0
complete
Data_Structure
Data_Structure_9241_C
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts the input list of integers using the merge sort algorithm. Args: arr: A list of integers to sort. Returns: A new list containing the sorted integers. Examples: >>> merge_sort([5, 2, 9, 1, 5, 6]) [1,...
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts the input list of integers using the merge sort algorithm. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(...
from solution import merge_sort def test_merge_sort_with_empty_list(): assert merge_sort([]) == [] def test_merge_sort_with_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_with_multiple_elements(): assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9] def test_merge_sort_with_r...
[ { "docstring": "Sorts the input list of integers using the merge sort algorithm.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merges two sorted lists into a single sorted list.", "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": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list using the merge sort algorithm.\n :param arr: List of...
trial_gpt4o_2
{ "original_instruction": "Merge Sort Implementation\n\n#### Context\nYou have been asked to implement a sorting algorithm for a software application that processes large datasets efficiently. Given the need for consistent performance regardless of the input data and the preservation of the relative order of equivale...
0.709017
Data_Structure_9241
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0250b20ed892b54f03160507a8348c58a9175ba0
0f854bab4eb5292f967f953954d167866d01ad0d
v1.0
complete
Data_Structure
Data_Structure_8765_C
def optimized_gcd(a, b): """ Calculate the Greatest Common Divisor (GCD) of two integers `a` and `b` using bitwise operations. Inputs: a: int - first integer (not both zero) b: int - second integer (not both zero) Output: int - GCD of a and b Example: >>> optimized_g...
def optimized_gcd(a, b): """ Calculate the Greatest Common Divisor (GCD) of two integers `a` and `b` using bitwise operations. """ if a == 0: return abs(b) if b == 0: return abs(a) a, b = abs(a), abs(b) shift = count_trailing_zeros(a | b) a >>= count_trailing_ze...
from solution import optimized_gcd, optimized_lcm, count_trailing_zeros def test_optimized_gcd(): assert optimized_gcd(34, 17) == 17 assert optimized_gcd(21, 6) == 3 assert optimized_gcd(100, 10) == 10 assert optimized_gcd(0, 5) == 5 assert optimized_gcd(5, 0) == 5 assert optimized_gcd(12, 15) ...
[ { "docstring": "Calculate the Greatest Common Divisor (GCD) of two integers `a` and `b` using bitwise operations.", "function_declaration": "def optimized_gcd(a, b):", "function_name": "optimized_gcd", "parameter_list": "(a, b)" }, { "docstring": "Calculate the Least Common Multiple (LCM) of...
[ 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_gcd(a, b):\n \"\"\"\n Calculate the Greatest Common Divisor (GCD) of two integers a and b using bitwise operations.\n \"\"\"\n if a ...
trial_gpt4o_2
{ "original_instruction": "### Question: Advanced Arithmetic Operations with Bitwise Optimization\n\n#### Context\nYou are tasked with creating a mathematical utility library for arithmetic operations often needed in cryptographic applications. Handling very large integer operations efficiently and safely is critical...
0.689953
Data_Structure_8765
C
[ "optimized_gcd", "optimized_lcm", "count_trailing_zeros" ]
3
[ [ "optimized_gcd", "count_trailing_zeros" ], [ "optimized_lcm", "optimized_gcd" ] ]
2
[]
false
[]
false
pytest
true
[]
true
38b046805da657cda6d36d4e6edf2c81b334f50c
8a0edab7041a5650aaf66ba609bd1ab741457ee6
v1.0
complete
Data_Structure
Data_Structure_9750_C
import random from typing import List def bogo_sort(arr: List[int], simulation: bool = False) -> List[int]: """ Sort the array using the highly inefficient Bogo Sort algorithm. Optionally, print the array at each iteration of shuffling if simulation is set to True. Parameters: arr (List[in...
import random from typing import List def is_sorted(arr: List[int]) -> bool: """ Check if the array is sorted. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort(arr: List[int], simulation: bool = False) -> List[int]: """ So...
from solution import 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_reverse_sorted(): assert bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_bogo_sort_unsorted(): assert bogo_sort([3, 1, 2, 5, 4]) == [1, 2, 3, 4, 5] def test_...
[ { "docstring": "Check if the array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sort the array using the highly inefficient Bogo Sort algorithm. Optionally, print\nthe array at each iteration of shuffli...
[ 1, 1 ]
2
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 bogo_sort(arr: List[int], simulation: bool = False) -> List[int]:\n def is_sorted(arr):\n return all(a...
trial_gpt4o_2
{ "original_instruction": "You have been given an array of integers that you need to sort. Normally, you would use efficient algorithms like quicksort, mergesort, or heapsort. However, as a part of an educational exercise, you are required to implement Bogo Sort. Your task is to demonstrate your understanding of algo...
0.629059
Data_Structure_9750
C
[ "is_sorted", "bogo_sort" ]
2
[ [ "bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c7e7b514d7ad25b73bce75b09cf1242fcd206a0e
089029c747073337605cc2c95a4472caeb4c96cf
v1.0
complete
Data_Structure
Data_Structure_8522_C
from typing import List def invert_matrix(matrix: List[List[float]]) -> List[List[float]]: """ Invert a square matrix (n x n). The inversion involves computing the matrix of minors, cofactor matrix, adjugate, and multiplying by the reciprocal of the determinant. It is guaranteed that the matrix is in...
from typing import List def get_minor(matrix: List[List[float]], i: int, j: int) -> List[List[float]]: """ Returns the minor of the matrix after removing the i-th row and j-th column. """ return [row[:j] + row[j+1:] for k, row in enumerate(matrix) if k != i] def get_determinant(matrix: List[List[float...
from solution import invert_matrix def test_invert_matrix_example_1(): matrix = [[4, 7], [2, 6]] result = invert_matrix(matrix) expected = [[0.6, -0.7], [-0.2, 0.4]] for i in range(2): for j in range(2): assert round(result[i][j], 1) == round(expected[i][j], 1) def test_invert_matr...
[ { "docstring": "Returns the minor of the matrix after removing the i-th row and j-th column.", "function_declaration": "def get_minor(matrix, i, j):", "function_name": "get_minor", "parameter_list": "(matrix, i, j)" }, { "docstring": "Recursively computes the determinant of the matrix.", ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef get_minor(matrix: List[List[float]], i: int, j: int) -> List[List[float]]:\n \"\"\"\n Returns the minor of the matrix aft...
trial_gpt4o_0
{ "original_instruction": "### Matrix Inversion Challenge\n\nYou are tasked with writing a function to invert a square matrix (n x n). This involves computing the matrix of minors, cofactor matrix, adjugate, and finally multiplying by the reciprocal of the determinant.\n\n#### Function Signature\n```python\ndef inver...
0.584262
Data_Structure_8522
C
[ "get_minor", "get_determinant", "get_matrix_of_minors", "get_cofactor_matrix", "transpose", "invert_matrix" ]
6
[ [ "get_cofactor_matrix", "get_matrix_of_minors" ], [ "get_determinant", "get_minor" ], [ "get_matrix_of_minors", "get_determinant" ], [ "get_matrix_of_minors", "get_minor" ], [ "invert_matrix", "get_cofactor_matrix" ], [ "invert_matrix", "get_deter...
7
[]
false
[]
false
pytest
true
[]
true
657a5ddabcd439841c6d31cc6ec6f927b414d2b7
966526fd1f5f8aee4668faf75fafa93cbe99f5da
v1.0
complete
Data_Structure
Data_Structure_9228_C
from typing import List def find_maximum_flow(graph: List[List[int]]) -> int: """ Computes the maximum flow from the source node (index 0) to the sink node (index n-1) in a given flow network. The network is represented by an n*n adjacency matrix where graph[i][j] denotes the capacity of the edge from nod...
from typing import List from collections import deque def bfs(residual_graph, source, sink, parent): visited = [False] * len(residual_graph) queue = deque([source]) visited[source] = True while queue: current = queue.popleft() for idx, capacity in enumerate(residual_graph[current]): ...
from solution import find_maximum_flow def test_example_case(): graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] assert find_maximum_flow(graph) == 23 def test_single_pat...
[ { "docstring": null, "function_declaration": "def bfs(residual_graph, source, sink, parent):", "function_name": "bfs", "parameter_list": "(residual_graph, source, sink, parent)" }, { "docstring": null, "function_declaration": "def find_maximum_flow(graph):", "function_name": "find_ma...
[ 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(graph, source, sink, parent):\n visited = [False] * len(graph)\n queue = deque([source])\n visited[source] =...
trial_gpt4o_2
{ "original_instruction": "#### Context:\nYou are tasked with improving the performance of a network optimization software. One of the core functionalities is to calculate the maximum flow from a source to a sink in a network represented by an adjacency matrix.\n\n#### Problem Statement:\nWrite a function `find_maxim...
0.57018
Data_Structure_9228
C
[ "bfs", "find_maximum_flow" ]
2
[ [ "find_maximum_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ba6a5a2a825379754febaf317e3f13846bbcec78
35fe6ca4a1b2c5f05d41dc494f957b6b35804108
v1.0
complete
Data_Structure
Data_Structure_9578_C
from typing import Optional, Tuple import random def generate_key(k: int, seed: Optional[int]=None) -> Tuple[int, int, int]: """ Generates an RSA key pair. Args: k (int): Number of bits in the modulus n. seed (Optional, int): Seed for random number generation. Returns: Tuple[int, int...
import random from sympy import isprime from sympy import nextprime from math import gcd def generate_large_prime(bits): """Generates a large prime number of the specified bit length.""" while True: number = random.getrandbits(bits) number |= (1 << bits - 1) | 1 # Ensure high bit and low bit a...
import pytest from solution import generate_key, encrypt, decrypt def test_generate_key(): n, e, d = generate_key(128, seed=42) # using a small bit length for test speed assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) assert n.bit_length() >= 128 def test_encryption_...
[ { "docstring": "Generates a large prime number of the specified bit length.", "function_declaration": "def generate_large_prime(bits):", "function_name": "generate_large_prime", "parameter_list": "(bits)" }, { "docstring": "Generates the RSA key pairs.\n\nArgs:\nk (int): Number of bits in th...
[ 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": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_key(k, seed=None):\n if seed is not None:\n random.seed(seed)\n \n def g...
trial_gpt4o_9
{ "original_instruction": "You are tasked with implementing an RSA encryption key generator, encryption, and decryption mechanism in Python. Your implementation will be used to securely transmit data between two parties. The generator function should produce public and private keys for encryption and decryption.\n\n#...
0.769033
Data_Structure_9578
C
[ "generate_large_prime", "generate_key", "encrypt", "decrypt" ]
4
[ [ "generate_key", "generate_large_prime" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
8c7f637b91f502c28de49286dcf1513488ac72fb
9366e74383a920924ae69d69818c8ff3131482b3
v1.0
complete
Data_Structure
Data_Structure_9187_C
def int_to_bytes_big_endian(num: int) -> bytes: """ Convert an integer to its big-endian byte representation. >>> int_to_bytes_big_endian(4660) == b'\x12\x34' >>> int_to_bytes_big_endian(0) == b'\x00' """ def int_to_bytes_little_endian(num: int) -> bytes: """ Convert an integer to its little-endian...
def int_to_bytes_big_endian(num): """ Convert an integer to its big-endian byte representation. """ return num.to_bytes((num.bit_length() + 7) // 8 or 1, 'big') def int_to_bytes_little_endian(num): """ Convert an integer to its little-endian byte representation. """ return num.to_bytes(...
def test_int_to_bytes_big_endian_zero(): assert int_to_bytes_big_endian(0) == b'\x00' def test_int_to_bytes_big_endian_positive(): assert int_to_bytes_big_endian(4660) == b'\x12\x34' def test_int_to_bytes_little_endian_zero(): assert int_to_bytes_little_endian(0) == b'\x00' def test_int_to_bytes_little_e...
[ { "docstring": "Convert an integer to its big-endian byte representation.", "function_declaration": "def int_to_bytes_big_endian(num):", "function_name": "int_to_bytes_big_endian", "parameter_list": "(num)" }, { "docstring": "Convert an integer to its little-endian byte representation.", ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def int_to_bytes_big_endian(num: int) -> bytes:\n \"\"\"\n Convert an integer to its big-endian byte representation.\n \"\"\"\n return num.to_byte...
trial_gpt4o_1
{ "original_instruction": "### Endianness Conversion and Validation\n\n**Objective**: Write functions to convert integers to bytes (both big-endian and little-endian) and convert bytes back to integers. Additionally, implement a validation function to ensure accuracy of the conversion processes.\n\n### Specifications...
0.537011
Data_Structure_9187
C
[ "int_to_bytes_big_endian", "int_to_bytes_little_endian", "bytes_big_endian_to_int", "bytes_little_endian_to_int", "validate_conversion" ]
5
[ [ "validate_conversion", "bytes_big_endian_to_int" ], [ "validate_conversion", "bytes_little_endian_to_int" ], [ "validate_conversion", "int_to_bytes_big_endian" ], [ "validate_conversion", "int_to_bytes_little_endian" ] ]
4
[]
false
[]
false
pytest
false
[]
true
00dd2979855a4dc5ca24d61095a78380a0fe1714
4ad58deff606bbc06fb2a378b81c240651c0cd74
v1.0
complete
Data_Structure
Data_Structure_9792_C
def classify_nearest_neighbor(x: tuple, tSet: dict) -> any: """ Classifies the given point x by finding the nearest neighbor in the training set tSet using Euclidean distance metric. Parameters: x (tuple): The input vector to classify. tSet (dict): The training set where keys are tuple points...
import math def euclidean_distance(pt1, pt2): """ Calculate the Euclidean distance between two points. """ return math.sqrt(sum((a - b) ** 2 for a, b in zip(pt1, pt2))) def classify_nearest_neighbor(x: tuple, tSet: dict) -> any: """ Classifies the given point x by finding the nearest neighbor ...
from solution import classify_nearest_neighbor def test_classify_nearest_neighbor_example(): x = (1, 2) tSet = { (0, 0): 'A', (1, 1): 'B', (2, 2): 'C' } assert classify_nearest_neighbor(x, tSet) == 'B' def test_classify_nearest_neighbor_single_point(): x = (1, 2) tSet =...
[ { "docstring": "Calculate the Euclidean distance between two points.", "function_declaration": "def euclidean_distance(pt1, pt2):", "function_name": "euclidean_distance", "parameter_list": "(pt1, pt2)" }, { "docstring": "Classifies the given point x by finding the nearest neighbor in the tra...
[ 0, 0, 0, 1, 1, 0, 1, 1, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom typing import Any, Dict, Tuple\n\ndef euclidean_distance(a: Tuple[float], b: Tuple[float]) -> float:\n return math.sqrt(sum((a_i - b_i)**...
trial_gpt4o_8
{ "original_instruction": "Nearest Neighbor Classification\n\nYou are given a training dataset where each data point is represented as a key in a dictionary, and the corresponding label is the value. Implement a function that, given a new data point, returns the label of the nearest data point in the training set usi...
0.633278
Data_Structure_9792
C
[ "euclidean_distance", "classify_nearest_neighbor" ]
2
[ [ "classify_nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1c12cdf47a2e5af6ba7b929401db471751b21a01
c44e7419d9ec0c06f0bf5b16829711f1d1d8f53d
v1.0
complete
Data_Structure
Data_Structure_9731_C
from typing import List def max_flow(capacity: List[List[int]], source: int, sink: int) -> int: """ Compute the maximum possible flow from a source node to a sink node in a given network graph represented by an NxN capacity matrix. Args: capacity (List[List[int]]): A 2D list where capacity[i][j] holds...
from collections import deque def bfs(level, capacity, source, sink): queue = deque([source]) level[source] = 0 while queue: u = queue.popleft() for v in range(len(capacity)): if level[v] < 0 and capacity[u][v] > 0: level[v] = level[u] + 1 qu...
import pytest from solution import max_flow def test_example_case(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert max_flow(capaci...
[ { "docstring": null, "function_declaration": "def bfs(level, capacity, source, sink):", "function_name": "bfs", "parameter_list": "(level, capacity, source, sink)" }, { "docstring": null, "function_declaration": "def dfs(flow, capacity, current_node, sink, level, start):", "function_...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef bfs(level, capacity, source, sink, N):\n \"\"\"\n Perform BFS and return True if there is an augmenting path.\n ...
trial_gpt4o_2
{ "original_instruction": "### Context\nNetwork flow problems are fundamental in optimization and have various applications like network routing, resource allocation, and bipartite matching. The following question will test your understanding of maximum flow algorithms.\n\n### Problem Statement\n\nYou are given a net...
0.617081
Data_Structure_9731
C
[ "bfs", "dfs", "max_flow" ]
3
[ [ "max_flow", "bfs" ], [ "max_flow", "dfs" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a762ab9d22fc26cb219f8e04d95e428d96c6a7a9
150ef17f10ba1b4c150f9924ef39dae84bece070
v1.0
complete
Data_Structure
Data_Structure_10089_C
from typing import List def check_prime_sequence(lst: List[int]) -> List[bool]: """ Checks whether each number in the list is a prime number. >>> check_prime_sequence([1, 2, 3, 4, 5, 6, 23, -17, 0, 19]) [False, True, True, False, True, False, True, False, False, True] >>> check_prime_sequence([33, 34, 35, ...
from typing import List def is_prime(n: int) -> bool: if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def chec...
from solution import check_prime_sequence def test_check_prime_sequence_basic(): assert check_prime_sequence([1, 2, 3, 4, 5, 6, 23, -17, 0, 19]) == [False, True, True, False, True, False, True, False, False, True] assert check_prime_sequence([33, 34, 35, 36, 37, 38, 39]) == [False, False, False, False, True, F...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def check_prime_sequence(lst):", "function_name": "check_prime_sequence", "parameter_list": "(lst)" } ]
[ 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 is_prime(n: int) -> bool:\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if n <= 1:\n return False...
trial_gpt4o_2
{ "original_instruction": "### Prime Number Sequence Checker\n\n**Objective:**\nImplement a function that checks whether every number in a given list is a prime number. The function should return a list of Boolean values correspondingly.\n\n**Function Signature:**\n```python\ndef check_prime_sequence(lst: List[int]) ...
0.787066
Data_Structure_10089
C
[ "is_prime", "check_prime_sequence" ]
2
[ [ "check_prime_sequence", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a4bb15a286824eb5556fffa943e56cbd7ed4b6c5
446f6d9f90d4c4072510a375bab9a257fe38cfd9
v1.0
complete
Data_Structure
Data_Structure_9714_C
import heapq from typing import List def insert_to_heaps(max_heap: List[int], min_heap: List[int], value: int) -> float: """ Insert a value into the max heap and min heap, and balance the heaps to maintain the median. >>> max_heap, min_heap = [], [] >>> insert_to_heaps(max_heap, min_heap, 3) == 3 >>> i...
import heapq from typing import List def insert_to_heaps(max_heap: List[int], min_heap: List[int], value: int) -> float: if not max_heap or value <= -max_heap[0]: heapq.heappush(max_heap, -value) else: heapq.heappush(min_heap, value) if len(max_heap) > len(min_heap) + 1: heapq....
from solution import median_heap_sort, insert_to_heaps def test_median_heap_sort(): assert median_heap_sort([7, 1, 5, 3, 9, 2]) == [1, 2, 3, 5, 7, 9] def test_median_heap_sort_single_element(): assert median_heap_sort([1]) == [1] def test_median_heap_sort_two_elements(): assert median_heap_sort([2, 1]) =...
[ { "docstring": null, "function_declaration": "def insert_to_heaps(max_heap, min_heap, value):", "function_name": "insert_to_heaps", "parameter_list": "(max_heap, min_heap, value)" }, { "docstring": null, "function_declaration": "def median_heap_sort(arr):", "function_name": "median_h...
[ 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 heapq\nfrom typing import List, Tuple\n\ndef insert_to_heaps(max_heap: List[int], min_heap: List[int], value: int) -> float:\n \"\"\"\n Insert an...
trial_gpt4o_1
{ "original_instruction": "### Question: Implement Optimized Median Heap Sort\n\nYou are tasked with implementing a modified version of the Heap Sort algorithm. Instead of using only a max heap or min heap, you will use a combination of both to efficiently find the median value during the sorting process. \n\n#### Sc...
0.681133
Data_Structure_9714
C
[ "insert_to_heaps", "median_heap_sort" ]
2
[ [ "median_heap_sort", "insert_to_heaps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
97cac0a2d5285b940edb431715858955d3091df5
e00af88bc9eeff5f866b9e2139051e34ab8b1648
v1.0
complete
Data_Structure
Data_Structure_8806_C
def max_heap_sort(arr: List[int], simulation: bool=False) -> List[int]: """ Use a max heap to sort an array of integers in ascending order. If simulation is True, print the array at each step of the heapify process. >>> max_heap_sort([3, 1, 5, 2, 4]) [1, 2, 3, 4, 5] >>> max_heap_sort([3, 1...
def max_heapify(arr, n, i, iteration, simulation): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: largest = right if largest != i: arr[i], arr[largest] = arr[largest], ...
from solution import max_heap_sort, min_heap_sort def test_max_heap_sort(): assert max_heap_sort([3, 1, 5, 2, 4]) == [1, 2, 3, 4, 5] assert max_heap_sort([]) == [] assert max_heap_sort([-1, -2, -3]) == [-3, -2, -1] assert max_heap_sort([10, 20, 30, 5]) == [5, 10, 20, 30] assert max_heap_sort([1, 2,...
[ { "docstring": null, "function_declaration": "def max_heapify(arr, n, i, iteration, simulation):", "function_name": "max_heapify", "parameter_list": "(arr, n, i, iteration, simulation)" }, { "docstring": null, "function_declaration": "def max_heap_sort(arr, simulation=False):", "func...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef max_heapify(arr: List[int], n: int, i: int, simulation: bool) -> None:\n largest = i\n left = 2 * i + 1\n right = 2 * ...
trial_gpt4o_1
{ "original_instruction": "You are required to implement a sorting algorithm using a binary heap. Your task is to implement a function that uses a max heap to sort an array of integers in ascending order and another function that uses a min heap to sort an array of integers in descending order. Additionally, simulate...
0.67461
Data_Structure_8806
C
[ "max_heapify", "max_heap_sort", "min_heapify", "min_heap_sort" ]
4
[ [ "max_heap_sort", "max_heapify" ], [ "min_heap_sort", "min_heapify" ] ]
2
[]
false
[]
false
pytest
true
[]
true
bf2be9655817c585a906ae0ff830cd1f5022a741
716926ba6130fc77051c6a72c50c7d21bfbef219
v1.0
complete
Data_Structure
Data_Structure_8614_C
from typing import List, Optional def matrix_power(matrix: List[List[int]], n: int, mod: Optional[int] = None) -> List[List[int]]: """ Implement a function `matrix_power` that employs the principles of binary exponentiation to raise a given square matrix `matrix` to the power `n`. The function should return t...
def matrix_multiply(A, B, mod=None): """ Multiplies two matrices A and B. If mod is specified, performs multiplication modulo 'mod'. """ m = len(A) result = [[0] * m for _ in range(m)] for i in range(m): for j in range(m): for k in range(m): result[i][j] += A[...
import pytest from solution import matrix_power def test_matrix_power_basic(): matrix = [ [1, 1], [1, 0] ] n = 5 mod = 1000 expected_output = [ [8, 5], [5, 3] ] assert matrix_power(matrix, n, mod) == expected_output def test_matrix_power_identity(): matr...
[ { "docstring": "Multiplies two matrices A and B. If mod is specified, performs multiplication modulo 'mod'.", "function_declaration": "def matrix_multiply(A, B, mod=None):", "function_name": "matrix_multiply", "parameter_list": "(A, B, mod=None)" }, { "docstring": "Returns the identity matri...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef matrix_multiply(a: List[List[int]], b: List[List[int]], mod: int = None) -> List[List[int]]:\n m = len(a)\n result = [[0]...
trial_gpt4o_9
{ "original_instruction": "### Binary Exponentiation Function Implementation\n\n#### Task\nImplement a function `matrix_power` that employs the principles of binary exponentiation to raise a given square matrix `matrix` to the power `n`. The function should return the resulting matrix. Assume all matrices are square ...
0.547846
Data_Structure_8614
C
[ "matrix_multiply", "matrix_identity", "matrix_power" ]
3
[ [ "matrix_power", "matrix_identity" ], [ "matrix_power", "matrix_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1c506f48a1e347dac097fba8a677ec03702622ee
bf7a7ec111b9c9abd5d13163600211dcd4b7a2ca
v1.0
complete
Data_Structure
Data_Structure_10368_C
from typing import List def optimized_insertion_sort(arr: List[int]) -> List[int]: """ An optimized version of insertion sort that uses binary search to find the correct insertion position. >>> optimized_insertion_sort([29, 10, 14, 37, 13]) [10, 13, 14, 29, 37] >>> optimized_insertion_sort([5...
from typing import List def binary_search(arr: List[int], val: int, start: int, end: int) -> int: """ A helper function to perform binary search on the array. It returns the position where the value should be inserted. """ if start == end: if arr[start] > val: return start ...
from solution import optimized_insertion_sort def test_sorted_array(): assert optimized_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): assert optimized_insertion_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_random_array(): assert optimized_insertion_sort([29, 10,...
[ { "docstring": "A helper function to perform binary search on the array.\nIt returns the position where the value should be inserted.", "function_declaration": "def binary_search(arr, val, start, end):", "function_name": "binary_search", "parameter_list": "(arr, val, start, end)" }, { "docst...
[ 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 binary_search(arr, val, start, end):\n \"\"\"\n Helper function to perform binary search and find the index where the value should be inserted.\n ...
trial_gpt4o_2
{ "original_instruction": "You are tasked with implementing an optimized version of the Insertion Sort algorithm. Your task is to write a function that enhances the insertion sort by utilizing a binary search to determine the correct position of the current element. This improvement aims to reduce the number of compa...
0.660159
Data_Structure_10368
C
[ "binary_search", "optimized_insertion_sort" ]
2
[ [ "optimized_insertion_sort", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
22862def0c8eae4d7a8d6513fd56ee89208d237e
d50ef5d300ded0fd7f9ef16f0c26fe6fadfecd75
v1.0
complete
Data_Structure
Data_Structure_10781_C
def optimized_lcm(a: int, b: int) -> int: """ Computes the Least Common Multiple (LCM) of two integers a and b. Handles negative integers by treating their absolute values. If either a or b is zero, returns 0. >>> optimized_lcm(21, 14) == 42 >>> optimized_lcm(0, 15) == 0 >>> optimized_...
def gcd(a, b): """ Computes the Greatest Common Divisor (GCD) of two integers using the Euclidean algorithm. """ a, b = abs(a), abs(b) while b: a, b = b, a % b return a def optimized_lcm(a, b): """ Computes the Least Common Multiple (LCM) of two integers a and b. Handles neg...
import pytest from solution import optimized_lcm def test_lcm_positive_numbers(): assert optimized_lcm(21, 14) == 42 def test_lcm_one_zero(): assert optimized_lcm(0, 15) == 0 assert optimized_lcm(15, 0) == 0 def test_lcm_both_non_zero(): assert optimized_lcm(12, 18) == 36 def test_lcm_negative_numbe...
[ { "docstring": "Computes the Greatest Common Divisor (GCD) of two integers using the Euclidean algorithm.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Computes the Least Common Multiple (LCM) of two integers a and b.\nHandl...
[ 0, 0, 1, 1, 1, 1, 1, 1, 1 ]
7
easy
0.778
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def gcd(x, y):\n \"\"\"\n Compute the Greatest Common Divisor (GCD) of x and y using the Euclidean algorithm.\n \"\"\"\n while y != 0:\n (x...
trial_gpt4o_9
{ "original_instruction": "### Question: Optimized Least Common Multiple Calculation\n\n#### Problem Statement\nImplement an optimized function to calculate the Least Common Multiple (LCM) of two integers. Your implementation should leverage an efficient algorithm to compute the Greatest Common Divisor (GCD) as a par...
0.656861
Data_Structure_10781
C
[ "gcd", "optimized_lcm" ]
2
[ [ "optimized_lcm", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a93edac829841991cc837d84e5d20b22a3cf7715
91e65fe6d7b69fc11307b3afd5b1d325c07763c5
v1.0
complete
Data_Structure
Data_Structure_8137_C
from typing import List, Optional def cholesky_decomposition(A: List[List[float]]) -> Optional[List[List[float]]]: """ Determine whether a given matrix can be decomposed using the Cholesky decomposition. Returns the lower triangular matrix V if decomposition is possible, otherwise returns None. Ar...
from typing import List, Optional import numpy as np def is_positive_definite(matrix): """Check if the matrix is positive definite.""" try: np.linalg.cholesky(matrix) return True except np.linalg.LinAlgError: return False def cholesky_decomposition(A: List[List[float]]) -> Optional...
from solution import cholesky_decomposition def matrices_are_close(mat1, mat2, tol=1e-9): """Helper function to compare if two matrices are nearly equal.""" return all(abs(a - b) < tol for row1, row2 in zip(mat1, mat2) for a, b in zip(row1, row2)) def test_cholesky_decomposition(): A1 = [ [4, 12, ...
[ { "docstring": "Check if the matrix is positive definite.", "function_declaration": "def is_positive_definite(matrix):", "function_name": "is_positive_definite", "parameter_list": "(matrix)" }, { "docstring": "Performs Cholesky decomposition of a given matrix A if possible.\nReturns the lowe...
[ 0, 0, 0, 1, 1, 1, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Optional\n\ndef cholesky_decomposition(A: List[List[float]]) -> Optional[List[List[float]]]:\n import math\n \n n = len(A)\n...
trial_gpt4o_9
{ "original_instruction": "**Problem Statement**: Cholesky Matrix Decomposition Verification\n\nYou are provided with a matrix, and your task is to determine whether this matrix can be decomposed using the Cholesky decomposition. If it can be decomposed, you should return the lower triangular matrix \\(V\\), otherwis...
0.512315
Data_Structure_8137
C
[ "is_positive_definite", "cholesky_decomposition" ]
2
[ [ "cholesky_decomposition", "is_positive_definite" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
dbba5d67456b5878034e1e09e6ca850249e1fcbd
6ef324b946a04fce5c9d3dc920766af498a92bf1
v1.0
complete
Data_Structure
Data_Structure_9066_C
def identity_matrix(size): """ Creates and returns an identity matrix of the given size. """ return [[1 if i == j else 0 for j in range(size)] for i in range(size)] def multiply_matrices(matrix1, matrix2): """ Multiplies two square matrices and returns the result. """ size = len(matrix1...
def identity_matrix(size): """ Creates and returns an identity matrix of the given size. """ return [[1 if i == j else 0 for j in range(size)] for i in range(size)] def multiply_matrices(matrix1, matrix2): """ Multiplies two square matrices and returns the result. """ size = len(matrix1...
from solution import matrix_power def test_identity_matrix(): matrix = [[1, 2], [3, 4]] n = 0 result = matrix_power(matrix, n) expected = [[1, 0], [0, 1]] assert result == expected def test_power_of_one(): matrix = [[1, 2], [3, 4]] n = 1 result = matrix_power(matrix, n) expected = ...
[ { "docstring": "Creates and returns an identity matrix of the given size.", "function_declaration": "def identity_matrix(size):", "function_name": "identity_matrix", "parameter_list": "(size)" }, { "docstring": "Multiplies two square matrices and returns the result.", "function_declarati...
[ 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 identity_matrix(size):\n \"\"\"\n Creates and returns an identity matrix of the given size.\n \"\"\"\n return [[1 if i == j else 0 for j in ra...
trial_gpt4o_0
{ "original_instruction": "Given a square matrix and an integer \\( n \\), implement a function to compute the power of the matrix raised to \\( n \\). Use matrix multiplication and identity matrix functions provided.\n\n### Function Signature\n```python\ndef matrix_power(matrix: list, n: int) -> list:\n \"\"\"\n ...
0.515022
Data_Structure_9066
C
[ "identity_matrix", "multiply_matrices", "matrix_power" ]
3
[ [ "matrix_power", "identity_matrix" ], [ "matrix_power", "multiply_matrices" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a2f52ee3764a91e71608636bedf09b84a3ad9853
4ee35f6e1288981638edd2552874d8dbc9d45742
v1.0
complete
Data_Structure
Data_Structure_9953_C
def gcd(a: int, b: int) -> int: """ Returns the greatest common divisor of a and b using Euclid's Algorithm. Inputs: Two non-zero integers (a, b). Output: The greatest common divisor of a and b. Constraints: Handle negative inputs by absolute value. >>> gcd(34, 17) 17 >>> gcd(21, 6)...
def gcd(a, b): """ Returns the greatest common divisor of a and b using Euclid's Algorithm. """ a, b = abs(a), abs(b) while b: a, b = b, a % b return a def lcm(a, b): """ Returns the least common multiple of a and b. """ return abs(a * b) // gcd(a, b) def trailing_zero(...
from solution import gcd, lcm, trailing_zero, gcd_bit def test_gcd(): assert gcd(34, 17) == 17 assert gcd(21, 6) == 3 assert gcd(48, 18) == 6 assert gcd(-48, 18) == 6 assert gcd(48, -18) == 6 def test_lcm(): assert lcm(21, 6) == 42 assert lcm(48, 18) == 144 assert lcm(-21, 6) == 42 ...
[ { "docstring": "Returns the greatest common divisor of a and b using Euclid's Algorithm.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the least common multiple of a and b.", "function_declaration": "def lcm(a, b...
[ 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 \"\"\"\n Returns the greatest common divisor of a and b using Euclid's algorithm.\n Handles negative inputs by taki...
trial_gpt4o_1
{ "original_instruction": "### Question: Advanced Arithmetic Operations with Constraints\n\nYou are tasked with implementing several arithmetic operations on integers for a numerical library. Your implementation should not only be correct but optimized for large numbers and edge cases.\n\n#### Task\nImplement the fol...
0.797182
Data_Structure_9953
C
[ "gcd", "lcm", "trailing_zero", "gcd_bit" ]
4
[ [ "lcm", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dbdbb79958984746faee37b78d4b5d58e3d6c144
271682e7724775285df5ef5c2e45c5667880e54a
v1.0
complete
Data_Structure
Data_Structure_8772_C
from typing import List from collections import deque def maximum_flow_bfs(adjacency_matrix: List[List[int]]) -> int: """Calculate the maximum flow in a network using the Edmonds-Karp algorithm. The algorithm uses Breadth-First Search (BFS) to find the shortest augmenting path. Args: adjacency_mat...
from typing import List from collections import deque def bfs(residual_graph, source, sink, parent): visited = [False] * len(residual_graph) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() for v, capacity in enumerate(residual_graph[u]): if ...
from solution import maximum_flow_bfs def test_simple_case(): graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] assert maximum_flow_bfs(graph) == 23 def test_no_flow(): ...
[ { "docstring": null, "function_declaration": "def bfs(residual_graph, source, sink, parent):", "function_name": "bfs", "parameter_list": "(residual_graph, source, sink, parent)" }, { "docstring": null, "function_declaration": "def maximum_flow_bfs(adjacency_matrix):", "function_name"...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\nfrom typing import List\n\ndef bfs(residual_graph: List[List[int]], parent: List[int], source: int, sink: int) -> bool:\n vi...
trial_gpt4o_1
{ "original_instruction": "### Maximum Network Flow - Advanced Implementation\n\nYou are given a function `maximum_flow_dfs` which calculates the maximum flow in a network using the Ford-Fulkerson algorithm with Depth-First Search (DFS). The graph is represented by an adjacency matrix where `graph[i][j]` defines the ...
0.622492
Data_Structure_8772
C
[ "bfs", "maximum_flow_bfs" ]
2
[ [ "maximum_flow_bfs", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5e306d9ac58905295a3b05687c127758adf1ccc4
864eda080fa8ac52305649a918c88146e82b4cb2
v1.0
complete
Data_Structure
Data_Structure_9447_C
from typing import List def pancake_sort(arr: List[int]) -> List[int]: """ Sort an array using the Pancake Sort algorithm. >>> pancake_sort([3, 2, 4, 1]) [1, 2, 3, 4] >>> pancake_sort([10, 9, 8, 7]) [7, 8, 9, 10] >>> pancake_sort([5, 2, 2, 5]) [2, 2, 5, 5] """ pass
def flip(arr, k): """ This helper function reverses the order of the first k elements in the array. """ start = 0 while start < k: arr[start], arr[k] = arr[k], arr[start] start += 1 k -= 1 def pancake_sort(arr): """ This function sorts an array using the Pancake Sort...
from solution import pancake_sort def test_pancake_sort(): assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4] assert pancake_sort([10, 9, 8, 7]) == [7, 8, 9, 10] assert pancake_sort([5, 2, 2, 5]) == [2, 2, 5, 5] assert pancake_sort([1]) == [1] assert pancake_sort([-1, 0, 1]) == [-1, 0, 1] assert...
[ { "docstring": "This helper function 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": "This function sorts an array using the Pancake Sort algorithm.", "function...
[ 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 Function to reverse the first k elements of sub_arr\n \"\"\"\n start ...
trial_gpt4o_2
{ "original_instruction": "You are tasked with implementing an in-place sorting algorithm known as Pancake Sort. This algorithm sorts an array by repeatedly flipping (reversing) the unsorted portion of the array to move the largest unsorted element to its correct position. Your implementation should follow the typica...
0.779827
Data_Structure_9447
C
[ "flip", "pancake_sort" ]
2
[ [ "pancake_sort", "flip" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a4706eba1ad622a2f0ca7b1bf64e23b27f6c82a5
bea2879d0512f23297c0239b24d01a7e7bc7ef5e
v1.0
complete
Data_Structure
Data_Structure_10473_C
def is_sorted(arr): """ Helper function to check if the array is sorted in ascending order >>> is_sorted([1, 2, 3, 4]) True >>> is_sorted([4, 3, 2, 1]) False """ pass def bogo_sort_deluxe(arr, max_shuffles): """ Bogo Sort Deluxe which shuffles the array randomly until it is sorted ...
import random def is_sorted(arr): """ Helper function to check if the array is sorted in ascending order """ return all(arr[i] <= arr[i+1] for i in range(len(arr)-1)) def bogo_sort_deluxe(arr, max_shuffles): """ Bogo Sort Deluxe which shuffles the array randomly until it is sorted or the n...
from solution import bogo_sort_deluxe def test_bogo_sort_deluxe_sorted_array(): assert bogo_sort_deluxe([1, 2, 3], 5) == [1, 2, 3] def test_bogo_sort_deluxe_reverse_sorted_array(): result = bogo_sort_deluxe([3, 2, 1], 1000) assert result == [1, 2, 3] or result is None def test_bogo_sort_deluxe_with_zero_...
[ { "docstring": "Helper function to check if the array is sorted in ascending order", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Bogo Sort Deluxe which shuffles the array randomly until it is sorted\nor the number ...
[ 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 is_sorted(arr):\n \"\"\"\n Helper function to check if an array is sorted in non-decreasing order.\n \"\"\"\n for i in range(...
trial_gpt4o_2
{ "original_instruction": "### Bogo sort deluxe\n\nBogo Sort is an entertaining but impractically inefficient sorting algorithm that shuffles the elements randomly until they are sorted. Your task is to implement a modified version of Bogo Sort -- `bogo_sort_deluxe`, that adds a counter and stops after a predetermine...
0.631054
Data_Structure_10473
C
[ "is_sorted", "bogo_sort_deluxe" ]
2
[ [ "bogo_sort_deluxe", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
407f2840e4da761116cf0ca85195bb3ec2781723
ab0d027836f5e3bf96160208882908b4fcb58072
v1.0
complete
Data_Structure
Data_Structure_9438_C
import math from random import randint def is_prime(n: int) -> bool: """ Check if a given number is prime. >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(4) False >>> is_prime(29) True >>> is_prime(100) False """ pass def find_order(a: int, n: int) -> int: ...
import math from random import randint def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def fi...
from solution import is_prime, find_primitive_root, diffie_hellman_key_exchange def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(29) == True assert is_prime(100) == False def test_find_primitive_root(): assert set(find_primi...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def find_order(a, n):", "function_name": "find_order", "parameter_list": "(a, n)" }, { "docstring": null,...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom random import randint\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n...
trial_gpt4o_0
{ "original_instruction": "### Diffie-Hellman Key Exchange Implementation\n\n### Problem Statement\nYou are tasked with implementing the Diffie-Hellman key exchange process for secure communication between two parties, Alice and Bob. From the context given above, design functions using Python that perform key generat...
0.617625
Data_Structure_9438
C
[ "is_prime", "find_order", "euler_totient", "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" ]
11
[ [ "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...
10
[]
false
[]
false
pytest
true
[]
true
f65e552fc6ab327ea9d52187c97ae86cbd002691
cd85c2150d6f012689f8d7132a9199a0b652eaf9
v1.0
complete
Data_Structure
Data_Structure_8632_C
import random def miller_rabin_test(n, k): """Check if a number is prime using the Rabin-Miller primality test. Args: n (int): The number to check. k (int): Number of trials to reduce the false positive rate. Returns: bool: True if n is prime, False otherwise. """ # Implementa...
import random def miller_rabin_test(n, k): if n <= 1: return False if n <= 3: return True if n % 2 == 0: return False def power_mod(b, e, m): res = 1 b = b % m while e > 0: if e % 2 == 1: res = (res * b) % m e ...
from solution import find_primes_in_range def test_find_primes_in_range_example1(): assert find_primes_in_range(10, 50, 10) == [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] def test_find_primes_in_range_example2(): assert find_primes_in_range(1, 20, 5) == [2, 3, 5, 7, 11, 13, 17, 19] def test_find_primes_in_r...
[ { "docstring": null, "function_declaration": "def miller_rabin_test(n, k):", "function_name": "miller_rabin_test", "parameter_list": "(n, k)" }, { "docstring": null, "function_declaration": "def find_primes_in_range(low, high, k):", "function_name": "find_primes_in_range", "param...
[ 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\n\ndef is_prime(n, k):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ret...
trial_gpt4o_1
{ "original_instruction": "### Objective:\nDesign a function to efficiently compute the prime numbers in a given range using the Rabin-Miller primality test algorithm.\n\n### Problem Statement:\nWrite a function `find_primes_in_range(low, high, k)` that returns a list of all numbers between `low` and `high` inclusive...
0.609148
Data_Structure_8632
C
[ "miller_rabin_test", "find_primes_in_range" ]
2
[ [ "find_primes_in_range", "miller_rabin_test" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a7b155b3d30908047bf66056633efa8d143632ed
8915f3545a6cbd3e4b670862be60fc613c66791e
v1.0
complete
Data_Structure
Data_Structure_10793_C
def reverse_string(s: str, method: str) -> str: """ Reverse a string using the specified method. Args: s (str): The string to be reversed. method (str): The method to use for reversing the string, one of 'recursive', 'iterative', 'pythonic', 'ultra_pythonic'. Returns: str: The reversed...
def reverse_string(s: str, method: str) -> str: """ Reverse a string using the specified method. Args: s (str): The string to be reversed. method (str): The method to use for reversing the string, one of 'recursive', 'iterative', 'pythonic', 'ultra_pythonic'. Returns: str: The reve...
from solution import reverse_string def test_reverse_string_recursive(): assert reverse_string("hello", "recursive") == "olleh" assert reverse_string("a", "recursive") == "a" assert reverse_string("", "recursive") == "" def test_reverse_string_iterative(): assert reverse_string("world", "iterative") =...
[ { "docstring": "Reverse a string using the specified method.\n\nArgs:\ns (str): The string to be reversed.\nmethod (str): The method to use for reversing the string, one of 'recursive', 'iterative', 'pythonic', 'ultra_pythonic'.\n\nReturns:\nstr: The reversed string.", "function_declaration": "def reverse_s...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def reverse_string(s: str, method: str) -> str:\n \"\"\"\n Reverses the string `s` based on the specified `method`.\n \n Args:\n s (str): The s...
trial_gpt4o_2
{ "original_instruction": "**Scenario**: \n\nYou are tasked with developing a feature for a text-processing software which involves reversing strings. Your main goal is to ensure that this feature is implemented efficiently. As part of the evaluation, you should demonstrate your understanding of both recursive and it...
0.753068
Data_Structure_10793
C
[ "reverse_string", "_recursive_reverse", "_iterative_reverse" ]
3
[ [ "reverse_string", "_iterative_reverse" ], [ "reverse_string", "_recursive_reverse" ] ]
2
[]
false
[]
false
pytest
true
[]
true
123ed219eb47ca625d6c5d07e47fbf7581f72111
e39993afca1cca3b7b2b206acef2888f26fd1011
v1.0
complete
Data_Structure
Data_Structure_9883_C
def elias_gamma_encode(x: int) -> str: """ Computes the Elias Gamma encoding of a given positive integer x. >>> elias_gamma_encode(1) '1' >>> elias_gamma_encode(2) '010' >>> elias_gamma_encode(3) '011' >>> elias_gamma_encode(4) '00100' >>> elias_gamma_encode(5) '001...
def elias_gamma_encode(x: int) -> str: """ Computes the Elias Gamma encoding of a given positive integer x. """ if x <= 0: raise ValueError("Input must be a positive integer.") # Find the binary representation of x binary_representation = bin(x)[2:] # Compute the length of the ...
from solution import elias_gamma_encode, elias_delta_encode def test_elias_gamma_encode(): # Basic cases assert elias_gamma_encode(1) == "1" assert elias_gamma_encode(2) == "010" assert elias_gamma_encode(3) == "011" assert elias_gamma_encode(4) == "00100" assert elias_gamma_encode(5) == "00101...
[ { "docstring": "Computes the Elias Gamma encoding of a given positive integer x.", "function_declaration": "def elias_gamma_encode(x):", "function_name": "elias_gamma_encode", "parameter_list": "(x)" }, { "docstring": "Computes the Elias Delta encoding of a given positive integer x.", "f...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def elias_gamma_encode(x: int) -> str:\n \"\"\"\n Returns the Elias gamma encoding of a given positive integer x.\n \"\"\"\n if x <= 0:\n r...
trial_gpt4o_2
{ "original_instruction": "You are tasked with implementing two encoding schemes, Elias γ and Elias δ, which are universal coding algorithms for positive integers. These encodings are useful for compressing numbers without requiring knowledge of their upper bounds. \n\nImplement the following functions:\n\n1. `elias_...
0.558571
Data_Structure_9883
C
[ "elias_gamma_encode", "elias_delta_encode" ]
2
[ [ "elias_delta_encode", "elias_gamma_encode" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2d64bb023f1969dc83e606352387e219f4b9a90c
5888c9b531cd0ba5afed98dc50ddc2134e388cfc
v1.0
complete
Data_Structure
Data_Structure_11284_C
def matrix_exponentiation(matrix: list, power: int) -> list: """ Raise a matrix to the specified power efficiently. >>> matrix_exponentiation([[2, 3], [4, 5]], 2) [[16, 21], [28, 37]] >>> matrix_exponentiation([[1, 0], [0, 1]], 0) [[1, 0], [0, 1]] >>> matrix_exponentiation([[1, 2], [3, 4]], 3) ...
def matrix_multiply(A, B): 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] * B[k][j] return result def matrix_exponentiation(matrix, power): if power == 0: size = len(ma...
def test_matrix_exponentiation_with_zero_power(): matrix = [ [2, 3], [4, 5] ] power = 0 assert matrix_exponentiation(matrix, power) == [ [1, 0], [0, 1] ] def test_matrix_exponentiation_with_power_one(): matrix = [ [2, 3], [4, 5] ] power = ...
[ { "docstring": null, "function_declaration": "def matrix_multiply(A, B):", "function_name": "matrix_multiply", "parameter_list": "(A, B)" }, { "docstring": null, "function_declaration": "def matrix_exponentiation(matrix, power):", "function_name": "matrix_exponentiation", "parame...
[ 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_multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B.\n \"\"\"\n size = len(A)\n result = [[0] * size for _ in range(size)]\n ...
trial_gpt4o_2
{ "original_instruction": "### Question\nYou are tasked with implementing a feature for a mathematical simulation that involves frequent calculations with matrices. Specifically, you need to create a function to take a matrix and raise it to a specified power efficiently.\n\nImplement the function `matrix_exponentiat...
0.554929
Data_Structure_11284
C
[ "matrix_multiply", "matrix_exponentiation" ]
2
[ [ "matrix_exponentiation", "matrix_multiply" ] ]
1
[]
false
[]
false
pytest
false
[]
true
719b4fcb7759aa11a3557ace5356c96daffba12f
2f03922cbb54ca78935e6e9e2823f238260631cb
v1.0
complete
Data_Structure
Data_Structure_9182_C
def max_heap_sort(arr: List[int]) -> List[int]: """ Sort an array of integers in ascending order using a max-heap and print each iteration of the sorting process. >>> arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] >>> print(max_heap_sort(arr)) iteration 0: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] iteration 1: [9,...
def max_heapify(arr, n, i): """ Helper function to maintain the max-heap property. """ largest = i l = 2 * i + 1 r = 2 * i + 2 if l < n and arr[i] < arr[l]: largest = l if r < n and arr[largest] < arr[r]: largest = r if largest != i: arr[i], arr...
from solution import max_heap_sort def test_sorted_empty_list(): assert max_heap_sort([]) == [] def test_sorted_single_element(): assert max_heap_sort([10]) == [10] def test_sorted_duplicate_elements(): assert max_heap_sort([1, 1, 1, 1]) == [1, 1, 1, 1] def test_sorted_positive_numbers(): assert max...
[ { "docstring": "Helper function to maintain the max-heap property.", "function_declaration": "def max_heapify(arr, n, i):", "function_name": "max_heapify", "parameter_list": "(arr, n, i)" }, { "docstring": "Function to sort an array of integers in ascending order using a max-heap.", "fun...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def max_heapify(arr, n, i):\n \"\"\"\n Maintain the max-heap property for the subtree rooted at index i.\n \"\"\"\n largest = i # Initialize ...
trial_gpt4o_1
{ "original_instruction": "Your task is to implement a function that uses a max-heap to sort an array of integers in ascending order. You are provided with the definitions of `max_heap_sort` and `max_heapify` functions which can be used as reference. Additionally, you are required to simulate and print each iteration...
0.712638
Data_Structure_9182
C
[ "max_heapify", "max_heap_sort" ]
2
[ [ "max_heap_sort", "max_heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f3e2bc5607f4bc338825fb093825a729647138d6
bf42d3d0635f4effeeb0409290cabbc524faafb7
v1.0
complete
Data_Structure
Data_Structure_7918_C
import numpy as np from sklearn.neighbors import KDTree def enhanced_nearest_neighbor(x: tuple, tSet: dict, metric: str = "euclidean") -> any: """ Returns the label of the nearest neighbor of the input vector x according to the specified distance metric. Handles variable distance metrics and efficiently se...
import numpy as np from sklearn.neighbors import KDTree def enhanced_nearest_neighbor(x: tuple, tSet: dict, metric: str = "euclidean") -> any: """ Returns the label of the nearest neighbor of the input vector x according to the specified distance metric. """ if not tSet: return None if len...
from solution import enhanced_nearest_neighbor, build_kd_tree, kd_tree_search import numpy as np def test_enhanced_nearest_neighbor_empty_set(): tSet = {} x = (1, 1) assert enhanced_nearest_neighbor(x, tSet, metric="euclidean") is None def test_enhanced_nearest_neighbor_single_element(): tSet = {(2, 3...
[ { "docstring": "Returns the label of the nearest neighbor of the input vector x according to the specified distance metric.", "function_declaration": "def enhanced_nearest_neighbor(x, tSet, metric='euclidean'):", "function_name": "enhanced_nearest_neighbor", "parameter_list": "(x, tSet, metric='eucl...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.neighbors import KDTree\n\ndef enhanced_nearest_neighbor(x: tuple, tSet: dict, metric: str = \"euclidean\") -> any:\n \"\"...
trial_gpt4o_0
{ "original_instruction": "Enhanced Nearest Neighbor Classification\n\nYou are provided with an implementation of the nearest neighbor classification algorithm. The existing implementation computes the nearest neighbor based on Euclidean distance between vectors. Your task is to extend and optimize this implementatio...
0.64848
Data_Structure_7918
C
[ "enhanced_nearest_neighbor", "build_kd_tree", "kd_tree_search" ]
3
[ [ "enhanced_nearest_neighbor", "build_kd_tree" ], [ "enhanced_nearest_neighbor", "kd_tree_search" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
7d69ecfaaf5cce40de1a7aec5785bbe6714cdcfb
03f4cc832a562f2429e8ab955b95883491544f7a
v1.0
complete
Data_Structure
Data_Structure_9900_C
class Node: def __init__(self, val=0, next=None): self.val = val self.next = next def get_length_and_tail(node): length = 0 while node: length += 1 if node.next is None: return length, node node = node.next return length, None def intersection(h1: No...
class Node: def __init__(self, val=0, next=None): self.val = val self.next = next def get_length_and_tail(node): length = 0 while node: length += 1 if node.next is None: return length, node node = node.next return length, None def intersection(h1: No...
import pytest from solution import Node, intersection def create_intersecting_lists(): # create linked list as: # 1 -> 3 -> 5 # \ # 7 -> 9 -> 11 # / # 2 -> 4 -> 6 a1 = Node(1) b1 = Node(3) c1 = Node(5) d = Node(7) a2 = Node(2) b2 = Nod...
[]
[ 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=0, next=None):\n self.val = val\n self.next = next\n\ndef get_count_and_tail(head):\n count = 0\n ...
trial_gpt4o_1
{ "original_instruction": "You are given two singly linked lists that might intersect at some point in the list. Your task is to write a function that finds and returns the node at which the two lists intersect. If the lists do not intersect, return `None`.\n\n### Scenario\nImagine you have two sets of friends who jo...
0.573102
Data_Structure_9900
C
[ "get_length_and_tail", "intersection" ]
2
[ [ "intersection", "get_length_and_tail" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
b1c56b0ed8810e9e4fe49242ff47af32b586a71c
ed1b2c00e63b9ccc979e6204e9247305fe338ac6
v1.0
complete
Data_Structure
Data_Structure_10504_C
def digit_sum(n: int) -> int: """ Calculates the sum of the digits of a non-negative integer n. """ return sum(int(digit) for digit in str(n)) def is_magic_number(n: int) -> bool: """ Determines if a given non-negative integer is a magic number. A magic number is defined as a number that re...
def digit_sum(n): """ Calculates the sum of the digits of a non-negative integer n. """ return sum(int(digit) for digit in str(n)) def is_magic_number(n: int) -> bool: """ Determines if a given non-negative integer is a magic number. A magic number is defined as a number that reduces to 1 a...
from solution import is_magic_number def test_is_magic_number_true(): assert is_magic_number(50113) == True assert is_magic_number(1234) == True assert is_magic_number(199) == True assert is_magic_number(37) == True # 37 -> 3+7=10 -> 1+0=1 def test_is_magic_number_false(): assert is_magic_number(...
[ { "docstring": "Calculates the sum of the digits of a non-negative integer n.", "function_declaration": "def digit_sum(n):", "function_name": "digit_sum", "parameter_list": "(n)" }, { "docstring": "Determines if a given non-negative integer is a magic number.\nA magic number is defined as a ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_magic_number(n: int) -> bool:\n \"\"\"\n Determines whether the given non-negative integer n is a magic number.\n A magic number is defined su...
trial_gpt4o_1
{ "original_instruction": "### Magic Number Function Implementation\n\n**Scenario**:\nYou are developing a feature that utilizes the concept of magic numbers in a puzzle game. Players can enter any non-negative integer to check if it is classified as a magic number based on the summation of its digits.\n\nWrite a fun...
0.61736
Data_Structure_10504
C
[ "digit_sum", "is_magic_number" ]
2
[ [ "is_magic_number", "digit_sum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cfb37bf1261ab990d508f3ef7e40627083ff7d44
c8673219fb806e4703d8b9cafaca300482726335
v1.0
complete
Data_Structure
Data_Structure_9543_C
import random from typing import List def is_sorted(arr: List[int]) -> bool: """ Check if the given list is sorted in non-decreasing order.""" return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) def alternating_bogo_sort(arr: List[int]) -> List[int]: """ Sorts the list by alternating between...
import random from typing import List def is_sorted(arr: List[int]) -> bool: """ Check if the given list is sorted in non-decreasing order. """ return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) def alternating_bogo_sort(arr: List[int]) -> List[int]: """ Sorts the list by alternatin...
from solution import alternating_bogo_sort def test_alternating_bogo_sort(): # Regular case with multiple elements assert alternating_bogo_sort([3, 1, 4, 1, 5, 9]) == [1, 1, 3, 4, 5, 9] # Case with repeated elements assert alternating_bogo_sort([2, 3, 5, 2, 2]) == [2, 2, 2, 3, 5] # Single...
[ { "docstring": "Check if the given list is sorted in non-decreasing order.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts the list by alternating between shuffling and reversing until it is sorted.\nThis metho...
[ 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 alternating_bogo_sort(arr: List[int]) -> List[int]:\n def is_sorted(arr: List[int]) -> bool:\n return ...
trial_gpt4o_2
{ "original_instruction": "**Problem Statement:**\n\nYou are provided with a list of integers and your task is to sort this list using a method derived from the highly inefficient Bogo Sort for educational purposes. To challenge your understanding, you will need to implement a function `alternating_bogo_sort` which s...
0.635494
Data_Structure_9543
C
[ "is_sorted", "alternating_bogo_sort" ]
2
[ [ "alternating_bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1e168754300ed330c8d099dc256e38eb9c4a5c3e
b5290d293bf49782e0d0493bd5d57419261399bc
v1.0
complete
Data_Structure
Data_Structure_9856_C
from typing import List def multiply(matA: List[List[int]], matB: List[List[int]]) -> List[List[int]]: """ Multiplies two square matrices matA and matB. """ d = len(matA) result = [[0] * d for _ in range(d)] for i in range(d): for j in range(d): for k in range(d): ...
def multiply(matA, matB): """ Multiplies two square matrices matA and matB. """ d = len(matA) 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] += matA[i][k] * matB[k][j] return result def...
from solution import multiply, identity, matrix_exponentiation def test_multiply(): matA = [ [1, 2], [3, 4] ] matB = [ [2, 0], [1, 2] ] expected = [ [4, 4], [10, 8] ] assert multiply(matA, matB) == expected def test_identity(): expected =...
[ { "docstring": "Multiplies two square matrices matA and matB.", "function_declaration": "def multiply(matA, matB):", "function_name": "multiply", "parameter_list": "(matA, matB)" }, { "docstring": "Returns the identity matrix of dimension n x n.", "function_declaration": "def identity(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": "def multiply(matA, matB):\n \"\"\"\n Multiplies two matrices matA and matB.\n \"\"\"\n d = len(matA)\n result = [[0] * d for _ in range(d)]\n ...
trial_gpt4o_2
{ "original_instruction": "### Matrix Operations and Exponentiation\n\n**Scenario**:\n\nYou are working on a project that involves a lot of matrix operations, particularly matrix exponentiation. You are given a task to optimize the calculation of matrix powers.\n\n**Problem Statement**:\n\nImplement the function `mat...
0.540304
Data_Structure_9856
C
[ "multiply", "identity", "matrix_exponentiation" ]
3
[ [ "matrix_exponentiation", "identity" ], [ "matrix_exponentiation", "multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4a994a7692932d318f246ac2931a6332a3db2da4
6b58f9d8dead7d14e70fa63081db7fb62b2eecfc
v1.0
complete
Data_Structure
Data_Structure_9644_C
class TreeNode: def __init__(self, key: int): self.left = None self.right = None self.val = key def insert(root: TreeNode, key: int) -> TreeNode: """Insert a new node with the given key into the BST. >>> root = None >>> root = insert(root, 8) >>> root = insert(root, 3) >...
class TreeNode: def __init__(self, key: int): self.left = None self.right = None self.val = key def insert(root: TreeNode, key: int) -> TreeNode: if root is None: return TreeNode(key) else: if root.val < key: root.right = insert(root.right, key) e...
import pytest from solution import TreeNode, insert, delete, search def test_insert(): root = None root = insert(root, 8) root = insert(root, 3) root = insert(root, 10) assert root.val == 8 assert root.left.val == 3 assert root.right.val == 10 def test_delete_leaf(): root = None ro...
[]
[ 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, key: int, left=None, right=None):\n self.key = key\n self.left = left\n self.right = right\n\ndef...
trial_gpt4o_1
{ "original_instruction": "### Scenario\nYou are building a search feature for a library system. The system maintains a dynamic set of books, allowing for insertions, deletions, and lookups of book records by their unique identifiers (ID). \n\n### Task\nImplement a Binary Search Tree (BST) to manage the library’s boo...
0.55401
Data_Structure_9644
C
[ "insert", "minValueNode", "delete", "search" ]
4
[ [ "delete", "minValueNode" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
0c7647c7a3cf82597d1322a649c5e05d2973b27f
9120f048038b943750e6daf774f5049ef208541a
v1.0
complete
Data_Structure
Data_Structure_11251_C
from typing import List def is_prime(n: int) -> bool: """ Determines if a number is a prime number. """ 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: ...
from typing import List def is_prime(n: int) -> bool: """ Determines if a number is a prime number. """ 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: ...
from solution import filter_primes def test_filter_primes_basic(): assert filter_primes([10, 15, 3, 7, 23, 30]) == [3, 7, 23] def test_filter_primes_empty_list(): assert filter_primes([]) == [] def test_filter_primes_no_primes(): assert filter_primes([4, 6, 8, 12, 14]) == [] def test_filter_primes_a...
[ { "docstring": "Determines if a number is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Filters out the prime numbers from the list of integers.", "function_declaration": "def filter_primes(numbers):"...
[ 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 is_prime(n: int) -> bool:\n \"\"\"\n Helper function to determine if a given number n is a prime number.\n \"\"\"\n ...
trial_gpt4o_1
{ "original_instruction": "### Prime Number Sequence Check\n\nGiven a list of integers, implement a function that returns a new list containing only the prime numbers from the original list.\n\n## Function Signature\n```python\ndef filter_primes(numbers: List[int]) -> List[int]:\n pass\n```\n\n### Input\n- A list ...
0.821381
Data_Structure_11251
C
[ "is_prime", "filter_primes" ]
2
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e287b2c35e4c06ea283c810192b0dcb2ea08d002
07f967393b352792f699bb1365e65d74b9963557
v1.0
complete
Data_Structure
Data_Structure_8227_C
class RBNode: def __init__(self, val, color): self.val = val self.color = color # 1 -> Red, 0 -> Black self.left = None self.right = None self.parent = None class RBTree: def __init__(self): self.nil = RBNode(0, 0) # Sentinel node (used for leaves) sel...
class RBNode: def __init__(self, val, color): self.val = val self.color = color # 1 -> Red, 0 -> Black self.left = None self.right = None self.parent = None class RBTree: def __init__(self): self.nil = RBNode(0, 0) # Sentinel node (used for leaves) sel...
import pytest from solution import RBTree, RBNode, successor, predecessor @pytest.fixture def rb_tree(): rb = RBTree() nodes = [20, 10, 30, 5, 15, 25, 35] node_map = {} for val in nodes: node = RBNode(val, 1) node_map[val] = node rb.insert(node) return rb, node_map def test...
[]
[ 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": "class RBNode:\n def __init__(self, val, color, left=None, right=None, parent=None):\n self.val = val\n self.color = color # 1 for Red, 0 for...
trial_gpt4o_2
{ "original_instruction": "### Question\nGiven a Red-Black Tree implementation in Python, your task is to extend this tree to efficiently handle the following operations:\n\n1. **Successor**: Find the in-order successor of a given node in the Red-Black Tree.\n2. **Predecessor**: Find the in-order predecessor of a giv...
0.44992
Data_Structure_8227
C
[ "tree_minimum", "tree_maximum", "successor", "predecessor" ]
4
[ [ "predecessor", "tree_maximum" ], [ "successor", "tree_minimum" ] ]
2
[]
false
[ "RBNode", "RBTree" ]
true
pytest
true
[]
true
4223a10e520cc8e9562aeb3a2ba08396e5031e31
9925fa513f03c6783dca82cdb3291656dbef46b4
v1.0
complete
Data_Structure
Data_Structure_10802_C
from typing import List, Dict def find_phrases(text: str, phrases: List[str]) -> Dict[str, List[int]]: """ Find the occurrences of each phrase in the text using the KMP algorithm. >>> find_phrases("abracadabra", ["abra", "cad"]) {"abra": [0, 7], "cad": [4]} >>> find_phrases("abababab", ["ab",...
from typing import List, Dict def knuth_morris_pratt(text: str, pattern: str) -> List[int]: """ KMP algorithm to find all occurrences of the pattern in the text. """ n, m = len(text), len(pattern) lps = [0] * m j = 0 # index for pattern occurrences = [] # Preprocess the pattern - crea...
from solution import find_phrases def test_find_phrases_single_occurrence(): text = "abracadabra" phrases = ["abra", "cad"] expected = {"abra": [0, 7], "cad": [4]} assert find_phrases(text, phrases) == expected def test_find_phrases_multiple_occurrences(): text = "abababab" phrases = ["ab", "a...
[ { "docstring": "KMP algorithm to find all occurrences of the pattern in the text.", "function_declaration": "def knuth_morris_pratt(text, pattern):", "function_name": "knuth_morris_pratt", "parameter_list": "(text, pattern)" }, { "docstring": "Find occurrences of each phrase in the text usin...
[ 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, Dict\n\ndef knuth_morris_pratt(text: str, pattern: str) -> List[int]:\n \"\"\"\n KMP algorithm to find all occurrences of the p...
trial_gpt4o_0
{ "original_instruction": "**Context**: A large digital library maintains vast collections of e-books and articles. For efficient content retrieval and plagiarism detection, the library needs an optimized text search feature that can quickly locate instances of specific phrases within large bodies of text.\n\n**Task*...
0.61596
Data_Structure_10802
C
[ "knuth_morris_pratt", "find_phrases" ]
2
[ [ "find_phrases", "knuth_morris_pratt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c4e192c0bd19ac2ba8040b46b565a05aa90c3434
20c2b57e8fbea95de1e9966378f2c7a9cf45ec2c
v1.0
complete
Data_Structure
Data_Structure_11294_C
def matrix_chain_order(array): """ Calculate the minimum number of multiplications needed to multiply the chain of matrices optimally. :param array: List[int] - An array where each element represents the dimension of matrices. :return: Tuple(List[List[int]], List[List[int]]) - A tuple containing tw...
def matrix_chain_order(array): n = len(array) - 1 # Number of matrices # Initialize the cost matrix cost = [[float('inf')] * n for _ in range(n)] # Initialize the solution matrix for optimal split positions solution = [[0] * n for _ in range(n)] # A single matrix multiplication cost is zer...
from solution import matrix_chain_order, get_optimal_order def test_matrix_chain_order_base_case(): array = [10, 20] cost, solution = matrix_chain_order(array) assert cost == [[0]] assert solution == [[0]] def test_matrix_chain_order_simple_case(): array = [10, 20, 30] cost, solution = matrix_...
[ { "docstring": null, "function_declaration": "def matrix_chain_order(array):", "function_name": "matrix_chain_order", "parameter_list": "(array)" }, { "docstring": null, "function_declaration": "def print_optimal_parenthesization(solution, i, j):", "function_name": "print_optimal_par...
[ 0, 0, 0, 1, 0, 0, 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 matrix_chain_order(array):\n \"\"\"\n :param array: List[int] - An array where each element represents the dimension of matrices.\n :return: Tupl...
trial_gpt4o_6
{ "original_instruction": "You are given an array of integers where each integer represents the size of matrices such that the ith matrix's dimension is array[i-1] x array[i]. Your task is to implement a function that calculates the minimum number of multiplications needed to multiply the chain of matrices optimally....
0.490891
Data_Structure_11294
C
[ "matrix_chain_order", "print_optimal_parenthesization", "get_optimal_order" ]
3
[ [ "get_optimal_order", "matrix_chain_order" ], [ "get_optimal_order", "print_optimal_parenthesization" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c66ef6809c3d317338c1ce5e0faa86cb360aea40
30f348978f2650a8e7142e578b9877f5ab88ce0e
v1.0
complete
Data_Structure
Data_Structure_9634_C
from sympy import isprime, mod_inverse def generate_key(k, seed=None): """ Generate RSA keys. Arguments: k (int): The number of bits in the modulus n. seed (int, optional): Seed for random number generator. Defaults to None. Returns: Tuple[int, int, int]: A tuple (n, e, d) represen...
import random from sympy import isprime, mod_inverse def generate_prime(bits): while True: p = random.getrandbits(bits) if isprime(p): return p def generate_key(k, seed=None): if seed is not None: random.seed(seed) p = generate_prime(k // 2) q = generate_prime(...
from solution import generate_key, encrypt, decrypt def test_rsa_encryption_decryption(): (n, e, d) = generate_key(32, seed=42) # small key size for test data = 42 encrypted = encrypt(data, e, n) decrypted = decrypt(encrypted, d, n) assert decrypted == data def test_rsa_encryption_decryption_with...
[ { "docstring": null, "function_declaration": "def generate_prime(bits):", "function_name": "generate_prime", "parameter_list": "(bits)" }, { "docstring": null, "function_declaration": "def generate_key(k, seed=None):", "function_name": "generate_key", "parameter_list": "(k, seed=...
[ 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 math import gcd\n\ndef generate_key(k, seed=None):\n if seed is not None:\n random.seed(seed)\n \n def is_prime(n):\n ...
trial_gpt4o_1
{ "original_instruction": "### Task:\nWrite a Python program to:\n1. Generate RSA keys using the provided RSA key generation algorithm.\n2. Encrypt and decrypt a given piece of data using the generated keys.\n\n### Requirements:\n1. Implement a function `generate_key(k, seed=None)` to generate RSA keys.\n2. Implement...
0.668801
Data_Structure_9634
C
[ "generate_prime", "generate_key", "encrypt", "decrypt" ]
4
[ [ "generate_key", "generate_prime" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
6c714919ecea24f7eb8a356693fd645fba0f4fa7
ff82fa04c62827c7e5af209669063a04d446a5ce
v1.0
complete
Data_Structure
Data_Structure_11577_C
from typing import List def library_sort(book_ids: List[int]) -> List[int]: """ Sort a given list of book IDs using the Radix Sort algorithm. >>> library_sort([3, 1, 2]) [1, 2, 3] >>> library_sort([432, 432, 432, 432]) [432, 432, 432, 432] >>> library_sort([170, 45, 75, 90, 802, 24, 2, 66]...
from typing import List def counting_sort_for_radix(arr, exp): n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = arr[i] // exp count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] i = n - 1 while i >= 0: index ...
from solution import library_sort def test_library_sort_with_small_list(): assert library_sort([3, 1, 2]) == [1, 2, 3] def test_library_sort_with_identical_elements(): assert library_sort([432, 432, 432, 432]) == [432, 432, 432, 432] def test_library_sort_with_example_list(): assert library_sort([170, 45...
[ { "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 library_sort(book_ids):", "function_name": "library_sort", "param...
[ 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 library_sort(book_ids: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of non-negative integers using Radix Sort.\n \...
trial_gpt4o_2
{ "original_instruction": "### Scenario\nYou are working on a library management system and need an efficient way to organize books based on their unique IDs, which are large non-negative integers. Since the volume of books is immense, a high-performance sorting algorithm is required that can handle large datasets ef...
0.638642
Data_Structure_11577
C
[ "counting_sort_for_radix", "library_sort" ]
2
[ [ "library_sort", "counting_sort_for_radix" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9299e0ad17d406fecdf3a95654896f68af2df264
a62ae7cca2078575a0ef9ec65a8d7784635ea134
v1.0
complete
Data_Structure
Data_Structure_11556_C
from typing import List def invert_matrix(m: List[List[float]]) -> List[List[float]]: """ Invert a given n x n matrix. >>> invert_matrix([ ... [4, 7], ... [2, 6] ... ]) [[0.6, -0.7], [-0.2, 0.4]] >>> invert_matrix([ ... [1, 2, 3], ... [4, 5, 6] ... ]) [[-1]...
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): minor = [[matrix[i][j] for j in range(n) if j != c] for i i...
from solution import invert_matrix def test_invert_2x2_matrix(): matrix = [ [4, 7], [2, 6] ] expected_result = [ [0.6, -0.7], [-0.2, 0.4] ] assert invert_matrix(matrix) == expected_result def test_invert_3x3_matrix(): matrix = [ [1, 2, 3], [0, 1,...
[ { "docstring": null, "function_declaration": "def determinant(matrix, n):", "function_name": "determinant", "parameter_list": "(matrix, n)" }, { "docstring": null, "function_declaration": "def get_matrix_of_minors(matrix, n):", "function_name": "get_matrix_of_minors", "parameter_...
[ 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 get_matrix_minor(matrix, i, j):\n return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]\n\ndef get_matrix_dete...
trial_gpt4o_2
{ "original_instruction": "### Matrix Inversion Problem\n\n#### Context\nIn linear algebra, matrix inversion is a crucial operation for solving systems of linear equations, computing pseudoinverses, and performing various transformations. You are required to implement a function that takes an invertible \\( n \\times...
0.585186
Data_Structure_11556
C
[ "determinant", "get_matrix_of_minors", "get_cofactor_matrix", "transpose", "invert_matrix" ]
5
[ [ "get_cofactor_matrix", "get_matrix_of_minors" ], [ "get_matrix_of_minors", "determinant" ], [ "invert_matrix", "determinant" ], [ "invert_matrix", "get_cofactor_matrix" ], [ "invert_matrix", "transpose" ] ]
5
[]
false
[]
false
pytest
true
[]
true
8e0ec1b14841073999c7a812f8854fd0a0c1a7a2
bb601c2583acb66501199e0f8fbc7a39e3c4f0fe
v1.0
complete
Data_Structure
Data_Structure_11361_C
def gcd_bit(a: int, b: int) -> int: """ Compute the greatest common divisor (GCD) of two positive integers using bitwise operations. >>> gcd_bit(8, 12) 4 >>> gcd_bit(14, 21) 7 >>> gcd_bit(101, 103) 1 >>> gcd_bit(18, 24) 6 >>> gcd_bit(0, 10) 10 >>> gcd_bit(1, 1) ...
def gcd_bit(a: int, b: int) -> int: """ Compute the greatest common divisor (GCD) of a and b using bitwise operations. """ if a == b: return a if a == 0: return b if b == 0: return a # Both a and b are even if (~a & 1) and (~b & 1): return gcd_bit(a >> 1,...
from solution import gcd_bit, lcm_using_gcd_bit def test_gcd_bit(): assert gcd_bit(8, 12) == 4 assert gcd_bit(14, 21) == 7 assert gcd_bit(101, 103) == 1 assert gcd_bit(18, 24) == 6 assert gcd_bit(56, 98) == 14 assert gcd_bit(1, 1) == 1 assert gcd_bit(1, 10) == 1 assert gcd_bit(0, 10) ==...
[ { "docstring": "Compute the greatest common divisor (GCD) of a and b using bitwise operations.", "function_declaration": "def gcd_bit(a, b):", "function_name": "gcd_bit", "parameter_list": "(a, b)" }, { "docstring": "Compute the least common multiple (LCM) of a and b using their GCD.", "...
[ 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_bit(a: int, b: int) -> int:\n \"\"\"\n Compute the greatest common divisor (GCD) of a and b using bitwise operations.\n \"\"\"\n if a == b...
trial_gpt4o_0
{ "original_instruction": "### Question\nYou are given a set of two positive integers and need to determine both their Greatest Common Divisor (GCD) and their Least Common Multiple (LCM). The catch is to implement the GCD using bitwise operations, as it can be faster for large integers. For this task:\n\n#### Functio...
0.784078
Data_Structure_11361
C
[ "gcd_bit", "lcm_using_gcd_bit" ]
2
[ [ "lcm_using_gcd_bit", "gcd_bit" ] ]
1
[]
false
[]
false
pytest
true
[]
true
92399810f912f2b37740227f483d56c6d8f901f2
e16bb3a855e8533a650621c3899e070a20574cfd
v1.0
complete
Data_Structure
Data_Structure_10649_C
def advanced_invert_matrix(matrix: List[List[float]]) -> List[List[float]]: """ This function inverts a given n x n matrix if it is invertible. If the matrix is not square, it returns [[-1]]. If the matrix is singular, it returns [[-2]]. Optimize Determination Calculation: - Implement LU decomp...
from typing import List import numpy as np def is_square_matrix(matrix: List[List[float]]) -> bool: return all(len(row) == len(matrix) for row in matrix) def lu_decomposition(matrix: List[List[float]]) -> (List[List[float]], List[List[float]], List[int]): n = len(matrix) L = [[0.0] * n for _ in range(n)] ...
from solution import advanced_invert_matrix import numpy as np def test_square_matrix(): non_square_matrix = [ [1, 2, 3], [4, 5, 6] ] assert advanced_invert_matrix(non_square_matrix) == [[-1]] def test_singular_matrix(): singular_matrix = [ [1, 2], [2, 4] ] asse...
[ { "docstring": null, "function_declaration": "def is_square_matrix(matrix):", "function_name": "is_square_matrix", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def lu_decomposition(matrix):", "function_name": "lu_decomposition", "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 lu_decomposition(matrix: List[List[float]]):\n n = len(matrix)\n L = [[0.0] * n for _ in range(n)]\n U = [[0.0] * n fo...
trial_gpt4o_4
{ "original_instruction": "### Problem Description\n\nYou have been provided with the algorithm for inverting an n x n matrix. Your task is to extend this functionality by implementing a function that can handle special cases more efficiently and handle larger matrices with an optimized determinant calculation.\n\n##...
0.502451
Data_Structure_10649
C
[ "is_square_matrix", "lu_decomposition", "determinant", "advanced_invert_matrix" ]
4
[ [ "advanced_invert_matrix", "determinant" ], [ "advanced_invert_matrix", "is_square_matrix" ], [ "determinant", "is_square_matrix" ], [ "determinant", "lu_decomposition" ] ]
4
[]
false
[]
false
pytest
true
[ "numpy" ]
false
2d04cd1d7c2d418cac0eb43e433163d02d394922
be36740079f6fa64c5bb1d430916287ad5556433
v1.0
complete
Data_Structure
Data_Structure_11339_C
def invert_matrix(m): """ Inverts a given n x n matrix. The matrix inversion follows these steps: 1. Calculate the Matrix of Minors. 2. Create the Matrix of Cofactors by applying a checkerboard pattern of signs. 3. Adjugate the Matrix by transposing it. 4. Multiply by the Reciprocal of the Dete...
def determinant(matrix): """ Recursively calculates the determinant of a square 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)): minor = get...
from solution import invert_matrix def test_invert_matrix_2x2(): assert invert_matrix([[4, 7], [2, 6]]) == [[0.6, -0.7], [-0.2, 0.4]] def test_invert_matrix_3x3(): assert invert_matrix([[1, 2, 3], [0, 1, 4], [5, 6, 0]]) == [[-24.0, 18.0, 5.0], [20.0, -15.0, -4.0], [-5.0, 4.0, 1.0]] def test_invert_matrix_sin...
[ { "docstring": "Recursively calculates the determinant of a square matrix ", "function_declaration": "def determinant(matrix):", "function_name": "determinant", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def get_minor(matrix, i, j):", "function_name...
[ 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 invert_matrix(m):\n \"\"\"\n Inverts a given square matrix m using the method described in the prompt.\n \"\"\"\n def get_matrix_minor(m, i, j...
trial_gpt4o_2
{ "original_instruction": "### Matrix Inversion Coding Challenge\n\n#### Objective\nImplement a function `invert_matrix(m)` that inverts a given n x n matrix.\n\n#### Description\nGiven an n x n matrix represented by a list of lists, write a Python function `invert_matrix(m)` that returns the inverted matrix. The mat...
0.549097
Data_Structure_11339
C
[ "determinant", "get_minor", "matrix_of_minors", "matrix_of_cofactors", "transpose", "invert_matrix" ]
6
[ [ "determinant", "get_minor" ], [ "invert_matrix", "determinant" ], [ "invert_matrix", "matrix_of_cofactors" ], [ "invert_matrix", "transpose" ], [ "matrix_of_cofactors", "matrix_of_minors" ], [ "matrix_of_minors", "determinant" ], [ "matri...
7
[]
false
[]
false
pytest
true
[]
true
3f4b551bf11d1a59619e1ca0d02a7173c424da1e
38b8ccddea8412027231f6342907774dc36d4252
v1.0
complete
Data_Structure
Data_Structure_11045_C
def elias_gamma(x: int) -> str: """ Implement the Elias Gamma encoding algorithm for a given positive integer. >>> elias_gamma(1) "1" >>> elias_gamma(2) "010" >>> elias_gamma(3) "011" >>> elias_gamma(4) "00100" >>> elias_gamma(5) "00101" >>> elias_gamma(6) "00110" ...
import math def elias_gamma(x: int) -> str: if x <= 0: raise ValueError("Input must be a positive integer.") if x == 1: # Special case for 1 return "1" N = int(math.log2(x)) # Unary part (1 + floor(log2(x))) unary_part = '0' * N + '1' # Binary part (x - 2^fl...
def test_elias_gamma(): assert elias_gamma(1) == "1" assert elias_gamma(2) == "010" assert elias_gamma(3) == "011" assert elias_gamma(4) == "00100" assert elias_gamma(5) == "00101" assert elias_gamma(6) == "00110" assert elias_gamma(7) == "00111" assert elias_gamma(8) == "0001000" as...
[ { "docstring": null, "function_declaration": "def elias_gamma(x):", "function_name": "elias_gamma", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def elias_delta(x):", "function_name": "elias_delta", "parameter_list": "(x)" } ]
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef elias_gamma(x: int) -> str:\n \"\"\"\n Returns the Elias Gamma encoded string of a positive integer x.\n x should be >= 1.\n \"...
trial_gpt4o_8
{ "original_instruction": "### Elias Gamma and Delta Encoding Algorithms\n\n#### Problem Statement\n\nYou are tasked with implementing two encoding algorithms for compressing positive integers: Elias Gamma encoding and Elias Delta encoding.\n\nEach encoded value must follow specific rules:\n1. **Elias Gamma Encoding*...
0.542077
Data_Structure_11045
C
[ "elias_gamma", "elias_delta" ]
2
[ [ "elias_delta", "elias_gamma" ] ]
1
[]
false
[]
false
pytest
false
[]
true
dd80d4d20602a6d8e4772e8e89f9ff07cfd5e002
a5ce11226695ead7c63bb48e4a638410ddfa67d5
v1.0
complete
Data_Structure
Data_Structure_11589_C
def extended_gcd(a: int, b: int) -> (int, int, int): """Apply the Extended Euclidean Algorithm to find coefficients that satisfy Bézout's identity. Args: - a (int): First integer. - b (int): Second integer. Returns: - (tuple): A tuple (s, t, g) where s and t are the Bézout coefficients and ...
def extended_gcd(a: int, b: int) -> (int, int, int): """ Applies the Extended Euclidean Algorithm to find the coefficients x and y such that: a*x + b*y = gcd(a, b) Returns a tuple (x, y, gcd). """ if b == 0: return (1, 0, a) else: x1, y1, gcd = extended_gcd(b, a % b) ...
from solution import extended_gcd, modular_inverse def test_extended_gcd_basic(): s, t, gcd = extended_gcd(30, 20) assert gcd == 10 assert s * 30 + t * 20 == gcd def test_extended_gcd_coprime(): s, t, gcd = extended_gcd(35, 64) assert gcd == 1 assert s * 35 + t * 64 == gcd def test_extended_g...
[ { "docstring": "Applies the Extended Euclidean Algorithm to find the coefficients x and y such that:\na*x + b*y = gcd(a, b)\n\nReturns a tuple (x, y, gcd).", "function_declaration": "def extended_gcd(a, b):", "function_name": "extended_gcd", "parameter_list": "(a, b)" }, { "docstring": "Find...
[ 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 extended_gcd(a: int, b: int) -> (int, int, int):\n \"\"\"\n Return a tuple (s, t, g), such that\n s * a + t * b = g\n where g is the greatest ...
trial_gpt4o_2
{ "original_instruction": "### Coding Problem: Extended Euclidean Algorithm and Modular Arithmetic Solver\n\n#### Objective:\nYour task is to write a Python function that takes two integers and returns their GCD, as well as coefficients that satisfy Bézout's identity. Additionally, you will implement a function that ...
0.632183
Data_Structure_11589
C
[ "extended_gcd", "modular_inverse" ]
2
[ [ "modular_inverse", "extended_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c5e161a0b79cff75450223130a6e199467966592
8bfe3bfa6062ac0f6cf9db1cb74c2f57e9b16e7c
v1.0
complete
Data_Structure
Data_Structure_10631_C
from typing import Tuple def generate_key(k: int, seed: int = None) -> Tuple[int, int, int]: """Generates and returns RSA keys. Args: k (int): The number of bits in n. Typically 1024 or 2048. seed (int or None): Optional seed for random number generation. Returns: Tuple[in...
import random from typing import Tuple from sympy import isprime, mod_inverse def generate_prime(bits: int, seed = None) -> int: if seed is not None: random.seed(seed) while True: num = random.getrandbits(bits) if isprime(num): return num def generate_key(k: int, seed: int ...
from solution import generate_key, encrypt, decrypt def test_generate_key(): n, e, d = generate_key(16, seed=42) 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(): k = 32 seed = 42 dat...
[ { "docstring": null, "function_declaration": "def generate_prime(bits, seed=None):", "function_name": "generate_prime", "parameter_list": "(bits, seed=None)" }, { "docstring": null, "function_declaration": "def generate_key(k, seed=None):", "function_name": "generate_key", "param...
[ 1, 0, 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 Tuple\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime(bits: int, seed = None) -> int:\n if seed is not None...
trial_gpt4o_0
{ "original_instruction": "RSA Encryption/Decryption System\n\n#### Context\nYou have been tasked to design a secure communication module that uses the RSA encryption algorithm to protect data being transmitted between clients and a server. To achieve this, you need to implement functions to generate RSA keys, encryp...
0.779023
Data_Structure_10631
C
[ "generate_prime", "generate_key", "encrypt", "decrypt" ]
4
[ [ "generate_key", "generate_prime" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
5bb08d4725557188dae87ea9944d0a6a8c68ff86
7b558c6497f73c2d453811d8dc76092e8c6c1e76
v1.0
complete
Data_Structure
Data_Structure_11410_C
from typing import List def binary_search(arr: List[int], val: int, start: int, end: int) -> int: """ Binary search helper function to find the index where val should be inserted. :param arr: List of sorted elements :param val: Element to be inserted :param start: Starting index for the search ...
from typing import List def binary_search(arr: List[int], val: int, start: int, end: int) -> int: """ Binary search helper function to find the index where val should be inserted. :param arr: List of sorted elements :param val: Element to be inserted :param start: Starting index for the search ...
from solution import insertion_sort_binary def test_insertion_sort_binary_sorted(): assert insertion_sort_binary([1, 2, 3, 4, 5, 6]) == [1, 2, 3, 4, 5, 6] def test_insertion_sort_binary_reverse(): assert insertion_sort_binary([6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6] def test_insertion_sort_binary_unsorted()...
[ { "docstring": "Binary search helper function to find the index where val should be inserted.\n:param arr: List of sorted elements\n:param val: Element to be inserted\n:param start: Starting index for the search\n:param end: Ending index for the search\n:return: The index where the val should be inserted", ...
[ 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_binary(arr: List[int]) -> List[int]:\n def binary_search(sub_array, val):\n lo, hi = 0, len(sub_array)...
trial_gpt4o_2
{ "original_instruction": "### Question: Implement Enhanced Insertion Sort using Binary Search\n\n**Context**:\nImagine you are tasked with implementing an optimized version of the Insertion Sort algorithm that leverages binary search to determine the location where the next element should be inserted. This approach ...
0.657549
Data_Structure_11410
C
[ "binary_search", "insertion_sort_binary" ]
2
[ [ "insertion_sort_binary", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
50752b4311a473b0c0bb3ebef411fd6a0e7cb2b1
12ce0a824aa185a051c0b90e46ea6eeb09613802
v1.0
complete
Data_Structure
Data_Structure_11922_C
def optimized_quick_sort(arr, threshold=10): """ Sorts a list of integers using an optimized Quick Sort algorithm. This implementation uses the median-of-three method for pivot selection and switches to Insertion Sort for partitions smaller than the given threshold. Args: arr (List[int]): The l...
def insertion_sort(arr, left, right): for i in range(left + 1, right + 1): key = arr[i] j = i - 1 while j >= left and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def median_of_three(arr, left, right): mid = (left + right) // 2 if arr[lef...
from solution import optimized_quick_sort def test_optimized_quick_sort_example(): arr = [23, 45, 12, 56, 1, 34, 22, 76, 64, 43] sorted_arr = optimized_quick_sort(arr, threshold=5) assert sorted_arr == sorted(arr) def test_optimized_quick_sort_empty(): arr = [] sorted_arr = optimized_quick_sort(ar...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr, left, right):", "function_name": "insertion_sort", "parameter_list": "(arr, left, right)" }, { "docstring": null, "function_declaration": "def median_of_three(arr, left, right):", "function_name": "median_of_three"...
[ 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 insertion_sort(arr, left, right):\n for i in range(left + 1, right + 1):\n key = arr[i]\n j = i - 1\n while j >= left and arr[j] >...
trial_gpt4o_0
{ "original_instruction": "### Context\nQuick Sort is a highly efficient sorting algorithm, but it can suffer from poor performance with certain types of input. To mitigate this, advanced versions of Quick Sort use techniques like median-of-three pivot selection or hybrid approaches. These methods are designed to opt...
0.59694
Data_Structure_11922
C
[ "insertion_sort", "median_of_three", "partition", "quick_sort_recursive", "optimized_quick_sort" ]
5
[ [ "optimized_quick_sort", "quick_sort_recursive" ], [ "partition", "median_of_three" ], [ "quick_sort_recursive", "insertion_sort" ], [ "quick_sort_recursive", "partition" ] ]
4
[]
false
[]
false
pytest
true
[]
true
6afa3d34c1686b94aeb0d9fab670a0929766e95e
4cc5cea2e3059ba61dd1fdd7d60bdb19171551d7
v1.0
complete
Data_Structure
Data_Structure_10861_C
def encode_rle(input: str) -> str: """ Compresses the input string using Run-Length Encoding (RLE). Parameters: input (str): The string to be encoded. Returns: str: The encoded string in RLE format. >>> encode_rle("aaabb") "3a2b" >>> encode_rle("abcdef") "1a1b1c1d1e1f" ""...
def encode_rle(input: str) -> str: """ Compresses the input string using Run-Length Encoding (RLE). """ if not input: return '' encoded_str = [] count = 1 for i in range(1, len(input)): if input[i] == input[i - 1]: count += 1 else: en...
from solution import encode_rle, decode_rle, compress_rle def test_encode_rle(): assert encode_rle("aaabb") == "3a2b" assert encode_rle("abcdef") == "1a1b1c1d1e1f" assert encode_rle("aabbaa") == "2a2b2a" assert encode_rle("") == "" assert encode_rle("a") == "1a" def test_decode_rle(): assert d...
[ { "docstring": "Compresses the input string using Run-Length Encoding (RLE).", "function_declaration": "def encode_rle(input):", "function_name": "encode_rle", "parameter_list": "(input)" }, { "docstring": "Decompresses an RLE encoded string back to its original form.", "function_declara...
[ 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 encode_rle(input: str) -> str:\n \"\"\"\n Returns the Run-Length Encoded (RLE) string of the input.\n \"\"\"\n if not input:\n return \...
trial_gpt4o_1
{ "original_instruction": "### Run-Length Encoding Compression and Decompression\n\nYou are given a simple data compression algorithm called Run-Length Encoding (RLE). Your task is to demonstrate your understanding of this algorithm by overriding the existing function `encode_rle` to enhance its functionality and wri...
0.642211
Data_Structure_10861
C
[ "encode_rle", "decode_rle", "compress_rle" ]
3
[ [ "compress_rle", "encode_rle" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3b9536084568b4e9433c6f5347126f3e87f2861f
f1c8f24e3068fb8e5e6fef7b2aef4bc6702826e6
v1.0
complete
Data_Structure
Data_Structure_10935_C
class Node: def __init__(self, data): self.data = data self.next = None def find_intersection(head1: Node, head2: Node) -> Node: """ Determine the node at which two singly linked lists intersect. Args: head1 (Node): The head node of the first singly linked list. head2 (Nod...
class Node: def __init__(self, data): self.data = data self.next = None def get_length(node): length = 0 while node: length += 1 node = node.next return length def find_intersection(head1, head2): if not head1 or not head2: return None # Get the len...
from solution import Node, find_intersection def test_find_intersection(): a1 = Node(1) b1 = Node(3) c1 = Node(5) d = Node(7) a2 = Node(2) b2 = Node(4) c2 = Node(6) e = Node(9) f = Node(11) a1.next = b1 b1.next = c1 c1.next = d a2.next = b2 b2.next = c2 c2.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": "class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\ndef get_length(node):\n length = 0\n while node:\n ...
trial_gpt4o_0
{ "original_instruction": "### Question 1: Intersection of Two Linked Lists\n\nYou are provided with the structure of a linked list and your task is to determine if two singly-linked lists intersect, and if so, return the node at which they intersect.\n\n### Constraints\n\n* The two linked lists must retain their ori...
0.561974
Data_Structure_10935
C
[ "get_length", "find_intersection" ]
2
[ [ "find_intersection", "get_length" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
6f8ded4563864b895677d8829da0499e0d445155
c84e254f3a4b11ce6ebf74cc43ddcc32ef360527
v1.0
complete
Data_Structure
Data_Structure_12442_C
def roman_to_int(s: str) -> int: """ Converts a valid Roman numeral string to an integer. Raises ValueError for invalid input. >>> roman_to_int("III") == 3 >>> roman_to_int("IX") == 9 >>> roman_to_int("MCMXCIV") == 1994 >>> roman_to_int("IC") Traceback (most recent call last): ... ...
def roman_to_int(s: str) -> int: """ Converts a valid Roman numeral string to an integer. Raises ValueError for invalid input. """ roman_values = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } valid_subtractives = {'IV', 'IX', 'XL', 'XC', 'CD', 'CM'} n = len...
from solution import roman_to_int def test_roman_to_int_valid_cases(): assert roman_to_int("III") == 3 assert roman_to_int("IV") == 4 assert roman_to_int("IX") == 9 assert roman_to_int("LVIII") == 58 assert roman_to_int("MCMXCIV") == 1994 assert roman_to_int("MMXX") == 2020 def test_roman_to_i...
[ { "docstring": "Converts a valid Roman numeral string to an integer. Raises ValueError for invalid input.", "function_declaration": "def roman_to_int(s):", "function_name": "roman_to_int", "parameter_list": "(s)" }, { "docstring": "Helper function to convert an integer to a Roman numeral str...
[ 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 roman_to_int(s: str) -> int:\n \"\"\"\n Converts a valid Roman numeral string to an integer. Raises ValueError for invalid input.\n \"\"\"\n r...
trial_gpt4o_0
{ "original_instruction": "### Roman Numeral to Integer Conversion Enhancement\n\nGiven the existing implementation for converting Roman numerals to integers, improve this function to handle invalid input scenarios. Specifically, ensure the function only processes valid Roman numeral representations and raise appropr...
0.733021
Data_Structure_12442
C
[ "roman_to_int", "int_to_roman" ]
2
[ [ "roman_to_int", "int_to_roman" ] ]
1
[]
false
[]
false
pytest
true
[]
true
64a487f38f904661a0839350841e17ea88fc198e
e1e7fd15bbc5f88df645fae1507459688e16bef0
v1.0
complete
Data_Structure
Data_Structure_12113_C
from typing import List def optimized_quick_sort(arr: List[int], simulation: bool = False) -> List[int]: """ Sort an array of integers using an optimized Quick Sort with median-of-three pivot selection. If simulation is True, print each step of the sort process. >>> optimized_quick_sort([10, 7, 8, 9, 1, 5]...
from typing import List def median_of_three(arr: List[int], low: int, high: int) -> int: mid = (low + high) // 2 a = arr[low] b = arr[mid] c = arr[high] if a > b: if a < c: median = low elif b > c: median = mid else: median = high else...
from solution import optimized_quick_sort def test_sorted_order(): assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_order(): assert optimized_quick_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_random_order(): assert optimized_quick_sort([3, 1, 4, 5, 2]) == [1, 2, 3, 4...
[ { "docstring": null, "function_declaration": "def median_of_three(arr, low, high):", "function_name": "median_of_three", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def partition(arr, low, high, simulation, step):", "function_name": "partitio...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef median_of_three(arr: List[int], low: int, high: int) -> int:\n mid = (low + high) // 2\n a = arr[low]\n b = arr[mid]\n...
trial_gpt4o_0
{ "original_instruction": "### Context:\nYou are given an array of integers that you need to sort using a modified version of the Quick Sort algorithm. Quick Sort is one of the fastest known sorting algorithms under average conditions but can degrade in performance due to poor pivot choices. To tackle this, we aim to...
0.617339
Data_Structure_12113
C
[ "median_of_three", "partition", "quick_sort_recursive", "optimized_quick_sort" ]
4
[ [ "optimized_quick_sort", "quick_sort_recursive" ], [ "partition", "median_of_three" ], [ "quick_sort_recursive", "partition" ] ]
3
[]
false
[]
false
pytest
true
[]
true
baf96a5be79bcb57efd4160f9a92cb8ea76c14ee
8ef8815b96fe755fe283ba69b5a9279ddd9c4b49
v1.0
complete
Data_Structure
Data_Structure_10780_C
from typing import List, Tuple def heapify(arr: List[int], n: int, i: int, simulation: bool=False) -> int: """ Helper function to maintain the heap property. """ def descending_heap_sort(arr: List[int], simulation: bool=False) -> Tuple[List[int], int]: """ Sort an array of integers in descending ...
from typing import List, Tuple def heapify(arr: List[int], n: int, i: int, simulation: bool=False) -> int: iterations = 1 largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: largest...
from solution import descending_heap_sort def test_sort_simple_array(): arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_arr, iterations = descending_heap_sort(arr) assert sorted_arr == [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1] assert iterations > 0 def test_sort_with_negative_numbers(): arr = [0, -10, 5, 3...
[ { "docstring": null, "function_declaration": "def heapify(arr, n, i, simulation=False):", "function_name": "heapify", "parameter_list": "(arr, n, i, simulation=False)" }, { "docstring": null, "function_declaration": "def descending_heap_sort(arr, simulation=False):", "function_name":...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\ndef heapify(arr: List[int], n: int, i: int, simulation: bool=False) -> int:\n iterations = 1\n largest = i\n left =...
trial_gpt4o_0
{ "original_instruction": "**Scenario**: You are tasked with implementing a sorting algorithm for a large dataset in a constrained environment where memory usage needs to be minimized. You need to use in-place sorting, and the dataset consists of integers. The requirement also includes that detailed simulation logs m...
0.63139
Data_Structure_10780
C
[ "heapify", "descending_heap_sort" ]
2
[ [ "descending_heap_sort", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
463de3c2705d972e3fb4ce1b64cd08f3beeaf7c9
3dd4d5a0451d38ae4e623cc65edd3da0db7fd289
v1.0
complete
Data_Structure
Data_Structure_12443_C
def bitwise_fibonacci(n: int) -> int: """ Calculate the n-th Fibonacci number using bitwise operations only. >>> bitwise_fibonacci(0) == 0 >>> bitwise_fibonacci(1) == 1 >>> bitwise_fibonacci(2) == 1 >>> bitwise_fibonacci(3) == 2 >>> bitwise_fibonacci(4) == 3 >>> bitwise_fibonacci(5) == 5 ...
def bitwise_add(a, b): while b != 0: carry = a & b a = a ^ b b = carry << 1 return a def bitwise_fibonacci(n): if n == 0: return 0 elif n == 1: return 1 prev, curr = 0, 1 for i in range(2, n + 1): next_value = bitwise_add(prev, curr) ...
from solution import bitwise_fibonacci def test_bitwise_fibonacci_base_cases(): assert bitwise_fibonacci(0) == 0 assert bitwise_fibonacci(1) == 1 def test_bitwise_fibonacci_small_numbers(): assert bitwise_fibonacci(2) == 1 assert bitwise_fibonacci(3) == 2 assert bitwise_fibonacci(4) == 3 asser...
[ { "docstring": null, "function_declaration": "def bitwise_add(a, b):", "function_name": "bitwise_add", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def bitwise_fibonacci(n):", "function_name": "bitwise_fibonacci", "parameter_list": "(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": "def bitwise_fibonacci(n):\n def add(a, b):\n while b != 0:\n carry = a & b\n a = a ^ b\n b = carry << 1\n re...
trial_gpt4o_2
{ "original_instruction": "### Question: Bitwise Fibonacci Sequence\n\nYou are working on optimizing algorithms for a low-level embedded system where memory and performance are critical. You need to implement a function that calculates the Fibonacci number but only using bitwise operations for performance efficiency....
0.810352
Data_Structure_12443
C
[ "bitwise_add", "bitwise_fibonacci" ]
2
[ [ "bitwise_fibonacci", "bitwise_add" ] ]
1
[]
false
[]
false
pytest
true
[]
true
60229e41c622ee9089cc151b702eda86ce5ec09a
32d50ccf694dc90cf5fe1724ca39bb8510d30523
v1.0
complete
Data_Structure
Data_Structure_10611_C
def is_prime(n: int) -> bool: """ Check if n is a prime number. >>> is_prime(23) == True >>> is_prime(10) == False >>> is_prime(100003) == True >>> is_prime(100000007) == True >>> is_prime(1000000) == False """ pass def find_primitive_root(p: int) -> int: """ Find the primit...
def is_prime(n): """ Check if n is a prime number. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return Tr...
import pytest from solution import secure_diffie_hellman, is_prime, find_primitive_root def test_prime_check(): assert is_prime(23) == True assert is_prime(10) == False assert is_prime(100003) == True assert is_prime(100000007) == True assert is_prime(1000000) == False def test_find_primitive_root...
[ { "docstring": "Check if n is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Find the primitive root of p.", "function_declaration": "def find_primitive_root(p):", "function_name": "find_primitive_...
[ 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 sympy\n\ndef is_primitive_root(a, p):\n \"\"\"\n Checks if `a` is a primitive root of `p`.\n \"\"\"\n if sympy.isprime(p):\n require...
trial_gpt4o_1
{ "original_instruction": "### Coding Challenge: Enhanced Diffie-Hellman Key Exchange with Error Handling\n\n#### Context\nDiffie-Hellman key exchange is a method that empowers two parties to establish a shared secret over an unsecured channel. However, for enhanced security and efficient operation, we must ensure th...
0.612083
Data_Structure_10611
C
[ "is_prime", "find_primitive_root", "secure_diffie_hellman" ]
3
[ [ "secure_diffie_hellman", "find_primitive_root" ], [ "secure_diffie_hellman", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
856d73d70bddc33c3012dbf01d40d43771c5416b
cf815acddca1ba4b76945f7105825300f9022050
v1.0
complete
Data_Structure
Data_Structure_12447_C
import random from typing import List, Tuple def limited_bogo_sort(arr: List[int], max_iterations: int) -> Tuple[List[int], int]: """ Uses a modified version of the Bogo Sort algorithm that stops after a specific number of maximum iterations. >>> limited_bogo_sort([3, 1, 2], 100) ([1, 2, 3], 5) ...
import random from typing import List, Tuple def is_sorted(arr: List[int]) -> bool: """ Helper function that checks if the given array is sorted. """ return all(arr[i] <= arr[i+1] for i in range(len(arr)-1)) def limited_bogo_sort(arr: List[int], max_iterations: int) -> Tuple[List[int], int]: """ ...
from solution import limited_bogo_sort def test_with_sorted_array(): arr = [1, 2, 3, 4, 5] sorted_arr, iterations = limited_bogo_sort(arr, 100) assert sorted_arr == [1, 2, 3, 4, 5] assert iterations == 0 def test_with_reverse_sorted_array(): arr = [5, 4, 3, 2, 1] sorted_arr, iterations = limit...
[ { "docstring": "Helper function that checks if the given array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Uses a modified version of the Bogo Sort algorithm that stops\nafter a specific number of maxi...
[ 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 typing import List, Tuple\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to check if the array is sorted.\n ...
trial_gpt4o_1
{ "original_instruction": "**Question**: Implement a function that uses a modified version of the Bogo Sort algorithm. In this version, stop the algorithm after a specific number of maximum iterations even if the array is not sorted, and return the array along with the number of iterations performed. The function sho...
0.624162
Data_Structure_12447
C
[ "is_sorted", "limited_bogo_sort" ]
2
[ [ "limited_bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
142166480d3e4fc0ccc43fca9e6c47b1f631c32f
3f7c7b274c053259e89a8d035bcc8eb0d42c868a
v1.0
complete
Data_Structure
Data_Structure_11473_C
import random def is_sorted(arr): """ Helper function to check if the array is sorted. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort_with_cap(arr, max_shuffles): """ Sort the array using a capped Bogo Sort. Par...
import random def is_sorted(arr): """ Helper function to check if the array is sorted. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort_with_cap(arr, max_shuffles): """ Sort the array using a capped Bogo Sort. Par...
from solution import bogo_sort_with_cap def test_bogo_sort_sorted_array(): assert bogo_sort_with_cap([1, 2, 3, 4], 10000) == [1, 2, 3, 4] assert bogo_sort_with_cap([], 10000) == [] def test_bogo_sort_single_element_array(): assert bogo_sort_with_cap([1], 10000) == [1] 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": "Sort the array using a capped Bogo Sort.\n\nParameters:\narr (list): A list of sortable elements.\nmax_...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef bogo_sort_with_cap(arr, max_shuffles):\n \"\"\"\n Sort the array using a capped Bogo Sort.\n \n Parameters:\n arr (list): ...
trial_gpt4o_2
{ "original_instruction": "- Bogo Sort Enhancement\n\n#### Context\nYou have been provided with the highly inefficient Bogo Sort algorithm. Despite its impracticality in real-world applications, it serves as a good exercise to understand brute-force methods and randomness in algorithms.\n\n#### Task\nWrite a function...
0.576571
Data_Structure_11473
C
[ "is_sorted", "bogo_sort_with_cap" ]
2
[ [ "bogo_sort_with_cap", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4064538874cffbe89ac6ad5ca07c9d030c697911
ae096a534892577092557a418a5bb956bddffccc
v1.0
complete
Data_Structure
Data_Structure_12176_C
from typing import List def bucket_sort(arr: List[int]) -> List[int]: """ Implement the bucket sort algorithm to sort a list of non-negative integers. >>> bucket_sort([37, 45, 29, 8, 12, 88, 55]) [8, 12, 29, 37, 45, 55, 88] >>> bucket_sort([1, 4, 1, 2, 7, 5, 2]) [1, 1, 2, 2, 4, 5, 7] ...
from typing import List def insertion_sort(arr: List[int]) -> List[int]: # Simple insertion sort used within the bucket for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key retu...
from solution import bucket_sort def test_empty_list(): assert bucket_sort([]) == [] def test_single_element_list(): assert bucket_sort([5]) == [5] def test_sorted_list(): assert bucket_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_list(): assert bucket_sort([5, 4, 3, 2, 1]) == [1...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr):", "function_name": "insertion_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def bucket_sort(arr):", "function_name": "bucket_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": "from typing import List\n\ndef insertion_sort(arr: List[int]) -> None:\n \"\"\"\n Utility function to sort an array using insertion sort.\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "You are required to implement a sorting function using the bucket sort algorithm that sorts a list of non-negative integers. Your implementation should address common edge cases and aim for efficiency. Note that the provided dummy `next_sort` uses insertion sort, but you are free to use a d...
0.645079
Data_Structure_12176
C
[ "insertion_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0898ae04883a8b96a71cfcb6ee97d6f8207a2719
63ea3a78f784a0e723a2fa47b323f81bb0122e92
v1.0
complete
Data_Structure
Data_Structure_12341_C
from typing import List def next_sort(arr): """ A sample sorting function (insertion sort) for sorting each bucket. """ for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key ...
from typing import List def next_sort(arr): """ A sample sorting function (insertion sort) for sorting each bucket. """ for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key ...
from solution import bucket_sort def test_empty_list(): assert bucket_sort([]) == [] def test_single_element(): assert bucket_sort([1]) == [1] def test_all_identical_elements(): assert bucket_sort([5, 5, 5, 5]) == [5, 5, 5, 5] def test_sorted_list(): assert bucket_sort([1, 2, 3, 4, 5]) == [1, 2, 3, ...
[ { "docstring": "A sample sorting function (insertion sort) for sorting each bucket.", "function_declaration": "def next_sort(arr):", "function_name": "next_sort", "parameter_list": "(arr)" }, { "docstring": "Sorts an array of non-negative integers using bucket sort algorithm.", "function...
[ 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 next_sort(arr: List[int]) -> List[int]:\n \"\"\"\n This function sorts the given list using Insertion Sort.\n It will ...
trial_gpt4o_2
{ "original_instruction": "### Bucket Sort Implementation\n\n#### Background Context\nBucket sort is a sorting algorithm that distributes the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm or recursively applying the bucket sort itsel...
0.635044
Data_Structure_12341
C
[ "next_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "next_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
45c77546502b7e59d88d683309edc83750f52b72
bb7c20ff0717028c6551a5dea0eabf84ed391d2b
v1.0
complete
Data_Structure
Data_Structure_12261_C
from typing import List, Tuple def generate_keys(k: int) -> Tuple[int, int, int]: """ Generate RSA keys of bit-length k. Args: k (int): Bit-length of the RSA modulus. Returns: Tuple[int, int, int]: A tuple containing the modulus (n), public e...
import random from sympy import randprime, mod_inverse def generate_keys(k: int): """ Generate RSA keys of bit-length k. Returns: tuple: (n, e, d) where n: modulus e: public exponent d: private exponent """ # Generate two distinct prime numbers p and...
from solution import generate_keys, encrypt_message, decrypt_message def test_generate_keys(): n, e, d = generate_keys(16) assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) def test_encrypt_message(): message = "RSA test" n, e, d = generate_keys(16) encrypted_me...
[ { "docstring": "Generate RSA keys of bit-length k.\n\nReturns:\n tuple: (n, e, d) where\n n: modulus\n e: public exponent\n d: private exponent", "function_declaration": "def generate_keys(k):", "function_name": "generate_keys", "parameter_list": "(k)" }, { "docstring...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl", "solution_code": "import random\nfrom sympy import randprime, mod_inverse\n\ndef generate_keys(k: int):\n \"\"\"\n Generate RSA keys of bit-lengt...
trial_gpt4o_1
{ "original_instruction": "### RSA Encryption and Decryption Implementation\n\nYou have been provided with an implementation of the key generation algorithm for the RSA encryption system. Your task is to write two functions `encrypt_message` and `decrypt_message` that utilize the provided RSA system to encrypt and de...
0.746407
Data_Structure_12261
C
[ "generate_keys", "encrypt_message", "decrypt_message", "gcd" ]
4
[ [ "generate_keys", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
1bc8f315a0cd4de73f648506e9b4e0674558ac43
677cd3f419b09f01967a952dbd5d675ccd72a3b6
v1.0
complete
Data_Structure
Data_Structure_10062_C
def extended_gcd(a: int, b: int) -> (int, int, int): """ Implements the Extended Euclidean Algorithm. Returns a tuple (s, t, g) such that s * a + t * b = g where g is the gcd of a and b. :param a: Integer :param b: Integer :return: Tuple of integers (s, t, g) >>> extended_gcd(30, 20) (...
def extended_gcd(a, b): """ Implements the Extended Euclidean Algorithm. Returns a tuple (s, t, g) such that s * a + t * b = g where g is the gcd of a and b. :param a: Integer :param b: Integer :return: Tuple of integers (s, t, g) """ old_s, s = 1, 0 old_t, t = 0, 1 old_r, r = a...
from solution import extended_gcd, modular_inverse def test_extended_gcd_basic(): s, t, g = extended_gcd(30, 20) assert s == 1 and t == -1 and g == 10 def test_extended_gcd_coprime(): s, t, g = extended_gcd(17, 31) assert s * 17 + t * 31 == g == 1 def test_extended_gcd_zero_case(): s, t, ...
[ { "docstring": "Implements the Extended Euclidean Algorithm.\nReturns a tuple (s, t, g) such that s * a + t * b = g where g is the gcd of a and b.\n\n:param a: Integer\n:param b: Integer\n:return: Tuple of integers (s, t, g)", "function_declaration": "def extended_gcd(a, b):", "function_name": "extended...
[ 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 extended_gcd(a, b):\n \"\"\"\n Returns a tuple (s, t, g) where:\n - s, t are the coefficients such that sa + tb = gcd(a, b)\n - g is the gcd o...
trial_gpt4o_2
{ "original_instruction": "Modular Cryptography\n\n#### Context\nYou are tasked with implementing a module for a cryptographic system that involves computations of multiplicative inverses under a given modulus. A critical part of RSA encryption/decryption algorithms uses the modular inverse for various operations. Gi...
0.623079
Data_Structure_10062
C
[ "extended_gcd", "modular_inverse" ]
2
[ [ "modular_inverse", "extended_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
35199fd8db39ae37ff84c634d9c48b07e3d3d0f8
8cc47f908b26089ce9786ffcc3b15126eab24e95
v1.0
complete
Data_Structure
Data_Structure_11064_C
def radix_sort(arr: List[int]) -> List[int]: """ Sort a list of positive integers in ascending order using the Radix Sort algorithm. >>> radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) [2, 24, 45, 66, 75, 90, 170, 802] >>> radix_sort([3, 1, 4, 1, 5]) [1, 1, 3, 4, 5] Args: arr (List[int])...
from typing import List def counting_sort(arr: List[int], exp: int) -> List[int]: n = len(arr) output = [0] * n # output array to store sorted numbers count = [0] * 10 # count array to store count of occurrences of digits # Store count of occurrences in count[] for i in range(n): index =...
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([3, 1, 4, 1, 5]) == [1, 1, 3, 4, 5] def test_radix_sort_empty_list(): assert radix_sort([]) == [] ...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp):", "function_name": "counting_sort", "parameter_list": "(arr, exp)" }, { "docstring": null, "function_declaration": "def radix_sort(arr):", "function_name": "radix_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": "from typing import List\n\ndef counting_sort(arr, exp):\n \"\"\"\n A function to do counting sort of arr[] according to\n the digit represented by ex...
trial_gpt4o_2
{ "original_instruction": "**Problem Statement**:\nYou are provided with a list of positive integers, and your task is to implement the `radix_sort` function to sort this list in ascending order. The `radix_sort` should be implemented as described in the provided algorithm analysis.\n\n**Function Signature**:\n```pyt...
0.684572
Data_Structure_11064
C
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eb7493328304222c612c792c5452cf454346afce
6c444f1398361296801059fe0ff7113238ba6e83
v1.0
complete
Data_Structure
Data_Structure_9929_C
from typing import List def maximum_flow_bfs(adjacency_matrix: List[List[int]]) -> int: """ Compute the maximum amount of flow that can be sent from the source to the sink in a flow network using the Edmonds-Karp implementation of the Ford-Fulkerson method. Args: adjacency_matrix (List[List[int]]...
from collections import deque def bfs(residual_graph, source, sink, parent): visited = [False] * len(residual_graph) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() for v, capacity in enumerate(residual_graph[u]): if not visited[...
from solution import maximum_flow_bfs def test_example_1(): adjacency_matrix = [ [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(adjacency_matrix) == 23 de...
[ { "docstring": null, "function_declaration": "def bfs(residual_graph, source, sink, parent):", "function_name": "bfs", "parameter_list": "(residual_graph, source, sink, parent)" }, { "docstring": null, "function_declaration": "def maximum_flow_bfs(adjacency_matrix):", "function_name"...
[ 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 collections import deque\nfrom typing import List\n\ndef bfs(residual_graph, source, sink, parent):\n visited = [False] * len(residual_graph)\n que...
trial_gpt4o_2
{ "original_instruction": "### Problem Description\n\nYou are given a directed graph representing a flow network with nodes representing junctions and edges representing pipes with specific capacities. Your task is to determine the maximum amount of flow that can be sent from the source node (the first node) to the s...
0.54768
Data_Structure_9929
C
[ "bfs", "maximum_flow_bfs" ]
2
[ [ "maximum_flow_bfs", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ad6eea20a9059e8e81eb618aba5e3015af86d063
2c20ec85d927cbe462ef75c029d8c745140643f4
v1.0
complete
Data_Structure
Data_Structure_12704_C
from typing import List def enhanced_radix_sort(arr: List[int]) -> List[int]: """ Enhanced Radix Sort to handle arrays with mixed negative and positive integers. Sorts an array containing both positive and negative integers with a linearithmic complexity. >>> enhanced_radix_sort([170, 45, 75, -90, 802, 24,...
from typing import List def counting_sort(arr, exp): n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = abs(arr[i]) // exp count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] for i in range(n - 1, -1, -1): index = abs(...
from solution import enhanced_radix_sort def test_enhanced_radix_sort_mixed_numbers(): assert enhanced_radix_sort([170, 45, 75, -90, 802, 24, 2, 66, -23]) == [-90, -23, 2, 24, 45, 66, 75, 170, 802] def test_enhanced_radix_sort_positive_and_negative(): assert enhanced_radix_sort([-5, -1, 3, 0, -2, 2, -3, 1, 4,...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp):", "function_name": "counting_sort", "parameter_list": "(arr, exp)" }, { "docstring": null, "function_declaration": "def radix_sort(arr):", "function_name": "radix_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": "from typing import List\n\ndef enhanced_radix_sort(arr: List[int]) -> List[int]:\n def counting_sort(arr, exp):\n n = len(arr)\n output = [0]...
trial_gpt4o_2
{ "original_instruction": "### Question: Implement Enhanced Radix Sort to Handle Extended Case\n\n**Context**: Radix Sort is an efficient sorting algorithm for numerical data which sorts numbers based on the digits from the least significant to the most significant. In this task, you are required to implement an enha...
0.699784
Data_Structure_12704
C
[ "counting_sort", "radix_sort", "enhanced_radix_sort" ]
3
[ [ "enhanced_radix_sort", "radix_sort" ], [ "radix_sort", "counting_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
da9ebdf1caee41b285799750c74f2763d7ae9f8d
d8229e30cb610e7129ad78a561eb4cee3878fc5e
v1.0
complete
Data_Structure
Data_Structure_12349_C
from typing import List def enhanced_interpolation_search(array: List[int], search_key: int) -> int: """ Enhanced Interpolation Search with Error Handling. :param array: The list of sorted integers to be searched. :param search_key: The integer key to be searched within the array. :returns: T...
from typing import List def binary_search(array: List[int], search_key: int, low: int, high: int) -> int: while low <= high: mid = low + (high - low) // 2 if array[mid] == search_key: return mid elif array[mid] < search_key: low = mid + 1 else: hi...
def test_enhanced_interpolation_search(): assert enhanced_interpolation_search([10, 20, 30, 40, 50, 60, 70, 80, 90, 100], 40) == 3 assert enhanced_interpolation_search([1, 3, 5, 7, 9, 11, 13, 15, 17, 19], 15) == 7 assert enhanced_interpolation_search([5, 10, 12, 14, 17, 20, 25, 30, 35], 100) == -1 asser...
[ { "docstring": null, "function_declaration": "def binary_search(array, search_key, low, high):", "function_name": "binary_search", "parameter_list": "(array, search_key, low, high)" }, { "docstring": null, "function_declaration": "def enhanced_interpolation_search(array, search_key):", ...
[ 0, 0, 0, 1, 0, 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 interpolation_search(array: List[int], search_key: int) -> int:\n low, high = 0, len(array) - 1\n \n while low <= high...
trial_gpt4o_3
{ "original_instruction": "### Coding Task: Enhanced Interpolation Search with Error Handling\n\nYou are given a sorted array of integers and a search key. Implement an enhanced version of the Interpolation Search algorithm that correctly handles edge cases and improves performance in certain scenarios. Additionally,...
0.568422
Data_Structure_12349
C
[ "binary_search", "enhanced_interpolation_search" ]
2
[ [ "enhanced_interpolation_search", "binary_search" ] ]
1
[]
false
[]
false
pytest
false
[]
true
67a40504560b28ed9df491a75cd845fe8da4b507
c28a85e86c6673613feeadfd363e34ff01945b62
v1.0
complete
Data_Structure
Data_Structure_11905_C
def merge_sort(arr): """ Merge Sort algorithm to sort an array. :param arr: List[int] - The input array of integers to be sorted :return: List[int] - The sorted array >>> merge_sort([]) == [] >>> merge_sort([1]) == [1] >>> merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] >>> merge_sort([5...
def merge_sort(arr): """ Merge Sort algorithm to sort an array. :param arr: List[int] - The input array of integers to be sorted :return: List[int] - The sorted array """ # Base case if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) ri...
from solution import merge_sort def test_merge_sort_empty_list(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_sorted_list(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_unsorted_list(): assert merge...
[ { "docstring": "Merge Sort algorithm to sort an array.\n:param arr: List[int] - The input array of integers to be sorted\n:return: List[int] - The sorted array", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merge ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\"\n Merge Sort algorithm to sort an array.\n :param arr: List[int] - The input array of integers to be sorted\n :retur...
trial_gpt4o_2
{ "original_instruction": "**Context**:\nYou are a developer at a company where you often need to sort large datasets efficiently. Your task is to implement the merge sort algorithm, ensuring it works correctly for all possible inputs.\n\n**Task**:\nImplement the `merge_sort` function provided. The function should so...
0.641268
Data_Structure_11905
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a074f8f228fd9f4f312d6bfe511f249fbf19d5fd
b2cbb6eb3b5c35e73e2ddff38eb82a44f2f94ec3
v1.0
complete
Data_Structure
Data_Structure_12865_C
from typing import List def predictive_text(corpus: str, n: int, starting_word: str) -> List[str]: """ Predict the next word given a current word based on a Markov Chain derived from the corpus. Given a corpus of text, this function builds a predictive text model using a Markov Chain. Args: c...
import random from collections import defaultdict from typing import List def build_markov_chain(corpus: str): words = corpus.lower().split() markov_chain = defaultdict(list) for i in range(len(words) - 1): markov_chain[words[i]].append(words[i + 1]) return markov_chain def predictiv...
from solution import predictive_text def test_predictive_text_short_corpus(): corpus = "The cat sat on the mat" result = predictive_text(corpus, 4, "the") assert result == ["the", "cat", "sat", "on", "the"] def test_predictive_text_multiple_options(): corpus = "The cat sat on the mat. The cat saw the ...
[ { "docstring": null, "function_declaration": "def build_markov_chain(corpus):", "function_name": "build_markov_chain", "parameter_list": "(corpus)" }, { "docstring": null, "function_declaration": "def predictive_text(corpus, n, starting_word):", "function_name": "predictive_text", ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom collections import defaultdict\nfrom typing import List\n\ndef build_markov_chain(corpus: str):\n words = corpus.lower().split()\n m...
trial_gpt4o_0
{ "original_instruction": "### Question: Designing a Predictive Text Model with Markov Chains\n\nGiven a corpus of text, your task is to build a predictive text model using a Markov Chain. Implement a function that predicts the next word given a current word based on a Markov Chain derived from the corpus.\n\n#### In...
0.611424
Data_Structure_12865
C
[ "build_markov_chain", "predictive_text" ]
2
[ [ "predictive_text", "build_markov_chain" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8c06c62e9e70c19f65900c2f871696ee146582cf
95aef29dedfe0ad29a63316999a0e58641ac445b
v1.0
complete
Data_Structure
Data_Structure_9747_C
def hailstone(n): """ Generate the Hailstone sequence starting from n. Args: n (int): The starting integer. Returns: List[int]: The Hailstone sequence. >>> hailstone(1) [1] >>> hailstone(2) [2, 1] >>> hailstone(3) [3, 10, 5, 16, 8, 4, 2, 1] """ # Imple...
def hailstone(n): """ Generate the Hailstone sequence starting from n. """ sequence = [] while n != 1: sequence.append(n) if n % 2 == 0: n //= 2 else: n = 3 * n + 1 sequence.append(1) return sequence def find_longest_hailstone_sequence(low, hi...
from solution import hailstone, find_longest_hailstone_sequence def test_hailstone_sequence(): assert hailstone(1) == [1] assert hailstone(2) == [2, 1] assert hailstone(3) == [3, 10, 5, 16, 8, 4, 2, 1] def test_find_longest_hailstone_sequence_range_1_to_10(): result = find_longest_hailstone_sequence(1...
[ { "docstring": "Generate the Hailstone sequence starting from n.", "function_declaration": "def hailstone(n):", "function_name": "hailstone", "parameter_list": "(n)" }, { "docstring": "Finds the integer within the range [low, high] that generates \nthe longest Hailstone sequence.\n\nParamete...
[ 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 hailstone(n):\n \"\"\"\n Generate the Hailstone sequence starting from n.\n \"\"\"\n sequence = []\n while n != 1:\n sequence.append...
trial_gpt4o_0
{ "original_instruction": "### Hailstone Sequence Analysis and Longest Sequence Finder\n\nImplement a function `find_longest_hailstone_sequence` that finds the integer within a given range `[low, high]` that generates the longest Hailstone sequence, and returns the starting integer, the length of the sequence, and th...
0.590533
Data_Structure_9747
C
[ "hailstone", "find_longest_hailstone_sequence" ]
2
[ [ "find_longest_hailstone_sequence", "hailstone" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f2c350f6d99f715bce035a0b5bf317355b222caa
1d81b01b25d9f9ce300c9c0d59678d9b8663a354
v1.0
complete
Data_Structure
Data_Structure_11220_C
from typing import List def solve_chinese_remainder(nums: List[int], rems: List[int]) -> int: """ Solve the system of simultaneous congruences using the Chinese Remainder Theorem. Args: nums (List[int]): List of pairwise coprime integers each > 1. rems (List[int]): List of remainders respective to...
from typing import List def extended_gcd(a, b): if a == 0: return b, 0, 1 gcd, x1, y1 = extended_gcd(b % a, a) x = y1 - (b // a) * x1 y = x1 return gcd, x, y def mod_inverse(a, m): gcd, x, _ = extended_gcd(a, m) if gcd != 1: raise ValueError(f"No modular inverse for {a} and...
def test_basic_solution(): nums = [3, 5, 7] rems = [2, 3, 2] assert solve_chinese_remainder(nums, rems) == 23 def test_valid_multiple_solutions(): nums = [2, 3, 5] rems = [1, 2, 3] assert solve_chinese_remainder(nums, rems) == 23 # 23 % 2 = 1, 23 % 3 = 2, 23 % 5 = 3 def test_single_congru...
[ { "docstring": null, "function_declaration": "def extended_gcd(a, b):", "function_name": "extended_gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def mod_inverse(a, m):", "function_name": "mod_inverse", "parameter_list": "(a, m)" }, { "d...
[ 0, 0, 0, 1, 0, 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 solve_chinese_remainder(nums: List[int], rems: List[int]) -> int:\n if len(nums) != len(rems):\n raise ValueError(\"T...
trial_gpt4o_3
{ "original_instruction": "### Coding Task\n\n#### Scenario:\nIn your work as a software developer, you often encounter systems of simultaneous congruences while dealing with various cryptographic protocols. To ensure the security and efficiency of your system, you must implement a reliable function that finds soluti...
0.554981
Data_Structure_11220
C
[ "extended_gcd", "mod_inverse", "solve_chinese_remainder" ]
3
[ [ "mod_inverse", "extended_gcd" ], [ "solve_chinese_remainder", "extended_gcd" ], [ "solve_chinese_remainder", "mod_inverse" ] ]
3
[]
false
[]
false
pytest
false
[]
true
3a15c1f9d554e2ce32b65907692c4ac1bbe4201b
73fa52cb13b28b0c2e1e91928a2c86372a242469
v1.0
complete
Data_Structure
Data_Structure_12405_C
from typing import List def efficient_bogo_sort(arr: List[int]) -> List[int]: """ Implement a more efficient strategy than classic Bogo Sort to sort an array. The function should avoid random shuffling each time but still rely on some 'probabilistic' approach reminiscent of the original Bogo Sort. ...
import random from typing import List def is_sorted(arr: List[int]) -> bool: """ Check if the given list is sorted in ascending order. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def efficient_bogo_sort(arr: List[int]) -> List[int]: ""...
from solution import efficient_bogo_sort def test_sorted_list(): assert efficient_bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_list(): assert efficient_bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_random_list(): random_list = [3, 5, 2, 4, 1] sorted_list = sorted...
[ { "docstring": "Check if the given list is sorted in ascending order.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "An improved version of Bogo Sort that checks random pairs and swaps to sort the array.", "func...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if the given array is sorted in ascending order.\n \"\"\"\n for i in rang...
trial_gpt4o_2
{ "original_instruction": "Implement a function `efficient_bogo_sort` that uses a more efficient strategy than classic Bogo Sort to sort an array. The function should avoid random shuffling each time but still rely on some 'probabilistic' approach reminiscent of the original Bogo Sort.\n\n### Requirements:\n1. Comple...
0.59615
Data_Structure_12405
C
[ "is_sorted", "efficient_bogo_sort" ]
2
[ [ "efficient_bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
37767b07f60af4d4b1e71630b0c1d32093ea710c
06e87ea82b3b53e7572f6fe88f201f960b388f00
v1.0
complete
Data_Structure
Data_Structure_10918_C
import time def stooge_sort(arr, l, h): """Implements the Stooge Sort algorithm on a list of integers.""" pass def merge_sort(arr): """Implements the Merge Sort algorithm on a list of integers.""" pass def compare_sorting_algorithms(arr): """Compares the performance of Stooge Sort and Merge Sort....
import time def stooge_sort(arr, l, h): if l >= h: return if arr[l] > arr[h]: arr[l], arr[h] = arr[h], arr[l] if h - l + 1 > 2: t = (h - l + 1) // 3 stooge_sort(arr, l, h - t) stooge_sort(arr, l + t, h) stooge_sort(arr, l, h - t) def merge_sort(arr): if ...
from solution import stooge_sort, merge_sort, compare_sorting_algorithms def test_stooge_sort(): arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] expected_sorted_arr = sorted(arr) stooge_sort(arr, 0, len(arr) - 1) assert arr == expected_sorted_arr def test_merge_sort(): arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3,...
[ { "docstring": null, "function_declaration": "def stooge_sort(arr, l, h):", "function_name": "stooge_sort", "parameter_list": "(arr, l, h)" }, { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\n\ndef stooge_sort(arr, l, h):\n \"\"\"\n Recursively sorts the array using Stooge Sort algorithm.\n \"\"\"\n if l >= h:\n retu...
trial_gpt4o_2
{ "original_instruction": "## Problem: Implement and Optimize a Stooge Sort\nStooge Sort is an interesting but inefficient sorting algorithm. Given its educational value, you are tasked with implementing this algorithm and then also implementing an optimized version of Merge Sort to compare performance.\n\n### Steps:...
0.56893
Data_Structure_10918
C
[ "stooge_sort", "merge_sort", "compare_sorting_algorithms" ]
3
[ [ "compare_sorting_algorithms", "merge_sort" ], [ "compare_sorting_algorithms", "stooge_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a67bfff1f806b76ec27386ce22014ed3dac86384
754cb79d80dd7a02517f843c89717b19d0b67b77
v1.0
complete
Data_Structure
Data_Structure_10888_C
def matrix_power(matrix: List[List[int]], exponent: int) -> List[List[int]]: """ Computes the power of a matrix using exponentiation by squaring. Args: matrix (List[List[int]]): a square matrix (n x n) where each element is a non-negative integer. exponent (int): a non-negative integer, representin...
from typing import List def matrix_multiply(a: List[List[int]], b: List[List[int]]) -> List[List[int]]: """ Multiplies two square matrices a and b. """ 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): re...
from solution import matrix_power def test_matrix_power_identity(): assert matrix_power([[1]], 5) == [[1]] assert matrix_power( [ [1, 0], [0, 1] ], 10 ) == [ [1, 0], [0, 1] ] def test_matrix_power_zero_exponent(): assert matrix_power( ...
[ { "docstring": "Multiplies two square matrices a and b.", "function_declaration": "def matrix_multiply(a, b):", "function_name": "matrix_multiply", "parameter_list": "(a, b)" }, { "docstring": "Computes the power of a matrix using exponentiation by squaring.", "function_declaration": "de...
[ 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 matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n n = len(A)\n result = [[0] * n for _ in ran...
trial_gpt4o_1
{ "original_instruction": "### Matrix Chain Multiplication Problem\n\nYou are designing an efficient system for computing powers of matrices. Given a square matrix, you need to implement a function to compute the power of this matrix using the technique of matrix exponentiation by repeated squaring.\n\n#### Function ...
0.55905
Data_Structure_10888
C
[ "matrix_multiply", "matrix_power" ]
2
[ [ "matrix_power", "matrix_multiply" ] ]
1
[]
false
[]
false
pytest
true
[]
true
55e64f4b580567a4191b3f97e01a42fed3597895
3846f2106e6bd7fec25a8f1a800bdfe39437abb2