version
stringclasses
1 value
style
stringclasses
2 values
subset
stringclasses
12 values
question_id
stringlengths
9
23
question
stringlengths
27
8.13k
solution
stringlengths
99
5.97k
test
stringlengths
105
4.45k
test_info
listlengths
0
13
gpt_pass_sequence
listlengths
1
10
gpt_pass_trial_num
int64
1
10
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
trials
dict
chosen_trial
stringclasses
10 values
metadata
dict
benchmark_similarity
float64
0.16
0.93
benchmark_instruction
stringclasses
1 value
benchmark_task_id
stringclasses
1 value
filter_reason
stringclasses
1 value
base_id
stringlengths
7
21
variant
stringclasses
2 values
top_function_names
listlengths
2
13
n_top_functions
int64
2
13
helper_call_edges
listlengths
1
16
n_helper_call_edges
int64
1
16
harness_functions
listlengths
0
3
structural_wrapper
bool
1 class
class_names
listlengths
0
5
has_class
bool
2 classes
test_kind
stringclasses
1 value
test_has_solution_import
bool
2 classes
third_party_imports
listlengths
0
5
stdlib_only
bool
2 classes
question_norm_sha1
stringlengths
40
40
solution_ast_sha1
stringlengths
40
40
v1.0
instruct
Data_Structure
Data_Structure_15283_I
**Problem Statement: Implement a Modified KMP Algorithm for Multi-Pattern Matching** You are tasked with modifying the Knuth-Morris-Pratt (KMP) algorithm to handle multiple patterns within a given text. This requires preprocessing a list of patterns and then searching for any of these patterns in the text. ### Instru...
from typing import List, Dict def compute_lps(pattern: str) -> List[int]: """Compute the Longest Prefix Suffix (LPS) array for the KMP algorithm.""" lps = [0] * len(pattern) length = 0 i = 1 while i < len(pattern): if pattern[i] == pattern[length]: length += 1 lps[i]...
def test_compute_lps(): assert compute_lps("ababc") == [0, 0, 1, 2, 0] assert compute_lps("aaaa") == [0, 1, 2, 3] assert compute_lps("abcd") == [0, 0, 0, 0] assert compute_lps("aabaaac") == [0, 1, 0, 1, 2, 2, 0] def test_kmp_search(): assert kmp_search("testtexttext", "test") == [0] assert kmp_...
[ { "docstring": "Compute the Longest Prefix Suffix (LPS) array for the KMP algorithm.", "function_declaration": "def compute_lps(pattern):", "function_name": "compute_lps", "parameter_list": "(pattern)" }, { "docstring": "Perform KMP search for a single pattern in the text.", "function_de...
[ 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, Dict\n\ndef kmp_pattern_table(pattern: str) -> List[int]:\n \"\"\"\n Computes the partial match table (also known as \"failure ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015283", "row_id": 15283, "seed_ids": "[93]" }
0.556999
Data_Structure_15283
I
[ "compute_lps", "kmp_search", "multi_pattern_kmp" ]
3
[ [ "kmp_search", "compute_lps" ], [ "multi_pattern_kmp", "kmp_search" ] ]
2
[]
false
[]
false
pytest
false
[]
true
d089d78e14e174b8455c6a8ca2bd35f9e6b3a77a
9342d3964eaf5e828b94e6af1e6b405bd8d23594
v1.0
instruct
Data_Structure
Data_Structure_15286_I
You are tasked with implementing a robust quick sort algorithm. This implementation must handle potential pitfalls of a basic quick-sort, such as poor pivot selection. Additionally, you are required to enhance the basic quick sort to better manage worst-case scenarios. ### Function Specification: Implement the functio...
from typing import List def insertion_sort(arr: List[int], low: int, high: int) -> None: for i in range(low + 1, high + 1): key = arr[i] j = i - 1 while j >= low and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def partition(arr: List[int], low:...
import pytest from solution import optimized_quick_sort def test_sorted_array(): arr = [1, 2, 3, 4, 5] assert optimized_quick_sort(arr) == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): arr = [5, 4, 3, 2, 1] assert optimized_quick_sort(arr) == [1, 2, 3, 4, 5] def test_duplicate_elements(): arr ...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr, low, high):", "function_name": "insertion_sort", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter_l...
[ 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], left: int, right: int) -> None:\n for i in range(left + 1, right + 1):\n key = arr[i]\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015286", "row_id": 15286, "seed_ids": "[25]" }
0.542792
Data_Structure_15286
I
[ "insertion_sort", "partition", "quick_sort", "optimized_quick_sort" ]
4
[ [ "optimized_quick_sort", "quick_sort" ], [ "quick_sort", "insertion_sort" ], [ "quick_sort", "partition" ] ]
3
[]
false
[]
false
pytest
true
[]
true
2b6fee2b958fcacf5a5347f20f52b3e67acf117d
ebaf277542bae1dc21efdceb3f689c98424b37e1
v1.0
instruct
Data_Structure
Data_Structure_15309_I
You have been given the task of improving the RSA key generation function to enhance its efficiency by incorporating probabilistic primality tests and optimizing the modular inverse calculation. Additionally, you should extend the RSA encryption scheme by implementing a signature verification mechanism. #### Requireme...
import random from sympy import isprime, mod_inverse def miller_rabin(n, k=40): """Test if n is a prime number using the Miller-Rabin primality test""" if n == 2 or n == 3: return True if n <= 1 or n % 2 == 0: return False r, s = 0, n - 1 while s % 2 == 0: r += 1 ...
from solution import generate_key, sign, verify 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 > 1 assert d > 1 assert e != d def test_sign_verify(): n, e, d = generate...
[ { "docstring": "Test if n is a prime number using the Miller-Rabin primality test", "function_declaration": "def miller_rabin(n, k=40):", "function_name": "miller_rabin", "parameter_list": "(n, k=40)" }, { "docstring": "Generate a prime number of specified bit length", "function_declarat...
[ 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 miller_rabin(n, k=40):\n if n == 2 or n == 3:\n return True\n if n <= 1 or n % 2 == 0:\n return...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015309", "row_id": 15309, "seed_ids": "[154]" }
0.507445
Data_Structure_15309
I
[ "miller_rabin", "generate_large_prime", "generate_key", "sign", "verify" ]
5
[ [ "generate_key", "generate_large_prime" ], [ "generate_large_prime", "miller_rabin" ] ]
2
[]
false
[]
false
pytest
true
[ "sympy" ]
false
a5cf8f6e2003482fc9a9210ab5ef399330fc0ca8
2e8f3bf76c77970fd45c73c4f5f49518e2009649
v1.0
instruct
Data_Structure
Data_Structure_15352_I
**Implement BST Operations** You are required to implement a Binary Search Tree (BST) with the following functionalities: 1. **Insert a node** 2. **Search for a node** 3. **Delete a node** Your implementation should consist of the following functions: 1. `insert(root, val)`: Insert a value into the BST. - **Inpu...
class TreeNode: def __init__(self, key): self.left = None self.right = None self.val = key def insert(root, val): if root is None: return TreeNode(val) if val < root.val: root.left = insert(root.left, val) else: root.right = insert(root.right, val) ...
from solution import TreeNode, insert, search, deleteNode def tree_to_list(root): result = [] def inorder(node): if node: inorder(node.left) result.append(node.val) inorder(node.right) inorder(root) return result def test_insert(): root = None root =...
[]
[ 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 in...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015352", "row_id": 15352, "seed_ids": "[287]" }
0.537308
Data_Structure_15352
I
[ "insert", "search", "minValueNode", "deleteNode" ]
4
[ [ "deleteNode", "minValueNode" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
4a866ae2932bb1b72884901d545125450ae9ec54
18222181834305f4cb50ef3305375abb9db7ebb8
v1.0
instruct
Data_Structure
Data_Structure_15391_I
### Coding Problem: Endian Conversion Validator #### Problem Description You are required to write a function that verifies the correctness of integer-to-byte and byte-to-integer conversion processes. This function should validate that the original integer value remains the same after converting to bytes and back to a...
def int_to_bytes_big_endian(num): return num.to_bytes((num.bit_length() + 7) // 8, 'big') def int_to_bytes_little_endian(num): return num.to_bytes((num.bit_length() + 7) // 8, 'little') def bytes_big_endian_to_int(byte_data): return int.from_bytes(byte_data, 'big') def bytes_little_endian_to_int(byte_dat...
from solution import validate_endian_conversion def test_validate_endian_conversion_basic(): assert validate_endian_conversion(305419896) == True def test_validate_endian_conversion_zero(): assert validate_endian_conversion(0) == True def test_validate_endian_conversion_max_value(): assert validate_endia...
[ { "docstring": null, "function_declaration": "def int_to_bytes_big_endian(num):", "function_name": "int_to_bytes_big_endian", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def int_to_bytes_little_endian(num):", "function_name": "int_to_bytes_little_endian...
[ 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 int_to_bytes_big_endian(num, length=8):\n return num.to_bytes(length, byteorder='big')\n\ndef int_to_bytes_little_endian(num, length=8):\n return nu...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015391", "row_id": 15391, "seed_ids": "[216]" }
0.507839
Data_Structure_15391
I
[ "int_to_bytes_big_endian", "int_to_bytes_little_endian", "bytes_big_endian_to_int", "bytes_little_endian_to_int", "validate_endian_conversion" ]
5
[ [ "validate_endian_conversion", "bytes_big_endian_to_int" ], [ "validate_endian_conversion", "bytes_little_endian_to_int" ], [ "validate_endian_conversion", "int_to_bytes_big_endian" ], [ "validate_endian_conversion", "int_to_bytes_little_endian" ] ]
4
[]
false
[]
false
pytest
true
[]
true
f0acdfe0d47c351079a7538d635ebbf8f09d1602
a5e15a14fff1c520ecc4685469ab9febb631fc27
v1.0
instruct
Data_Structure
Data_Structure_15419_I
### Context: You are tasked with implementing a function to construct a Binary Search Tree (BST) from a given list of integers. The BST should satisfy the properties of a Binary Search Tree where, for each node, all elements in its left subtree are less than the node's value and all elements in the right subtree are gr...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def insert_into_bst(root, val): if root is None: return TreeNode(val) if val < root.val: root.left = insert_into_bst(root.left, val) else: ...
import pytest from solution import TreeNode, construct_bst, in_order_traversal def test_construct_bst(): nums = [5, 3, 1, 4, 7, 6, 8] root = construct_bst(nums) assert root.val == 5 assert root.left.val == 3 assert root.left.left.val == 1 assert root.left.right.val == 4 assert root.right.va...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef in...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015419", "row_id": 15419, "seed_ids": "[287]" }
0.543494
Data_Structure_15419
I
[ "insert_into_bst", "construct_bst", "in_order_traversal" ]
3
[ [ "construct_bst", "insert_into_bst" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
8d7f7b131d27717c86faaa75827d2eff04c0037f
b85b3ae1cdd8655b42791005e67c3c3e0cf2cd79
v1.0
instruct
Data_Structure
Data_Structure_15463_I
You are given an array of integers representing a stack of pancakes, each with a different diameter. Your task is to sort the pancakes in order of their size, with the smallest pancake at the top (index 0) and the largest at the bottom (index N-1). You can only flip pancakes from the top of the stack. A flip operatio...
def flip(arr, k): return arr[:k][::-1] + arr[k:] def find_max_index(arr, n): max_index = 0 for i in range(1, n): if arr[i] > arr[max_index]: max_index = i return max_index def pancake_sort(arr): n = len(arr) for size in range(n, 1, -1): max_index = find_max_index(ar...
from solution import pancake_sort def test_pancake_sort_empty(): assert pancake_sort([]) == [] def test_pancake_sort_single_element(): assert pancake_sort([1]) == [1] def test_pancake_sort_sorted_array(): assert pancake_sort([1, 2, 3, 4]) == [1, 2, 3, 4] def test_pancake_sort_reverse_sorted_array(): ...
[ { "docstring": null, "function_declaration": "def flip(arr, k):", "function_name": "flip", "parameter_list": "(arr, k)" }, { "docstring": null, "function_declaration": "def find_max_index(arr, n):", "function_name": "find_max_index", "parameter_list": "(arr, n)" }, { "doc...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def pancake_sort(arr):\n \"\"\"\n Sorts the array using the pancake sorting algorithm.\n \"\"\"\n \n def flip(sub_arr, k):\n \"\"\"Helpe...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015463", "row_id": 15463, "seed_ids": "[9]" }
0.705415
Data_Structure_15463
I
[ "flip", "find_max_index", "pancake_sort" ]
3
[ [ "pancake_sort", "find_max_index" ], [ "pancake_sort", "flip" ] ]
2
[]
false
[]
false
pytest
true
[]
true
57a9236cb74a70d52ef0f078163e1e26cf523414
834120a2ce1c2c2ac5aaec087784e90ee45799c9
v1.0
instruct
Data_Structure
Data_Structure_15540_I
You are given a sequence of integers and you must perform specific operations: finding the GCD and LCM of two numbers, and counting the trailing zeros in the binary representation of an integer. Furthermore, implement an optimized version of GCD using bitwise operations. ### Tasks: 1. Write a function `compute_gcd(a, ...
def compute_gcd(a, b): """ Compute the GCD (Greatest Common Divisor) of two integers using Euclid's Algorithm. :param a: First integer :param b: Second integer :return: GCD of a and b """ while b: a, b = b, a % b return a def compute_lcm(a, b): """ Compute the LCM (...
from solution import compute_gcd, compute_lcm, count_trailing_zeros, compute_gcd_bitwise def test_compute_gcd(): assert compute_gcd(48, 18) == 6 assert compute_gcd(100, 10) == 10 assert compute_gcd(7, 5) == 1 assert compute_gcd(0, 1) == 1 assert compute_gcd(1, 0) == 1 def test_compute_lcm(): a...
[ { "docstring": "Compute the GCD (Greatest Common Divisor) of two integers using Euclid's Algorithm.\n\n:param a: First integer\n:param b: Second integer\n:return: GCD of a and b", "function_declaration": "def compute_gcd(a, b):", "function_name": "compute_gcd", "parameter_list": "(a, b)" }, { ...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def compute_gcd(a, b):\n \"\"\"\n Returns the GCD of integers a and b using Euclid’s Algorithm.\n \"\"\"\n while b:\n a, b = b, a % b\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015540", "row_id": 15540, "seed_ids": "[166]" }
0.608879
Data_Structure_15540
I
[ "compute_gcd", "compute_lcm", "count_trailing_zeros", "compute_gcd_bitwise" ]
4
[ [ "compute_gcd_bitwise", "count_trailing_zeros" ], [ "compute_lcm", "compute_gcd" ] ]
2
[]
false
[]
false
pytest
true
[]
true
07598641e28e1e3f892f92a36b13355b742a8c77
2c77a6405d653a3eeba3e762c9d04b82d4b29276
v1.0
instruct
Data_Structure
Data_Structure_15542_I
### Scenario You are assisting in improving the performance of a startup's inventory management system. The current system works well with just a few hundred items but shows considerable lag as more items are added. You are asked to implement a function that sorts the list of items using the Insertion Sort algorithm, e...
from typing import List def binary_search_insert(arr: List[int], val: int, start: int, end: int) -> int: """ Binary search helper to find the correct insert position for val within arr[start:end] """ while start < end: mid = (start + end) // 2 if arr[mid] < val: start = mid ...
from solution import optimized_insertion_sort def test_sorted_list(): arr = [1, 2, 3, 4, 5] assert optimized_insertion_sort(arr) == [1, 2, 3, 4, 5] def test_reverse_sorted_list(): arr = [5, 4, 3, 2, 1] assert optimized_insertion_sort(arr) == [1, 2, 3, 4, 5] def test_unsorted_list(): arr = [4, 3, ...
[ { "docstring": "Binary search helper to find the correct insert position for val within arr[start:end]", "function_declaration": "def binary_search_insert(arr, val, start, end):", "function_name": "binary_search_insert", "parameter_list": "(arr, val, start, end)" }, { "docstring": "Sorts the...
[ 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 binary_search(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Helper function to perform binary search...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015542", "row_id": 15542, "seed_ids": "[7]" }
0.565969
Data_Structure_15542
I
[ "binary_search_insert", "optimized_insertion_sort" ]
2
[ [ "optimized_insertion_sort", "binary_search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e6702614db99128c31f2b7187785ed736571ab5b
ca4cb100fb0e75ea1224de47dc934817617f3fe3
v1.0
instruct
Data_Structure
Data_Structure_15565_I
### Question: Implement an Enhanced Radix Sort **Background**: You are tasked with implementing an enhanced version of Radix Sort. This sort algorithm is particularly beneficial for sorting large datasets of fixed-length integers due to its linear time complexity under these circumstances. However, to leverage Radix S...
from typing import List def enhanced_radix_sort(arr: List[int], simulation: bool = False) -> List[int]: """ Sorts a list of non-negative integers using Radix Sort with optional simulation/debugging. Args: arr (List[int]): The list of non-negative integers to sort. simulation (bool): If True, p...
import pytest from solution import enhanced_radix_sort def test_enhanced_radix_sort_standard(): assert enhanced_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_enhanced_radix_sort_small_numbers(): assert enhanced_radix_sort([5, 3, 8, 6, 2, 7, 4, 1]) == [1, 2, 3, 4, ...
[ { "docstring": "Sorts a list of non-negative integers using Radix Sort with optional simulation/debugging.\n\nArgs:\narr (List[int]): The list of non-negative integers to sort.\nsimulation (bool): If True, print debug information for each iteration.\n\nReturns:\nList[int]: The sorted list of integers in ascendi...
[ 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], simulation: bool = False) -> List[int]:\n if not arr:\n return []\n\n # Utilit...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015565", "row_id": 15565, "seed_ids": "[15]" }
0.631673
Data_Structure_15565
I
[ "enhanced_radix_sort", "counting_sort" ]
2
[ [ "enhanced_radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
06226da8770e0877e2e33b8c1da5b151f9ac8317
5fbf853adbed72a0427b147a8181051dc8d720f5
v1.0
instruct
Data_Structure
Data_Structure_15568_I
Enhanced Quick Sort Implementation **Scenario**: You have been hired by a tech company to optimize their data processing software. One critical module is responsible for sorting large datasets efficiently. The current implementation uses Quick Sort, and while performant, it encounters significant slowdowns in certain...
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 median_of_three(arr, left, right): mid = (left + right) // 2 a = arr[le...
from solution import enhanced_quick_sort def test_sorted_array(): assert enhanced_quick_sort([1, 2, 3, 4, 5, 6]) == [1, 2, 3, 4, 5, 6] def test_reverse_sorted_array(): assert enhanced_quick_sort([6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6] def test_random_array(): assert enhanced_quick_sort([3, 6, 1, 5, 2, ...
[ { "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"...
[ 0, 0, 0, 1, 1, 0, 1, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def enhanced_quick_sort(arr):\n \"\"\"\n Sorts the array using an optimized Quick Sort algorithm with median-of-three pivot selection and insertion sort...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00015568", "row_id": 15568, "seed_ids": "[25]" }
0.581532
Data_Structure_15568
I
[ "insertion_sort", "median_of_three", "quick_sort", "enhanced_quick_sort" ]
4
[ [ "enhanced_quick_sort", "quick_sort" ], [ "quick_sort", "insertion_sort" ], [ "quick_sort", "median_of_three" ] ]
3
[]
false
[]
false
pytest
true
[]
true
4b5b371d413d90aa830db443333d093a91c1c6c9
fcba00a5c29bf381b36854a9bc2fbee0f009c5fb
v1.0
instruct
Data_Structure
Data_Structure_15694_I
**Problem Statement**: You are given an integer array `nums`. Implement the `bogo_sort` function that sorts the array using the Bogo Sort algorithm—a highly inefficient sorting algorithm that randomly shuffles the array until it is sorted. This is mainly educational to understand algorithm inefficiency. The function ...
import random from typing import List def is_sorted(nums: List[int]) -> bool: """ Helper function to check if the list is sorted. """ for i in range(len(nums) - 1): if nums[i] > nums[i + 1]: return False return True def bogo_sort(nums: List[int], simulation: bool = False) -> Li...
from solution import bogo_sort def test_bogo_sort_sorted_input(): assert bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_bogo_sort_reversed_input(): assert bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_bogo_sort_unsorted_input(): assert bogo_sort([3, 2, 5, 1, 4]) == [1, 2, 3, 4, 5] def t...
[ { "docstring": "Helper function to check if the list is sorted.", "function_declaration": "def is_sorted(nums):", "function_name": "is_sorted", "parameter_list": "(nums)" }, { "docstring": "Function to sort the array using the Bogo Sort algorithm.\nIt shuffles the array until it gets sorted....
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List\n\ndef is_sorted(nums: List[int]) -> bool:\n \"\"\"\n Helper function to check if the list is sorted.\n \"\"\"...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00015694", "row_id": 15694, "seed_ids": "[16]" }
0.549989
Data_Structure_15694
I
[ "is_sorted", "bogo_sort" ]
2
[ [ "bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b342f47edc379b43243f1fc68cb916af9e44ff92
a268cc1420049c41131fe9b5f3fd95738a7f97ec
v1.0
instruct
Data_Structure
Data_Structure_15711_I
### Scenario You are given a city's road network represented as a directed graph, where intersections are nodes and roads are edges with certain capacities. Your task is to compute the maximum amount of traffic that can flow from the central intersection (source) to the main exit (sink) using the Ford-Fulkerson method ...
from collections import deque from typing import List def bfs(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool: """ Perform BFS to find a path from source to sink in the residual graph. Updates the parent array to store the path. Returns True if a path is found, ...
from solution import maximum_flow_bfs def test_maximum_flow_example(): graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] assert maximum_flow_bfs(graph) == 23 def test_maxi...
[ { "docstring": "Perform BFS to find a path from source to sink in the residual graph.\nUpdates the parent array to store the path.\n\nReturns True if a path is found, False otherwise.", "function_declaration": "def bfs(residual_graph, source, sink, parent):", "function_name": "bfs", "parameter_list"...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\nfrom typing import List\n\ndef bfs(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n \"...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015711", "row_id": 15711, "seed_ids": "[229]" }
0.54492
Data_Structure_15711
I
[ "bfs", "maximum_flow_bfs" ]
2
[ [ "maximum_flow_bfs", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9d12b2f002510cbef9af0a8fc9abfd391cfdbee5
c6d956740aa213c88015c1bd305d0ac8aab8f466
v1.0
instruct
Data_Structure
Data_Structure_15726_I
### Kruskal's Algorithm: Find the Minimum Spanning Tree #### Problem Statement: Given a connected, undirected graph with `n` vertices and `m` edges, find the Minimum Spanning Tree (MST) of the graph using Kruskal’s algorithm and compute the sum of the weights of the edges in this MST. #### Input: * The first line con...
def find(parent, i): if parent[i] == i: return i else: return find(parent, parent[i]) def union(parent, rank, x, y): xroot = find(parent, x) yroot = find(parent, y) if rank[xroot] < rank[yroot]: parent[xroot] = yroot elif rank[xroot] > rank[yroot]: parent[yr...
from solution import kruskal def test_simple_graph(): assert kruskal(5, [ (1, 2, 3), (1, 3, 8), (2, 4, 5), (3, 4, 2), (3, 5, 4), (4, 5, 6) ]) == 14 def test_single_edge(): assert kruskal(2, [ (1, 2, 1) ]) == 1 def test_disconnected_graph(): # Even though the problem guara...
[ { "docstring": null, "function_declaration": "def find(parent, i):", "function_name": "find", "parameter_list": "(parent, i)" }, { "docstring": null, "function_declaration": "def union(parent, rank, x, y):", "function_name": "union", "parameter_list": "(parent, rank, x, y)" }, ...
[ 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 find(parent, i):\n if parent[i] == i:\n return i\n else:\n return find(parent, parent[i])\n\ndef union(parent, rank, x, y):\n xroot...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00015726", "row_id": 15726, "seed_ids": "[230]" }
0.815446
Data_Structure_15726
I
[ "find", "union", "kruskal" ]
3
[ [ "kruskal", "find" ], [ "kruskal", "union" ], [ "union", "find" ] ]
3
[]
false
[]
false
pytest
true
[]
true
753a0d9ffecd0887446507275489beedecce2931
aee1eb012fddf0e6254462d1079b632ead47d0f1
v1.0
instruct
Data_Structure
Data_Structure_15749_I
### Question: Optimizing Quick Sort for Improved Performance The QuickSort algorithm is efficient for sorting large datasets but suffers from poor performance in certain cases, such as when the input array is already sorted or contains many duplicate elements. A common optimization involves using the "median-of-three"...
def insertion_sort(arr, low, high): for i in range(low + 1, high + 1): key = arr[i] j = i - 1 while j >= low and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def median_of_three(arr, low, mid, high): if arr[low] > arr[mid]: arr[low], ...
from solution import optimized_quick_sort def test_sorted_array(): arr = [1, 2, 3, 4, 5] sorted_arr = optimized_quick_sort(arr, 3) assert sorted_arr == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): arr = [5, 4, 3, 2, 1] sorted_arr = optimized_quick_sort(arr, 3) assert sorted_arr == [1, 2, 3...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr, low, high):", "function_name": "insertion_sort", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def median_of_three(arr, low, mid, high):", "function_name": "median_of_three",...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def insertion_sort(arr, low, high):\n for i in range(low + 1, high + 1):\n key = arr[i]\n j = i - 1\n while j >= low and arr[j] > key:...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00015749", "row_id": 15749, "seed_ids": "[25]" }
0.555074
Data_Structure_15749
I
[ "insertion_sort", "median_of_three", "partition", "quick_sort", "optimized_quick_sort" ]
5
[ [ "optimized_quick_sort", "quick_sort" ], [ "partition", "median_of_three" ], [ "quick_sort", "insertion_sort" ], [ "quick_sort", "partition" ] ]
4
[]
false
[]
false
pytest
true
[]
true
3a1373aba51547227ff6330b0283df8b21ba3cae
7c5861c704d213d936f2e28a2c1649e1f238edbf
v1.0
instruct
Data_Structure
Data_Structure_15781_I
### Task Description Design a function `compare_serializations` that takes the root of two binary trees and returns `True` if their serialized forms are identical, otherwise return `False`. This function will help ensure consistency in tree structure and node values between two trees. ### Requirements * **Function Sig...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def serialize(root): """Encodes a tree to a single string.""" if not root: return "None" return f"{root.val},{serialize(root.left)},{serialize(root.right)...
from solution import TreeNode, compare_serializations def test_compare_serializations_identical_trees(): # Tree 1: 1 # / \ # 2 3 # / \ # 4 5 root1 = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5))) # Tre...
[]
[ 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 se...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015781", "row_id": 15781, "seed_ids": "[330]" }
0.51649
Data_Structure_15781
I
[ "serialize", "compare_serializations" ]
2
[ [ "compare_serializations", "serialize" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
5f7488c9dd00231ab9a69aeea3eed13d8f7faa7d
e949354227614f061ef24feb37290ae04cc15081
v1.0
instruct
Data_Structure
Data_Structure_15842_I
### Bogo Sort Challenge In this challenge, you are asked to implement a highly inefficient sorting algorithm known as Bogo Sort. While this algorithm serves more as a cautionary tale of inefficiency, it provides a useful educational example of randomness in algorithmic operations. ### Task Write a function `bogo_sort...
import random import time def is_sorted(arr): for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort_optimized(arr, max_attempts=1000000): """ Sorts an array using Bogo Sort algorithm with an upper limit on shuffle attempts. Parameters: ...
from solution import bogo_sort_optimized def test_bogo_sort_optimized_sorted_list(): assert bogo_sort_optimized([1, 2, 3, 4]) == [1, 2, 3, 4] def test_bogo_sort_optimized_reverse_list(): assert bogo_sort_optimized([4, 3, 2, 1]) == [1, 2, 3, 4] def test_bogo_sort_optimized_unsorted_list(): sorted_list = b...
[ { "docstring": null, "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts an array using Bogo Sort algorithm with an upper limit on shuffle attempts.\n\nParameters:\narr (list): The list of integers to sort.\nmax_atte...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.111
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl", "solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"Helper function to check if the array is sorted.\"\"\"\n return all(arr[i] <= arr[...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00015842", "row_id": 15842, "seed_ids": "[16]" }
0.615083
Data_Structure_15842
I
[ "is_sorted", "bogo_sort_optimized" ]
2
[ [ "bogo_sort_optimized", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bbd2cbe7673ca27d0acf662a73906f59f8b1166d
5881d6a190d4f834c775dc9d0424de2fb15a3b1c
v1.0
instruct
Data_Structure
Data_Structure_15899_I
You are given an array of strings `strs`. Write a function `longestCommonPrefix(strs)` to find the longest common prefix string among these strings. #### Input: - An array of strings `strs` (1 ≤ length of each string ≤ 200, 1 ≤ number of strings ≤ 200). #### Output: - A single string that represents the longest commo...
def longestCommonPrefix_horizontal_scanning(strs): """ Finds the longest common prefix among a list of strings using horizontal scanning. """ if not strs: return "" prefix = strs[0] for string in strs[1:]: while string[:len(prefix)] != prefix: prefix = prefix[:-1] ...
from solution import longestCommonPrefix, longestCommonPrefix_horizontal_scanning, longestCommonPrefix_vertical_scanning def test_longestCommonPrefix_example1(): assert longestCommonPrefix(["flower", "flow", "flight"]) == "fl" def test_longestCommonPrefix_example2(): assert longestCommonPrefix(["dog", "raceca...
[ { "docstring": "Finds the longest common prefix among a list of strings using horizontal scanning.", "function_declaration": "def longestCommonPrefix_horizontal_scanning(strs):", "function_name": "longestCommonPrefix_horizontal_scanning", "parameter_list": "(strs)" }, { "docstring": "Finds t...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def longestCommonPrefix_horizontal_scanning(strs):\n \"\"\"\n Finds the longest common prefix among a list of strings using horizontal scanning.\n \"...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00015899", "row_id": 15899, "seed_ids": "[67]" }
0.828266
Data_Structure_15899
I
[ "longestCommonPrefix_horizontal_scanning", "longestCommonPrefix_vertical_scanning", "longestCommonPrefix" ]
3
[ [ "longestCommonPrefix", "longestCommonPrefix_horizontal_scanning" ] ]
1
[]
false
[]
false
pytest
true
[]
true
627476673da94fa5d2f68602ad5f20bc4a1540a5
763a87a3a8938f1e5be766cc6f0f410d8fbd5113
v1.0
instruct
Data_Structure
Data_Structure_15937_I
**Radix Sort Implementation and Enhancements** In this exercise, you are required to implement the Radix Sort algorithm, as well as handle some additional constraints to test your understanding of the algorithm. #### Task 1. Implement the `radix_sort` function to sort an input list of non-negative integers. 2. Enhanc...
from typing import List def counting_sort(arr, exp, simulation): n = len(arr) output = [0] * n count = [0] * 10 # Store count of occurrences in count[] for i in range(n): index = (arr[i] // exp) count[index % 10] += 1 # Change count[i] so that count[i] contains actual position...
from solution import radix_sort def test_radix_sort_basic(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_with_empty_list(): assert radix_sort([]) == [] def test_radix_sort_single_element(): assert radix_sort([5]) == [5] def test_radix_sor...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp, simulation):", "function_name": "counting_sort", "parameter_list": "(arr, exp, simulation)" }, { "docstring": null, "function_declaration": "def radix_sort(arr, simulation=False):", "function_name": "radix_sort...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def radix_sort(arr, simulation=False):\n \"\"\"\n Perform radix sort on a list of non-negative integers.\n \n Parameters:\n arr (List[int]): A ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015937", "row_id": 15937, "seed_ids": "[15]" }
0.632493
Data_Structure_15937
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f5d43729e301f83e728fda3a43fd645611f28f39
6ec3a78060c8fed05aee16c1361672ff518b5e21
v1.0
instruct
Data_Structure
Data_Structure_15941_I
You are to implement a modified version of the RSA encryption algorithm that ensures better performance for key generation and encryption/decryption process. Specifically, you will use efficient algorithms for selecting prime numbers and calculating the modular multiplicative inverse. ### Requirements * Implement an e...
from typing import Tuple import random import sympy def is_prime(num: int) -> bool: return sympy.isprime(num) def generate_large_prime(bits: int) -> int: while True: candidate = random.getrandbits(bits) if is_prime(candidate): return candidate def egcd(a: int, b: int) -> Tuple[int...
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 e == 65537 def test_encryption_decryption(): n, e, d = generate_key(16, seed=42) data = 12...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def generate_large_prime(bits):", "function_name": "generate_large_prime", "parameter_list": "(bits)" }, ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import Tuple\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime(bits: int) -> int:\n \"\"\"Generate a prime number wi...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015941", "row_id": 15941, "seed_ids": "[154]" }
0.520002
Data_Structure_15941
I
[ "is_prime", "generate_large_prime", "egcd", "modinv", "generate_key", "encrypt", "decrypt" ]
7
[ [ "generate_key", "generate_large_prime" ], [ "generate_key", "modinv" ], [ "generate_large_prime", "is_prime" ], [ "modinv", "egcd" ] ]
4
[]
false
[]
false
pytest
true
[ "sympy" ]
false
6411f1f67ac519dcdbd28bc80265643609380384
c5bba33405ca071444bf149086e8ac5642348fe9
v1.0
instruct
Data_Structure
Data_Structure_15943_I
### Scenario Bogo Sort is known for its simplicity and serves as a fun example in theoretical computer science. However, due to its inefficiency, you'll rarely, if ever, use it in practical applications. Nevertheless, it provides good practice for understanding sorting algorithms and probabilistic processes. ### Probl...
import random def is_sorted(arr): """ Helper function to check if the array is sorted """ return all(arr[i] <= arr[i+1] for i in range(len(arr)-1)) def constrained_bogo_sort(arr, max_iterations): """ Sorts the array using Bogo Sort method. Parameters: arr (list[int]): The list of integers...
from solution import constrained_bogo_sort def test_sorted_case(): assert constrained_bogo_sort([1, 2, 3], 1000) == [1, 2, 3] def test_single_element(): assert constrained_bogo_sort([1], 10) == [1] def test_empty_list(): assert constrained_bogo_sort([], 10) == [] def test_reversed_list(): result = c...
[ { "docstring": "Helper function to check if the array is sorted ", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts the array using Bogo Sort method.\n\nParameters:\narr (list[int]): The list of integers to sort.\...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Checks if the array is sorted in non-decreasing order.\n \"\"\"\n return all(arr[i] <= arr[i+1] fo...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015943", "row_id": 15943, "seed_ids": "[16]" }
0.541445
Data_Structure_15943
I
[ "is_sorted", "constrained_bogo_sort" ]
2
[ [ "constrained_bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
98f9e8333578e176e9942473bf658ed0fc15d57c
96f88e9f69637a880f77cb99ee1706963d285629
v1.0
instruct
Data_Structure
Data_Structure_15945_I
### Question: Implement and Analyze Radix Sort Your task is to implement the Radix Sort algorithm to sort a list of non-negative integers. You have been given an unsorted array of integers, and you are required to output a sorted array. ### Requirements: 1. Implement the provided `radix_sort` function to sort a list...
from typing import List def counting_sort(arr, exp, simulation): n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = (arr[i] // exp) % 10 count[index] += 1 for i in range(1, 10): count[i] += count[i - 1] for i in range(n - 1, -1, -1): ind...
from solution import radix_sort def test_radix_sort_on_empty(): assert radix_sort([]) == [] def test_radix_sort_on_single_element(): assert radix_sort([1]) == [1] def test_radix_sort_on_identical_elements(): assert radix_sort([7, 7, 7, 7]) == [7, 7, 7, 7] def test_radix_sort_on_multiple_elements(): ...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp, simulation):", "function_name": "counting_sort", "parameter_list": "(arr, exp, simulation)" }, { "docstring": null, "function_declaration": "def radix_sort(arr, simulation=False):", "function_name": "radix_sort...
[ 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 counting_sort(arr: List[int], exp: int, simulation: bool) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015945", "row_id": 15945, "seed_ids": "[15]" }
0.660776
Data_Structure_15945
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0cc3480db947cbba15121155685f6a5c1280d9ea
0327b6e6f788b1cca478f805d7bc424d4a43f9f3
v1.0
instruct
Data_Structure
Data_Structure_15991_I
You are tasked with improving the given nearest neighbor classifier by addressing some of its limitations and ensuring efficiency in high-dimensional data. Specifically, you should enhance the performance of the nearest neighbor search algorithm. ### Task Implement a nearest neighbor search function that: 1. Uses a KD...
from collections import namedtuple import math KDTreeNode = namedtuple('KDTreeNode', ['point', 'left', 'right']) def build_kd_tree(points, depth=0): if not points: return None k = len(points[0]) # Assume all points have the same dimension axis = depth % k points.sort(key=lambda x: x...
from solution import build_kd_tree, kd_tree_nearest_neighbor def test_kd_tree_construction(): points = [(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)] kd_tree = build_kd_tree(points) assert kd_tree.point == (7, 2) def test_kd_tree_nearest_neighbor_basic(): points = [(2, 3), (5, 4), (9, 6), (4, 7), (8...
[ { "docstring": null, "function_declaration": "def build_kd_tree(points, depth=0):", "function_name": "build_kd_tree", "parameter_list": "(points, depth=0)" }, { "docstring": null, "function_declaration": "def distance_squared(p1, p2):", "function_name": "distance_squared", "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 collections import namedtuple\nimport math\n\nKDTreeNode = namedtuple('KDTreeNode', ['point', 'left', 'right'])\n\ndef build_kd_tree(points, depth=0):\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00015991", "row_id": 15991, "seed_ids": "[260]" }
0.637578
Data_Structure_15991
I
[ "build_kd_tree", "distance_squared", "kd_tree_nearest_neighbor" ]
3
[ [ "kd_tree_nearest_neighbor", "distance_squared" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c3343280968705b9415bf9ba305940379d95a869
e4827b569182e18712c55efae8a3e5d38cf32c73
v1.0
instruct
Data_Structure
Data_Structure_16007_I
### Question: Maximum Flow Network Optimization You are tasked with optimizing a network flow in an urban transportation system. Given a directed graph representing the transportation network with nodes as junctions and edges as roads with certain capacities, you are required to compute the maximum possible flow from ...
from typing import List def bfs(capacity, source, sink, parent): visited = [False] * len(capacity) queue = [] queue.append(source) visited[source] = True while queue: u = queue.pop(0) for idx, val in enumerate(capacity[u]): if visited[idx] == False and val > 0: ...
from solution import optimized_max_flow def test_optimized_max_flow_example1(): 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 opti...
[ { "docstring": null, "function_declaration": "def bfs(capacity, source, sink, parent):", "function_name": "bfs", "parameter_list": "(capacity, source, sink, parent)" }, { "docstring": null, "function_declaration": "def optimized_max_flow(capacity, source, sink):", "function_name": "o...
[ 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 bfs(capacity, source, sink, parent):\n visited = [False] * len(capacity)\n queue = []\n queue.append(source)\n visi...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016007", "row_id": 16007, "seed_ids": "[240]" }
0.626039
Data_Structure_16007
I
[ "bfs", "optimized_max_flow" ]
2
[ [ "optimized_max_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c12ac6f431656a0e1db669b88375a70addac53c2
9ee2d74066165a6a07c649f8a144891b2d200b74
v1.0
instruct
Data_Structure
Data_Structure_16014_I
### Run-Length Encoding and Decoding You are provided with two functions: `encode_rle` and `decode_rle`, which perform run-length encoding and decoding, respectively. Your task is to implement additional functionalities to enhance the Run-Length Encoding. Implement a function `optimized_encode_rle(input)` that perfor...
def optimized_encode_rle(input: str) -> str: """ Perform run-length encoding on the input string, optimized for large inputs. """ if not input: return '' encoded_string = [] count = 1 prev_char = input[0] for char in input[1:]: if char == prev_char: ...
from solution import optimized_encode_rle, verify_decode_rle, decode_rle def test_optimized_encode_rle_empty_string(): assert optimized_encode_rle('') == '' def test_optimized_encode_rle_single_char(): assert optimized_encode_rle('a') == '1a' assert optimized_encode_rle('aaaaa') == '5a' def test_optimize...
[ { "docstring": "Perform run-length encoding on the input string, optimized for large inputs.", "function_declaration": "def optimized_encode_rle(input):", "function_name": "optimized_encode_rle", "parameter_list": "(input)" }, { "docstring": "Decode a run-length encoded string.", "functi...
[ 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 optimized_encode_rle(input: str) -> str:\n \"\"\"\n This function performs run-length encoding on the input string in an optimized manner.\n \"\"...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016014", "row_id": 16014, "seed_ids": "[334]" }
0.664569
Data_Structure_16014
I
[ "optimized_encode_rle", "decode_rle", "verify_decode_rle" ]
3
[ [ "verify_decode_rle", "decode_rle" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b6b8b6e9f0479c672cf040bac8fc2258ed6f8798
faa5222b9534124b482aa5f79ccad65c7156b4e8
v1.0
instruct
Data_Structure
Data_Structure_16015_I
### Roman Numeral Validation and Conversion You have been given a function `roman_to_int` that converts a Roman numeral string into its corresponding integer value. This function assumes that the given Roman numeral string is always valid and within the range from 1 to 3999. However, in real-world scenarios, input va...
def validate_roman(s: str) -> bool: valid_chars = {'I', 'V', 'X', 'L', 'C', 'D', 'M'} if not s: return False if any(char not in valid_chars for char in s): return False invalid_repeats = ["IIII", "VV", "XXXX", "LL", "CCCC", "DD", "MMMM"] for repeat in invalid_repeats: ...
from solution import validate_roman, roman_to_int def test_validate_roman_valid(): assert validate_roman("MCMXCIV") == True assert validate_roman("III") == True assert validate_roman("MMXXII") == True def test_validate_roman_invalid(): assert validate_roman("IIII") == False assert validate_roman("...
[ { "docstring": null, "function_declaration": "def validate_roman(s):", "function_name": "validate_roman", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def roman_to_int(s):", "function_name": "roman_to_int", "parameter_list": "(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 validate_roman(s: str) -> bool:\n \"\"\"\n Validates a Roman numeral string.\n Returns True if the string is a valid Roman numeral, otherwise Fal...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016015", "row_id": 16015, "seed_ids": "[82]" }
0.698149
Data_Structure_16015
I
[ "validate_roman", "roman_to_int" ]
2
[ [ "roman_to_int", "validate_roman" ] ]
1
[]
false
[]
false
pytest
true
[]
true
737f913d02a3d0ab167d0ed0c42f5b81e26e6d76
59c76c406d00fbf3fb8fa21cf02c29e3473e13aa
v1.0
instruct
Data_Structure
Data_Structure_16095_I
### String Matching with Enhanced Error Handling Implement an enhanced version of the Knuth-Morris-Pratt (KMP) string matching algorithm. Your task is to write a function `kmp_search_with_validation` that: 1. Enhances the provided `knuth_morris_pratt` algorithm by handling additional edge cases and validating inputs....
from typing import Sequence, List def compute_lps(pattern: Sequence) -> List[int]: """ Compute the longest prefix suffix (LPS) array used to skip characters while matching. """ lps = [0] * len(pattern) j = 0 # length of the previous longest prefix suffix for i in range(1, len(pattern)): ...
import pytest from solution import kmp_search_with_validation def test_kmp_empty_text(): assert kmp_search_with_validation("", "a") == [] def test_kmp_empty_pattern(): assert kmp_search_with_validation("a", "") == [] def test_kmp_pattern_longer_than_text(): assert kmp_search_with_validation("a", "aa") ==...
[ { "docstring": "Compute the longest prefix suffix (LPS) array used to\nskip characters while matching.", "function_declaration": "def compute_lps(pattern):", "function_name": "compute_lps", "parameter_list": "(pattern)" }, { "docstring": "Enhanced version of the KMP string matching algorithm...
[ 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 Sequence, List\n\ndef build_lps(pattern: Sequence) -> List[int]:\n \"\"\"\n Build the longest prefix that is also suffix array (LPS) ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016095", "row_id": 16095, "seed_ids": "[93]" }
0.621919
Data_Structure_16095
I
[ "compute_lps", "kmp_search_with_validation" ]
2
[ [ "kmp_search_with_validation", "compute_lps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0eda1cb9a0a7817e0a77eaa4711bfac7661542f9
ca12dd54acc2917de770980b7ef5eba52a4e875d
v1.0
instruct
Data_Structure
Data_Structure_16150_I
### Problem Description You are given a task to compute the n-th Fibonacci number using different methods. The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1 F(n) = F(n-1) + F(n-2) for n >= 2 Write a function `compute_fibonacci` that takes an integer n and a string method as input. The method c...
def compute_fibonacci(n, method): """ Compute the n-th Fibonacci number using the specified method. Parameters: n (int): The index in the Fibonacci sequence. method (str): The method to use for computation ("recursive", "dynamic", "iterative"). Returns: int: The n-th Fibonacci numb...
def test_compute_fibonacci_recursive(): assert compute_fibonacci(10, "recursive") == 55 assert compute_fibonacci(0, "recursive") == 0 assert compute_fibonacci(1, "recursive") == 1 assert compute_fibonacci(5, "recursive") == 5 def test_compute_fibonacci_dynamic(): assert compute_fibonacci(100, "dyna...
[ { "docstring": "Compute the n-th Fibonacci number using the specified method.\n\nParameters:\nn (int): The index in the Fibonacci sequence.\nmethod (str): The method to use for computation (\"recursive\", \"dynamic\", \"iterative\").\n\nReturns:\nint: The n-th Fibonacci number.", "function_declaration": "de...
[ 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 compute_fibonacci(n, method):\n \"\"\"\n Computes the n-th Fibonacci number using given method (recursive, dynamic, or iterative).\n \n :param...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016150", "row_id": 16150, "seed_ids": "[37]" }
0.734705
Data_Structure_16150
I
[ "compute_fibonacci", "fibonacci_recursive", "fibonacci_dynamic", "fibonacci_iterative" ]
4
[ [ "compute_fibonacci", "fibonacci_dynamic" ], [ "compute_fibonacci", "fibonacci_iterative" ], [ "compute_fibonacci", "fibonacci_recursive" ] ]
3
[]
false
[]
false
pytest
false
[]
true
13518371d012cfbdff6e33eccc0ad267353b6fe6
dfde0d027667e32d96df07eace4a677ba9b96522
v1.0
instruct
Data_Structure
Data_Structure_16157_I
You have been given two integers, `num1` and `num2`. Your task is to compute three values `s`, `t`, and `g` such that: ```plaintext num1 * s + num2 * t = g ``` where `g` is the Greatest Common Divisor (GCD) of `num1` and `num2`, and `s` and `t` are Bézout's coefficients. Write a function `solve_bezout(num1: int, num2...
from typing import Tuple def extended_gcd(a: int, b: int) -> Tuple[int, int, int]: """ Uses the Extended Euclidean Algorithm to find the Bezout coefficients (s, t) and the greatest common divisor (g) of the integers a and b. """ if b == 0: return (1, 0, a) else: s, t, g = extend...
from solution import solve_bezout def test_solve_bezout_standard(): assert solve_bezout(30, 12) == (1, -2, 6) def test_solve_bezout_both_zero(): assert solve_bezout(0, 0) == (0, 0, 0) def test_solve_bezout_num1_zero(): assert solve_bezout(0, 25) == (0, 1, 25) def test_solve_bezout_num2_zero(): asser...
[ { "docstring": "Uses the Extended Euclidean Algorithm to find the Bezout coefficients (s, t) and the\ngreatest common divisor (g) of the integers a and b.", "function_declaration": "def extended_gcd(a, b):", "function_name": "extended_gcd", "parameter_list": "(a, b)" }, { "docstring": "Solve...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def extended_gcd(a, b):\n if b == 0:\n return (1, 0, a) if a >= 0 else (-1, 0, -a)\n else:\n s, t, g = extended_gcd(b, a % b)\n ret...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00016157", "row_id": 16157, "seed_ids": "[156]" }
0.610708
Data_Structure_16157
I
[ "extended_gcd", "solve_bezout" ]
2
[ [ "solve_bezout", "extended_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
824d239149b5b52d2aa62aeb80135d2e505ac5c5
feba48b39ca8b8bf36aff6e0083a48fef32d7804
v1.0
instruct
Data_Structure
Data_Structure_16188_I
### Problem: Efficient Insertion Sort #### Scenario: You have been hired by a tech company to optimize their sorting module, which frequently needs to sort small or nearly sorted datasets. Your task is to implement an improved version of the Insertion Sort algorithm that exploits a binary search technique to find the ...
def search_insert(array, val): low = 0 high = len(array) - 1 while low <= high: mid = low + (high - low) // 2 if val > array[mid]: low = mid + 1 else: high = mid - 1 return low def insertion_sort(array): """ Sorts the given list of integers using ...
from solution import insertion_sort, search_insert def test_insertion_sort_example_cases(): assert insertion_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9] assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] assert insertion_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert insertion_sort([]) == []...
[ { "docstring": null, "function_declaration": "def search_insert(array, val):", "function_name": "search_insert", "parameter_list": "(array, val)" }, { "docstring": "Sorts the given list of integers using an improved insertion sort algorithm with binary search\nfor finding the insertion point...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def search_insert(array, val):\n low = 0\n high = len(array) - 1\n while low <= high:\n mid = low + (high - low) // 2\n if val > array[...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016188", "row_id": 16188, "seed_ids": "[199]" }
0.558431
Data_Structure_16188
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a416b39905ad6173ba46028a5cc5667a05385a66
74c5293b4bb73ef10a190f105b41d3b1be6196e1
v1.0
instruct
Data_Structure
Data_Structure_16216_I
Implement and Analyze Bogo Sort #### Background: Bogo Sort (also known as Monkey Sort) is a highly inefficient sorting algorithm that works by randomly shuffling an array until it is sorted. While impractical, it serves as a theoretical exploration of algorithm performance and randomness. #### Problem Statement: You ...
import random def is_sorted(arr): """ Helper function to check if the array is sorted. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort(arr, simulation=False): """ Function that implements Bogo Sort. Parameters: ...
from solution import bogo_sort def test_bogo_sort_empty(): assert bogo_sort([]) == [] def test_bogo_sort_single_element(): assert bogo_sort([1]) == [1] def test_bogo_sort_already_sorted(): assert bogo_sort([1, 2, 3]) == [1, 2, 3] def test_bogo_sort_reverse_sorted(): result = bogo_sort([3, 2, 1]) ...
[ { "docstring": "Helper function to check if the array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Function that implements Bogo Sort.\n\nParameters:\narr (list): List of integers to be sorted.\nsimulat...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Checks if the given list is sorted in ascending order.\n \"\"\"\n for i in range(len(arr)-1):\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016216", "row_id": 16216, "seed_ids": "[16]" }
0.602718
Data_Structure_16216
I
[ "is_sorted", "bogo_sort" ]
2
[ [ "bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
774b90c17f489027b85b0a4bec48ea680a734d76
bfb965ec1303d0780e76c58d9b73419e7b67481f
v1.0
instruct
Data_Structure
Data_Structure_16298_I
### Question You are tasked with implementing a function to determine if one binary tree is a subtree of another binary tree. Given two binary trees `big` and `small`, write a function `is_subtree(big, small)` that returns `True` if `small` is a subtree of `big`, and `False` otherwise. #### Input - `big`: The root nod...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_subtree(big: TreeNode, small: TreeNode) -> bool: if not small: return True # An empty tree is always a subtree if not big: return False # big...
from solution import TreeNode, is_subtree, are_identical def test_is_subtree(): # Test case 1: # big: 3 # / \ # 4 5 # / \ # 1 2 # small: 4 # / \ # 1 2 big = TreeNode(3) big.left = TreeNode(4) big.right = TreeNo...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016298", "row_id": 16298, "seed_ids": "[288]" }
0.610158
Data_Structure_16298
I
[ "is_subtree", "are_identical" ]
2
[ [ "is_subtree", "are_identical" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
8a80dc2999f0fd377dc30fbf8d66d95269184a60
1060dba30b70f3544b0e04427b65910d7ac8e62e
v1.0
instruct
Data_Structure
Data_Structure_16318_I
### Scenario You are given the task of developing a simple recommendation system. The recommendation system utilizes the nearest neighbor algorithm to recommend the most similar items to a user based on their preference vector. ### Task Implement a function `recommend` that takes a user preference vector and a diction...
import math def euclidean_distance(vec1, vec2): """ Computes the Euclidean distance between two vectors. """ return math.sqrt(sum((x - y) ** 2 for x, y in zip(vec1, vec2))) def recommend(user_vector: tuple, item_dict: dict) -> str: """ Recommends the closest item to the user vector from the it...
from solution import recommend def test_recommend_single_item(): user_vector = (1, 2, 3) item_dict = {(1, 2, 3): 'Item A'} assert recommend(user_vector, item_dict) == 'Item A' def test_recommend_multiple_items(): user_vector = (1, 2, 3) item_dict = { (2, 2, 2): 'Item A', (1, 2, 1):...
[ { "docstring": "Computes the Euclidean distance between two vectors.", "function_declaration": "def euclidean_distance(vec1, vec2):", "function_name": "euclidean_distance", "parameter_list": "(vec1, vec2)" }, { "docstring": "Recommends the closest item to the user vector from the item dictio...
[ 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 math\n\ndef recommend(user_vector: tuple, item_dict: dict) -> str:\n \"\"\"\n Recommends the item closest to the user's preference vector from th...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00016318", "row_id": 16318, "seed_ids": "[260]" }
0.581418
Data_Structure_16318
I
[ "euclidean_distance", "recommend" ]
2
[ [ "recommend", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3963f94c24846d42382581e410c9ecfe742e9fd9
819a642815a73d6e31379550f42bf8cc2cc4a3fc
v1.0
instruct
Data_Structure
Data_Structure_16337_I
#### Problem Statement You have been tasked with implementing a custom sorting algorithm that efficiently sorts an array of floating-point numbers. The sorting technique you're implementing is a variation of the Bucket Sort, using a specified secondary sorting algorithm within each bucket. Your goal is to complete th...
def selection_sort(arr): """ Performs selection sort on the given list. """ n = len(arr) for i in range(n - 1): min_index = i for j in range(i + 1, n): if arr[j] < arr[min_index]: min_index = j arr[i], arr[min_index] = arr[min_index], arr[i] def b...
from solution import bucket_sort def test_bucket_sort_example_case(): arr = [0.23, 0.45, 0.12, 0.68, 0.34] expected = [0.12, 0.23, 0.34, 0.45, 0.68] assert bucket_sort(arr) == expected def test_bucket_sort_already_sorted(): arr = [0.1, 0.2, 0.3, 0.4, 0.5] expected = [0.1, 0.2, 0.3, 0.4, 0.5] a...
[ { "docstring": "Performs selection sort on the given list.", "function_declaration": "def selection_sort(arr):", "function_name": "selection_sort", "parameter_list": "(arr)" }, { "docstring": "Sorts an array of floating-point numbers using the Bucket Sort algorithm with Selection Sort as the...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def bucket_sort(arr):\n \"\"\"\n Sorts an array of floating-point numbers using the Bucket Sort algorithm with Selection Sort as the secondary sorting m...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016337", "row_id": 16337, "seed_ids": "[26]" }
0.588795
Data_Structure_16337
I
[ "selection_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "selection_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a82fac65c24cb186e9e327187ec8e92b62ece73a
1cf0704e13b2bedfd46ada25595aa5de888d4714
v1.0
instruct
Data_Structure
Data_Structure_16384_I
### Polynomial Addition, Multiplication, and Evaluation You are given two classes, `Monomial` and `Polynomial`, which represent mathematical monomials and polynomials. Your task is to add a feature to handle the addition of polynomials and multiply them efficiently. Furthermore, you need to provide a method to evaluat...
from typing import List, Tuple, Dict, Union from fractions import Fraction from collections import defaultdict def combine_monomials(monomials): combined = defaultdict(Fraction) for vars_exp, coeff in monomials: vars_exp_tuple = tuple(sorted(vars_exp.items())) combined[vars_exp_tuple] += Fracti...
from solution import add_polynomials, multiply_polynomials, evaluate_polynomial from fractions import Fraction def test_add_polynomials(): p1 = [({1: 1}, 3), ({2: 2}, 4)] p2 = [({1: 1}, 2), ({2: 1}, 5)] assert add_polynomials(p1, p2) == [({1: 1}, 5), ({2: 2}, 4), ({2: 1}, 5)] def test_add_polynomials_with...
[ { "docstring": null, "function_declaration": "def combine_monomials(monomials):", "function_name": "combine_monomials", "parameter_list": "(monomials)" }, { "docstring": null, "function_declaration": "def add_polynomials(p1, p2):", "function_name": "add_polynomials", "parameter_l...
[ 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 fractions import Fraction\nfrom collections import defaultdict\nfrom typing import List, Tuple, Dict, Union\n\ndef add_polynomials(p1: List[Tuple[Dict[in...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016384", "row_id": 16384, "seed_ids": "[157]" }
0.632663
Data_Structure_16384
I
[ "combine_monomials", "add_polynomials", "multiply_polynomials", "evaluate_polynomial" ]
4
[ [ "add_polynomials", "combine_monomials" ], [ "multiply_polynomials", "combine_monomials" ] ]
2
[]
false
[]
false
pytest
true
[]
true
180b82e0f4c2af0db1476a4e5148311dd2df7f4f
28d1be6d1dff29b17ec921aae2c34b6fc9463ff5
v1.0
instruct
Data_Structure
Data_Structure_16414_I
Implement a Modified Bitonic Sort Given the recursive sorting mechanism of **Bitonic Sort**, you are to **enhance and modify the existing implementation** to handle arrays of any arbitrary length \(n\). This involves: 1. Extending and pre-processing the input array such that its length becomes the next power of two whi...
def bitonic_compare_and_swap(arr, i, j, direction): if direction == (arr[i] > arr[j]): arr[i], arr[j] = arr[j], arr[i] def bitonic_merge(arr, low, cnt, direction): if cnt > 1: k = cnt // 2 for i in range(low, low + k): bitonic_compare_and_swap(arr, i, i + k, direction) ...
from solution import modified_bitonic_sort def test_empty_array(): assert modified_bitonic_sort([]) == [] def test_single_element(): assert modified_bitonic_sort([42]) == [42] def test_sorted_array(): assert modified_bitonic_sort([1, 2, 3]) == [1, 2, 3] def test_reverse_sorted_array(): assert modifi...
[ { "docstring": null, "function_declaration": "def bitonic_compare_and_swap(arr, i, j, direction):", "function_name": "bitonic_compare_and_swap", "parameter_list": "(arr, i, j, direction)" }, { "docstring": null, "function_declaration": "def bitonic_merge(arr, low, cnt, direction):", ...
[ 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 next_power_of_two(n):\n if n <= 0:\n return 1\n power = 1\n while power < n:\n power *= 2\n return power\n\ndef compare_and_swap...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016414", "row_id": 16414, "seed_ids": "[17]" }
0.667043
Data_Structure_16414
I
[ "bitonic_compare_and_swap", "bitonic_merge", "bitonic_sort_recursive", "next_power_of_two", "modified_bitonic_sort" ]
5
[ [ "bitonic_merge", "bitonic_compare_and_swap" ], [ "bitonic_sort_recursive", "bitonic_merge" ], [ "modified_bitonic_sort", "bitonic_sort_recursive" ], [ "modified_bitonic_sort", "next_power_of_two" ] ]
4
[]
false
[]
false
pytest
true
[]
true
7a94febb0969291fd86a05c17f4b3b6ef31aa797
7e7fe689e79f5d13fe579c15d154583945c904b5
v1.0
instruct
Data_Structure
Data_Structure_16518_I
### Selection Sort - Binary Search Enhancement Selection sort is a basic algorithm with suboptimal performance for larger datasets. Your task is to improve the selection sort by incorporating binary search during the selection phase to find the minimum element more efficiently. ### Task Implement the function `enhanc...
from typing import List def binary_search_min(arr: List[int], start: int, end: int) -> int: """ Perform a binary search to find the index of the minimum element in the array between indices start and end. """ min_index = start min_value = arr[start] for i in range(start + 1, end + 1):...
from solution import enhanced_selection_sort def test_enhanced_selection_sort_basic(): assert enhanced_selection_sort([64, 25, 12, 22, 11]) == [11, 12, 22, 25, 64] def test_enhanced_selection_sort_empty(): assert enhanced_selection_sort([]) == [] def test_enhanced_selection_sort_single_element(): assert ...
[ { "docstring": "Perform a binary search to find the index of the minimum element \nin the array between indices start and end.", "function_declaration": "def binary_search_min(arr, start, end):", "function_name": "binary_search_min", "parameter_list": "(arr, start, end)" }, { "docstring": "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": "from typing import List\n\ndef binary_search_min(arr: List[int], start: int, end: int) -> int:\n \"\"\"\n Perform a binary search to find the index of t...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016518", "row_id": 16518, "seed_ids": "[18]" }
0.635782
Data_Structure_16518
I
[ "binary_search_min", "enhanced_selection_sort" ]
2
[ [ "enhanced_selection_sort", "binary_search_min" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c78ea258b49eb2dc3f17c0aeadb02b6babbd902e
1fd08dab8a12a308e85a2b4ed1c1248a01f4e36f
v1.0
instruct
Data_Structure
Data_Structure_16523_I
#### Scenario A project planner uses a directed graph to represent tasks in a project and their dependencies. Each task is a node, and a directed edge from task A to task B means that task A must be completed before task B can start. The planner needs to check whether the graph of tasks contains any cycles to prevent p...
WHITE = 0 # Vertex has not been visited yet GRAY = 1 # Vertex is in the current DFS traversal stack BLACK = 2 # Vertex and its descendants have been fully explored def is_in_cycle(graph, traversal_states, vertex): """ Helper function to check if the current vertex is part of a cycle. Uses DFS and verte...
from solution import contains_cycle def test_contains_cycle_with_simple_cycle(): graph = { 'A': ['B'], 'B': ['C'], 'C': ['A'] } assert contains_cycle(graph) == True # This graph contains a cycle. def test_contains_cycle_no_edges(): graph = { 'A': [], 'B': [], ...
[ { "docstring": "Helper function to check if the current vertex is part of a cycle.\nUses DFS and vertex states to track the traversal.", "function_declaration": "def is_in_cycle(graph, traversal_states, vertex):", "function_name": "is_in_cycle", "parameter_list": "(graph, traversal_states, vertex)" ...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "WHITE = 0 # Vertex has not been visited yet\nGRAY = 1 # Vertex is in the current DFS traversal stack\nBLACK = 2 # Vertex and its descendants have been ful...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016523", "row_id": 16523, "seed_ids": "[237]" }
0.633949
Data_Structure_16523
I
[ "is_in_cycle", "contains_cycle" ]
2
[ [ "contains_cycle", "is_in_cycle" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ce0c9343d04c419b8ee8c038f8fee0fce6bdc246
10586293993c98a76a5a5de7cbde8e820c4d3e4e
v1.0
instruct
Data_Structure
Data_Structure_16528_I
### Context Bogo Sort is a notoriously inefficient sorting algorithm that works by generating random permutations of the input array until the array happens to be sorted. Despite its impractical nature, it is an excellent educational tool for illustrating the importance of algorithm efficiency. ### Task You are requir...
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_limit(arr, max_iterations): """ Sorts an array using the Bogo Sort algorithm, but...
from solution import bogo_sort_with_limit def test_bogo_sort_with_limit_sorted_array(): arr = [1, 2, 3, 4] max_iterations = 1000 sorted_arr, iterations, success = bogo_sort_with_limit(arr, max_iterations) assert sorted_arr == [1, 2, 3, 4] assert iterations >= 0 and iterations <= max_iterations ...
[ { "docstring": "Helper function to check if the array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts an array using the Bogo Sort algorithm, but stops if the number of iterations exceeds the limit.\...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef bogo_sort_with_limit(arr, max_iterations):\n \"\"\"\n Sorts an array using the Bogo Sort algorithm, but stops if the number of iter...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016528", "row_id": 16528, "seed_ids": "[16]" }
0.607962
Data_Structure_16528
I
[ "is_sorted", "bogo_sort_with_limit" ]
2
[ [ "bogo_sort_with_limit", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c29f161d1a23126366d2ccac1abe1cf7ac05681c
1b2a5fbaa17788ec5c7edbfcc3b3debbf02340c4
v1.0
instruct
Data_Structure
Data_Structure_16586_I
### Matrix Exponentiation Coding Challenge #### Context In graph theory, the k-th power of the adjacency matrix of a graph gives information about the number of paths of length k between vertices. In cryptographic algorithms, matrix exponentiation is widely used for key generation and transformations. #### Objective ...
def matrix_multiply(A, B): """ Multiplies two 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): result[i][j] += A[i][k] * B[k][j] return result def matrix_exponentiation_kth...
from solution import matrix_exponentiation_kth_power def test_identity_matrix_power(): matrix = [ [1, 0], [0, 1] ] k = 5 result = matrix_exponentiation_kth_power(matrix, k) expected = [ [1, 0], [0, 1] ] assert result == expected def test_zero_power(): ma...
[ { "docstring": "Multiplies two matrices A and B.", "function_declaration": "def matrix_multiply(A, B):", "function_name": "matrix_multiply", "parameter_list": "(A, B)" }, { "docstring": "Compute the k-th power of a given square matrix using exponentiation by squaring.", "function_declara...
[ 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 matrix_multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B.\n \"\"\"\n n = len(A)\n result = [[0] * n for _ in range(n)]\n \n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016586", "row_id": 16586, "seed_ids": "[340]" }
0.508184
Data_Structure_16586
I
[ "matrix_multiply", "matrix_exponentiation_kth_power" ]
2
[ [ "matrix_exponentiation_kth_power", "matrix_multiply" ] ]
1
[]
false
[]
false
pytest
true
[]
true
39a78da00d9baa525379a09c39c22f6487630a84
905a745faf8fa1a8128579b94c905a2c7871f00e
v1.0
instruct
Data_Structure
Data_Structure_16624_I
### Coding Assessment: Improving the Nearest Neighbor Algorithm #### Problem Statement You are provided with an implementation of the nearest neighbor classification algorithm. Your task is to improve and extend the provided code in the following ways: 1. **Optimize Distance Calculation**: Modify the distance computat...
from collections import Counter import math def euclidean_distance(p1, p2): """ Computes the Euclidean distance between two points p1 and p2. p1 and p2 are tuples of the same length. """ return math.sqrt(sum((a - b) ** 2 for a, b in zip(p1, p2))) def k_nearest_neighbors(x: tuple, tSet: dict, k: in...
from solution import k_nearest_neighbors # Utility function for unit tests def test_k_nearest_neighbors(): assert k_nearest_neighbors((1, 2), {(0, 0): 'A', (0, 1): 'A', (1, 1): 'B', (2, 3): 'B'}, 2) == 'B' def test_query_identical_to_point(): assert k_nearest_neighbors((1, 2), {(1, 2): 'A', (2, 3): 'B', (3, 4...
[]
[ 0, 0, 0, 1, 0, 1, 1, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import Counter\nimport math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points i...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00016624", "row_id": 16624, "seed_ids": "[260]" }
0.659489
Data_Structure_16624
I
[ "euclidean_distance", "k_nearest_neighbors" ]
2
[ [ "k_nearest_neighbors", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9b6c332aab947920ba0ba48f68c703cbbaa458aa
d3bd1f5dc480c3f3275c25f8d9d65eae546474ae
v1.0
instruct
Data_Structure
Data_Structure_16641_I
### Context As part of a software system's performance optimization module, you are required to write a function that calculates the Greatest Common Divisor (GCD) using bitwise operations. ### Task Implement a function `bitwise_gcd` that computes the GCD of two non-negative integers using bitwise operations. ### Spec...
def trailing_zero(x): """ Returns the number of trailing zero bits in x. For example, trailing_zero(8) returns 3 because the binary representation of 8 is 1000. """ if x == 0: return 32 return (x & -x).bit_length() - 1 def bitwise_gcd(a, b): """ Computes the GCD of two non-negat...
from solution import bitwise_gcd, trailing_zero def test_trailing_zero(): assert trailing_zero(0) == 32 assert trailing_zero(1) == 0 assert trailing_zero(2) == 1 assert trailing_zero(8) == 3 assert trailing_zero(16) == 4 def test_bitwise_gcd_basic(): assert bitwise_gcd(34, 17) == 17 assert...
[ { "docstring": "Returns the number of trailing zero bits in x.\nFor example, trailing_zero(8) returns 3 because the binary representation of 8 is 1000.", "function_declaration": "def trailing_zero(x):", "function_name": "trailing_zero", "parameter_list": "(x)" }, { "docstring": "Computes the...
[ 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_gcd(a: int, b: int) -> int:\n \"\"\"\n Calculate the greatest common divisor (GCD) of two non-negative integers using bitwise operations.\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016641", "row_id": 16641, "seed_ids": "[166]" }
0.682957
Data_Structure_16641
I
[ "trailing_zero", "bitwise_gcd" ]
2
[ [ "bitwise_gcd", "trailing_zero" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f745fac968e146018badc353a96c27943e3c97ab
c2fb3b31f6e9cfa30f76b2d11d0f991dc3ee03c3
v1.0
instruct
Data_Structure
Data_Structure_16656_I
#### Scenario: You are tasked with creating a utility to help mathematicians with computing GCD, LCM, and analyzing binary representations. You need to write an efficient function to compute the **product of LCM and GCD** for two given positive integers using advanced bitwise operations combined with the conventional E...
def gcd(a: int, b: int) -> int: while b: a, b = b, a % b return a def lcm(a: int, b: int, gcd_value: int) -> int: return a // gcd_value * b def product_lcm_gcd(a: int, b: int) -> int: gcd_value = gcd(a, b) lcm_value = lcm(a, b, gcd_value) return gcd_value * lcm_value
from solution import product_lcm_gcd def test_example_1(): assert product_lcm_gcd(12, 18) == 216 def test_example_2(): assert product_lcm_gcd(48, 180) == 8640 def test_same_numbers(): assert product_lcm_gcd(10, 10) == 100 def test_prime_numbers(): assert product_lcm_gcd(13, 29) == 377 def test_one_...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def lcm(a, b, gcd_value):", "function_name": "lcm", "parameter_list": "(a, b, gcd_value)" }, { "docstring": n...
[ 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 gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef lcm(a, b, gcd_val):\n return (a // gcd_val) * b\n\ndef product_lcm_gcd(a: int, b...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016656", "row_id": 16656, "seed_ids": "[166]" }
0.672984
Data_Structure_16656
I
[ "gcd", "lcm", "product_lcm_gcd" ]
3
[ [ "product_lcm_gcd", "gcd" ], [ "product_lcm_gcd", "lcm" ] ]
2
[]
false
[]
false
pytest
true
[]
true
cc7378696d08f2264652f84f14b1c029f290e98e
8026c28fc0246d3e88930c2e90c3b0bff3601f9d
v1.0
instruct
Data_Structure
Data_Structure_16669_I
### Matrix Multiplication Challenge #### Task: Write a function `generalized_multiply(matrices: List[List[List[int]]]) -> List[List[int]]` that takes a list of matrices (each matrix represented as a 2D list of integers) and returns the result of their chained multiplication. #### Requirements: 1. The function should ...
from typing import List def matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]: """ Multiplies two matrices A and B. """ # Check matrix dimensions if len(A[0]) != len(B): raise ValueError("Incompatible matrix dimensions for multiplication") # Resultant matri...
from solution import generalized_multiply def test_generalized_multiply_example1(): matrices = [ [[1, 2], [3, 4]], [[5, 6], [7, 8]] ] expected_result = [ [19, 22], [43, 50] ] assert generalized_multiply(matrices) == expected_result def test_gene...
[ { "docstring": "Multiplies two matrices A and B.", "function_declaration": "def matrix_multiply(A, B):", "function_name": "matrix_multiply", "parameter_list": "(A, B)" }, { "docstring": "Multiplies a list of matrices in the given order.", "function_declaration": "def generalized_multiply...
[ 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 multiply_matrices(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Multiplies two matrices A and B....
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016669", "row_id": 16669, "seed_ids": "[343]" }
0.565411
Data_Structure_16669
I
[ "matrix_multiply", "generalized_multiply" ]
2
[ [ "generalized_multiply", "matrix_multiply" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f037ffe1878229d17e86697fc61c1c37e2dfea3c
73f3d46b195733b45a7cae25be86711190234259
v1.0
instruct
Data_Structure
Data_Structure_16677_I
### Bitonic Sort Implementation with Edge Case Handling #### Problem Description: You are required to implement the bitonic sort algorithm to sort an array of integers in either increasing or decreasing order. Ensure that the input array size is always a power of two. If the size of the input array is not a power of t...
from typing import List def bitonic_compare(arr: List[int], i: int, j: int, direction: bool) -> None: if (direction and arr[i] > arr[j]) or (not direction and arr[i] < arr[j]): arr[i], arr[j] = arr[j], arr[i] def bitonic_merge(arr: List[int], low: int, cnt: int, direction: bool) -> None: if cnt > 1: ...
import pytest from solution import bitonic_sort def test_bitonic_sort_increasing(): assert bitonic_sort([3, 7, 4, 8, 6, 2, 1, 5], reverse=True) == [1, 2, 3, 4, 5, 6, 7, 8] def test_bitonic_sort_decreasing(): assert bitonic_sort([3, 7, 4, 8, 6, 2, 1, 5], reverse=False) == [8, 7, 6, 5, 4, 3, 2, 1] def test_bit...
[ { "docstring": null, "function_declaration": "def bitonic_compare(arr, i, j, direction):", "function_name": "bitonic_compare", "parameter_list": "(arr, i, j, direction)" }, { "docstring": null, "function_declaration": "def bitonic_merge(arr, low, cnt, direction):", "function_name": "...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef bitonic_sort(arr: List[int], reverse: bool = False) -> List[int]:\n def compare_and_swap(arr, i, j, direction):\n if ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00016677", "row_id": 16677, "seed_ids": "[17]" }
0.667999
Data_Structure_16677
I
[ "bitonic_compare", "bitonic_merge", "bitonic_sort_rec", "bitonic_sort" ]
4
[ [ "bitonic_merge", "bitonic_compare" ], [ "bitonic_sort", "bitonic_sort_rec" ], [ "bitonic_sort_rec", "bitonic_merge" ] ]
3
[]
false
[]
false
pytest
true
[]
true
0192d094899511761f0318e1344c73f251908224
d170d75523296207e4fd52a108b5d9949a73f4b6
v1.0
instruct
Data_Structure
Data_Structure_16697_I
### Radix Sort Implementation Implement the `radix_sort` function for sorting a list of non-negative integers. Your implementation should be able to handle a list of integers and sort them in non-decreasing order using the radix sort algorithm specified above. #### Function Signature ```python def radix_sort(arr: lis...
def counting_sort(arr, exp, simulation, iter_num): n = len(arr) output = [0] * n count = [0] * 10 # Store count of occurrences in count[] for i in range(n): index = arr[i] // exp count[index % 10] += 1 # Change count[i] so that it contains the actual # position of this digi...
from solution import radix_sort def test_radix_sort_basic_cases(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_empty_list(): assert radix_sort([]) == [] def test_radix_sort_single_element_list(): assert radix_sort([5]) == [5] def test_rad...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp, simulation, iter_num):", "function_name": "counting_sort", "parameter_list": "(arr, exp, simulation, iter_num)" }, { "docstring": "Perform radix sort on a list of non-negative integers.\n\n:param arr: List of non-negat...
[ 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 counting_sort(arr, exp, simulation, iter_num):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # Store count of occurrences in count[...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016697", "row_id": 16697, "seed_ids": "[15]" }
0.629027
Data_Structure_16697
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1e63adc76798dc35ca389c464fcb48526b705890
fae8c5e257e3e40add3077895aa1682dc4358cf3
v1.0
instruct
Data_Structure
Data_Structure_16759_I
### Question Title: Efficiently Finding GCD and LCM Using Custom Functions ### Question Description: You are tasked with implementing a set of functions to compute the Greatest Common Divisor (GCD), Least Common Multiple (LCM), and trailing zeros in the binary representation of integers using advanced bitwise operatio...
def extended_gcd(a: int, b: int) -> int: """ Returns the Greatest Common Divisor (GCD) of two integers a and b using bitwise operations. """ if a == 0: return b if b == 0: return a shift = 0 while ((a | b) & 1) == 0: a >>= 1 b >>= 1 shift += 1 ...
from solution import extended_gcd, optimized_lcm, count_trailing_zeros def test_extended_gcd(): assert extended_gcd(18, 24) == 6 assert extended_gcd(48, 180) == 12 assert extended_gcd(0, 16) == 16 assert extended_gcd(16, 0) == 16 assert extended_gcd(0, 0) == 0 assert extended_gcd(37, 600) == 1 ...
[ { "docstring": "Returns the Greatest Common Divisor (GCD) of two integers a and b using bitwise operations.", "function_declaration": "def extended_gcd(a, b):", "function_name": "extended_gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the Least Common Multiple (LCM) of two integ...
[ 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 extended_gcd(a: int, b: int) -> int:\n \"\"\"\n Compute the GCD of two integers using the Euclidean algorithm.\n \"\"\"\n if a == 0:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016759", "row_id": 16759, "seed_ids": "[166]" }
0.600846
Data_Structure_16759
I
[ "extended_gcd", "optimized_lcm", "count_trailing_zeros" ]
3
[ [ "optimized_lcm", "extended_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7f567654a444d3cce333e6553539e21405fc1e0f
00d25734c93b628e5edf1a2681244167ab2e26f6
v1.0
instruct
Data_Structure
Data_Structure_16761_I
#### **Prime Number Reversal Game** **Context**: In the game of Prime Number Reversal, the player is provided with a list of integers. For each integer, the player needs to determine whether reversing the digits of the integer gives a prime number. The game judges the player's performance based on correctly identifyin...
from typing import List def is_prime(n: int) -> bool: """Check 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: return...
from solution import prime_reversal def test_single_number(): assert prime_reversal([13]) == [True] assert prime_reversal([17]) == [True] assert prime_reversal([29]) == [False] def test_multiple_numbers(): assert prime_reversal([13, 17, 29, 31, 37, 97]) == [True, True, False, True, True, True] def te...
[ { "docstring": "Check if a number is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Check if the reversed digit sequence of each number in the list is a prime number.", "function_declaration": "def pri...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016761", "row_id": 16761, "seed_ids": "[143]" }
0.665841
Data_Structure_16761
I
[ "is_prime", "prime_reversal" ]
2
[ [ "prime_reversal", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
339c61116b98834ba5cb4c06ea5d0cf4257a566e
0702277ef4d5e46616806b6125387edc1e258f68
v1.0
instruct
Data_Structure
Data_Structure_16780_I
### Matrix Inversion Function #### Scenario You are tasked with building on an existing module that inverts \(n \times n\) matrices. This function is crucial in numerical linear algebra for solving systems of linear equations, among other applications. You'll implement a matrix inversion function that encapsulates the...
def get_determinant(matrix): """ Calculates the determinant of a (n x n) matrix. """ n = len(matrix) if n == 1: return matrix[0][0] if n == 2: return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0] determinant = 0 for c in range(n): determinant += ((-1...
from solution import invert_matrix def approx_equal(matrix1, matrix2, tol=1e-9): for row1, row2 in zip(matrix1, matrix2): for el1, el2 in zip(row1, row2): if abs(el1 - el2) > tol: return False return True def test_invert_matrix_2x2(): matrix = [ [4, 7], ...
[ { "docstring": "Calculates the determinant of a (n x n) matrix.", "function_declaration": "def get_determinant(matrix):", "function_name": "get_determinant", "parameter_list": "(matrix)" }, { "docstring": "Returns the minor of the matrix after removing the ith row and jth column.", "func...
[ 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 get_determinant(matrix):\n \"\"\"\n Computes the determinant of a 2x2 or 3x3 matrix.\n \"\"\"\n n = len(matrix)\n \n if n == 2:\n ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00016780", "row_id": 16780, "seed_ids": "[347]" }
0.593336
Data_Structure_16780
I
[ "get_determinant", "get_minor", "transpose_and_multiply", "invert_matrix" ]
4
[ [ "get_determinant", "get_minor" ], [ "invert_matrix", "get_determinant" ], [ "invert_matrix", "get_minor" ], [ "invert_matrix", "transpose_and_multiply" ] ]
4
[]
false
[]
false
pytest
true
[]
true
0c2d4ec3a5365baac2a8c4952baec741df49e2d7
9caa8c4994556a2dfdd7911be7af1ce502e2a827
v1.0
instruct
Data_Structure
Data_Structure_16827_I
Implement Insertion Sort using Search Insert #### Context Given an array of integers, you are required to sort it using the insertion sort algorithm. However, to optimize the insertion point search, you should use the provided `search_insert` function that employs binary search to find the correct index to insert the ...
from typing import List def search_insert(sorted_array: List[int], target: int) -> int: """ Uses binary search to find the insert position for the target in the sorted_array. """ left, right = 0, len(sorted_array) while left < right: mid = (left + right) // 2 if sorted_array[mid] < ...
from solution import insertion_sort_with_search_insert def test_insertion_sort_with_search_insert_basic(): assert insertion_sort_with_search_insert([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13] assert insertion_sort_with_search_insert([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12] def test_insertion_so...
[ { "docstring": "Uses binary search to find the insert position for the target in the sorted_array.", "function_declaration": "def search_insert(sorted_array, target):", "function_name": "search_insert", "parameter_list": "(sorted_array, target)" }, { "docstring": "Sorts an array of integers ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef search_insert(sorted_array: List[int], target: int) -> int:\n \"\"\"\n Finds the index at which the target should be inse...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016827", "row_id": 16827, "seed_ids": "[199]" }
0.569706
Data_Structure_16827
I
[ "search_insert", "insertion_sort_with_search_insert" ]
2
[ [ "insertion_sort_with_search_insert", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dfca3ebd7b385ce1f3c17b80ebd6a090513f242c
4dac64626bbe87576389b3bee435788fdaab9005
v1.0
instruct
Data_Structure
Data_Structure_16857_I
You are tasked with implementing a variation of the Merge Sort algorithm. This variation, called "Iterative Merge Sort," avoids recursion by using an iterative approach to divide the array and then merge the parts. Your task is to write a function that sorts an input list of integers using the Iterative Merge Sort algo...
def iterative_merge_sort(arr): if not arr: # Edge case: empty array return arr n = len(arr) width = 1 while width < n: for i in range(0, n, 2 * width): left = arr[i:i + width] right = arr[i + width:i + 2 * width] arr[i:i + 2 * width] = merge(left, ri...
def test_iterative_merge_sort(): assert iterative_merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] assert iterative_merge_sort([1, 3, 2, 5, 4, 6]) == [1, 2, 3, 4, 5, 6] assert iterative_merge_sort([5]) == [5] assert iterative_merge_sort([]) == [] assert iterative_merge_sort([9, -...
[ { "docstring": null, "function_declaration": "def iterative_merge_sort(arr):", "function_name": "iterative_merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)"...
[ 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 iterative_merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n width = 1\n n = len(arr...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016857", "row_id": 16857, "seed_ids": "[12]" }
0.606654
Data_Structure_16857
I
[ "iterative_merge_sort", "merge" ]
2
[ [ "iterative_merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
false
[]
true
36c44d4a0849e79cd4cd2afb80629fe8aed371f5
9373d08e36521ffc250aefb852ad12a243816a9d
v1.0
instruct
Data_Structure
Data_Structure_16890_I
**Context:** You are working with a highly inefficient sorting algorithm known as Bogo Sort. Although impractical for real applications due to its random nature and excessive time complexity, Bogo Sort is a useful academic example to illustrate the importance of choosing efficient algorithms. **Task:** Implement the B...
import random def is_sorted(arr): for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort(arr, simulation=False): def shuffle(arr): random.shuffle(arr) return arr iteration = 0 while not is_sorted(arr): if simulation...
from solution import bogo_sort, is_sorted def test_is_sorted(): assert is_sorted([1, 2, 3, 4]) == True assert is_sorted([1, 3, 2, 4]) == False assert is_sorted([]) == True assert is_sorted([1]) == True assert is_sorted([2, 2, 2, 2]) == True def test_bogo_sort(): # Note: These tests might take ...
[ { "docstring": null, "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def bogo_sort(arr, simulation=False):", "function_name": "bogo_sort", "parameter_list": "(arr, simulation=F...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_sorted(arr):\n for i in range(len(arr) - 1):\n if arr[i] > arr[i + 1]:\n return False\n return True\n\ndef bog...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016890", "row_id": 16890, "seed_ids": "[16]" }
0.599299
Data_Structure_16890
I
[ "is_sorted", "bogo_sort" ]
2
[ [ "bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6a20cb7c3a9a5ba894ae6e1dd10e00937e3cdadb
098f68bfbfc7504d4467cf0104cc28ebc746519d
v1.0
instruct
Data_Structure
Data_Structure_16913_I
### Heap Sort Implementation and Analysis As a data scientist, you are working on a feature that requires the efficient sorting of large datasets. Given your understanding of the Heap Sort algorithm, we would like you to implement a function that sorts an array using a max heap, and another using a min heap. Additiona...
def max_heapify(arr, n, i, simulation): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[largest] < arr[left]: largest = left if right < n and arr[largest] < arr[right]: largest = right if largest != i: arr[i], arr[largest] = arr[largest], arr[i] ...
from solution import max_heap_sort_with_simulation, min_heap_sort_with_simulation def test_max_heap_sort_with_simulation_unsorted_array(): arr = [3, 1, 5, 2, 4] sorted_arr = max_heap_sort_with_simulation(arr[:], simulation=False) assert sorted_arr == [1, 2, 3, 4, 5] def test_max_heap_sort_with_simulation_...
[ { "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_with_simulation(arr, simulation=False):", "function_n...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def heapify(arr, n, i, is_max_heap, simulation):\n largest_or_smallest = i # Initialize largest/smallest as root\n left = 2 * i + 1 # left = 2*i + ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016913", "row_id": 16913, "seed_ids": "[8]" }
0.617128
Data_Structure_16913
I
[ "max_heapify", "max_heap_sort_with_simulation", "min_heapify", "min_heap_sort_with_simulation" ]
4
[ [ "max_heap_sort_with_simulation", "max_heapify" ], [ "min_heap_sort_with_simulation", "min_heapify" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f745a8bdcd61cb07912aae3784cca97a48f414fe
858d8d44f71d91db670aafc061894f1790d99713
v1.0
instruct
Data_Structure
Data_Structure_16937_I
You are tasked with implementing a classification system using the Nearest Neighbor algorithm. Given a vector \(x\) and a training set \(tSet\), your objective is to find the closest neighbor to \(x\) in \(tSet\) using Euclidean distance, and return the label associated with that neighbor in \(tSet\). ### Function Sig...
import math from typing import Tuple, Dict, Any def euclidean_distance(p: Tuple[float, ...], q: Tuple[float, ...]) -> float: """ Calculate the Euclidean distance between two points p and q. """ return math.sqrt(sum((pi - qi) ** 2 for pi, qi in zip(p, q))) def nearest_neighbor(x: Tuple[float, ...], tSe...
from solution import nearest_neighbor def test_nearest_neighbor_basic(): x = (1.0, 2.0) tSet = { (2.0, 3.0): "Class_A", (3.0, 4.0): "Class_B", (1.1, 2.1): "Class_C" } assert nearest_neighbor(x, tSet) == "Class_C" def test_nearest_neighbor_single_element(): x = (1.0, 1.0) ...
[ { "docstring": "Calculate the Euclidean distance between two points p and q.", "function_declaration": "def euclidean_distance(p, q):", "function_name": "euclidean_distance", "parameter_list": "(p, q)" }, { "docstring": "Find the label of the closest vector to x in tSet using Euclidean dista...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom typing import Tuple, Dict, Any\n\ndef euclidean_distance(v1: Tuple[float, ...], v2: Tuple[float, ...]) -> float:\n \"\"\"\n Calculate ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016937", "row_id": 16937, "seed_ids": "[260]" }
0.667603
Data_Structure_16937
I
[ "euclidean_distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
946d81de151d2c35c9a1f6140c10293ec8868de9
0958fad9f5ac2ee2fb8831b4810fe3a6480f5567
v1.0
instruct
Data_Structure
Data_Structure_16982_I
### RSA Encryption Implementation As part of your cryptography coursework, you are required to implement a secure communication mechanism using the RSA algorithm. Your task is to complete the following two functions for RSA encryption and decryption. #### Requirements: 1. **Function Signature**: - `generate_key...
import random from typing import Tuple, Optional from sympy import isprime, gcd def generate_prime(bit_length: int, seed: Optional[int] = None) -> int: if seed is not None: random.seed(seed) while True: prime_candidate = random.getrandbits(bit_length) if isprime(prime_candidate): ...
from solution import generate_key_pair, rsa_encrypt, rsa_decrypt def test_key_generation(): n, e, d = generate_key_pair(16, seed=42) assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) def test_rsa_encryption_decryption(): n, e, d = generate_key_pair(16, seed=42) ...
[ { "docstring": null, "function_declaration": "def generate_prime(bit_length, seed=None):", "function_name": "generate_prime", "parameter_list": "(bit_length, seed=None)" }, { "docstring": null, "function_declaration": "def generate_key_pair(k, seed=None):", "function_name": "generate...
[ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, gcd\nfrom typing import Tuple\n\ndef generate_prime_candidate(k):\n # Generate random number of k bits\n candi...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00016982", "row_id": 16982, "seed_ids": "[154]" }
0.598662
Data_Structure_16982
I
[ "generate_prime", "generate_key_pair", "rsa_encrypt", "rsa_decrypt" ]
4
[ [ "generate_key_pair", "generate_prime" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
aab062c4b9c102cc0b16a1759ce5b0a1c567f40c
5f5f0c5971c83e14fd195eaf9a5b1cb20441fcbb
v1.0
instruct
Data_Structure
Data_Structure_17022_I
### Question Description You are required to implement a Markov Chain simulator. The simulator will use a dictionary-based Markov Chain to generate a sequence of states, given an initial state. ### Function Implementation #### Function 1: next_state Create a function `next_state(chain: dict, current_state: str) -> s...
import random def next_state(chain, current_state): """ Selects the next state based on the transition probabilities defined in the chain for the current state. """ transitions = chain[current_state] states = list(transitions.keys()) probabilities = list(transitions.values()) return random....
from solution import next_state, iterating_markov_chain def test_next_state(): chain = { 'A': {'A': 0.6, 'B': 0.4}, 'B': {'A': 0.3, 'B': 0.7} } assert next_state(chain, 'A') in ['A', 'B'] assert next_state(chain, 'B') in ['A', 'B'] def test_iterating_markov_chain(): chain = { ...
[ { "docstring": "Selects the next state based on the transition probabilities defined in the chain for the current state.", "function_declaration": "def next_state(chain, current_state):", "function_name": "next_state", "parameter_list": "(chain, current_state)" }, { "docstring": "Generates 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": "import random\n\ndef next_state(chain: dict, current_state: str) -> str:\n \"\"\"\n Chooses the next state based on the current state's transition proba...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017022", "row_id": 17022, "seed_ids": "[232]" }
0.474477
Data_Structure_17022
I
[ "next_state", "iterating_markov_chain" ]
2
[ [ "iterating_markov_chain", "next_state" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0677b57f9acab81b12fb96f674aa6fe24b2eecc2
823829595d274e3eee9421004da0bc2580ce31eb
v1.0
instruct
Data_Structure
Data_Structure_17037_I
#### Question Prompt Design and implement a function that sorts an array using the Heap Sort algorithm. Specifically, implement the heap sort using a modified version of the Min Heap data structure, but also allow an optional simulation mode that outputs the state of the array at each iteration of the heapify process....
def heapify(arr, n, i, simulation): smallest = i l = 2 * i + 1 r = 2 * i + 2 if l < n and arr[l] < arr[smallest]: smallest = l if r < n and arr[r] < arr[smallest]: smallest = r if smallest != i: arr[i], arr[smallest] = arr[smallest], arr[i] if simulation: ...
from solution import custom_heap_sort def test_custom_heap_sort_empty(): assert custom_heap_sort([]) == [] def test_custom_heap_sort_single_element(): assert custom_heap_sort([1]) == [1] def test_custom_heap_sort_sorted_array(): assert custom_heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_custom...
[ { "docstring": null, "function_declaration": "def heapify(arr, n, i, simulation):", "function_name": "heapify", "parameter_list": "(arr, n, i, simulation)" }, { "docstring": null, "function_declaration": "def custom_heap_sort(arr, simulation=False):", "function_name": "custom_heap_so...
[ 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 custom_heap_sort(arr, simulation=False):\n def heapify(arr, n, i):\n smallest = i\n left = 2 * i + 1\n right = 2 * i + 2\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017037", "row_id": 17037, "seed_ids": "[8]" }
0.708953
Data_Structure_17037
I
[ "heapify", "custom_heap_sort" ]
2
[ [ "custom_heap_sort", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2ef98a3c2551d476dd05c14ca777bae378a7d5fa
4c96c4a2a5e1ce15da9f4007644919dddeb4d0d0
v1.0
instruct
Data_Structure
Data_Structure_17055_I
**Problem Statement**: You have been tasked with implementing a function that calculates the Least Common Multiple (LCM) of an array of integers using a combination of Euclid's algorithm for GCD and the provided LCM formula. You must also handle various edge cases gracefully, such as non-integer inputs or an empty list...
import math from functools import reduce def gcd(a, b): """ Calculates the Greatest Common Divisor (GCD) of two numbers using Euclid's algorithm. """ while b: a, b = b, a % b return a def lcm(a, b): """ Calculates the Least Common Multiple (LCM) of two numbers using the relationshi...
from solution import lcm, gcd, lcm_array import pytest def test_gcd(): assert gcd(12, 15) == 3 assert gcd(100, 10) == 10 assert gcd(7, 13) == 1 assert gcd(0, 5) == 5 def test_lcm(): assert lcm(3, 4) == 12 assert lcm(5, 0) == 0 assert lcm(6, 8) == 24 assert lcm(7, 13) == 91 def test_lc...
[ { "docstring": "Calculates the Greatest Common Divisor (GCD) of two numbers using Euclid's algorithm.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Calculates the Least Common Multiple (LCM) of two numbers using the relation...
[ 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 functools import reduce\n\ndef gcd(a, b):\n \"\"\"\n Calculates the Greatest Common Divisor (GCD) of two numbers using Euclid's algori...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017055", "row_id": 17055, "seed_ids": "[166]" }
0.694464
Data_Structure_17055
I
[ "gcd", "lcm", "lcm_array" ]
3
[ [ "lcm", "gcd" ], [ "lcm_array", "lcm" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b36776904bf7f960f9b774d7924945839e7bbdda
aaeed79531528375d668c3ef9d58569263f33b93
v1.0
instruct
Data_Structure
Data_Structure_17087_I
You are provided with two functions designed to compute the exponentiation of given integers, optionally modulo another integer: 1. **Iterative Version**: `power(a: int, n: int, mod: int = None)` 2. **Recursive Version**: `power_recur(a: int, n: int, mod: int = None)` ### Task Implement a function `validate_exponent...
def power(a: int, n: int, mod: int = None) -> int: """ Iterative version to compute a^n % mod """ if n == 0: return 1 if mod is None else 1 % mod result = 1 base = a if mod is None else a % mod while n > 0: if n % 2 == 1: result = (result * base) % mod if mod else...
from solution import power, power_recur, validate_exponentiation def test_power_iter(): assert power(2, 10) == 1024 assert power(2, 10, 1000) == 24 assert power(0, 0) == 1 assert power(100, 0, 10) == 1 assert power(3, 0) == 1 assert power(10, 5) == 100000 def test_power_recur(): assert pow...
[ { "docstring": "Iterative version to compute a^n % mod", "function_declaration": "def power(a, n, mod=None):", "function_name": "power", "parameter_list": "(a, n, mod=None)" }, { "docstring": "Recursive version to compute a^n % mod", "function_declaration": "def power_recur(a, n, mod=Non...
[ 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 power(a: int, n: int, mod: int = None) -> int:\n \"\"\"\n Iterative function to compute a^n % mod.\n \"\"\"\n result = 1\n base = a\n \n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017087", "row_id": 17087, "seed_ids": "[151]" }
0.619381
Data_Structure_17087
I
[ "power", "power_recur", "validate_exponentiation" ]
3
[ [ "validate_exponentiation", "power" ], [ "validate_exponentiation", "power_recur" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ba2586b83f022e823b2c83d3d5927646217ed192
32f3190f2f30b8310e75fbac9562c6720a691488
v1.0
instruct
Data_Structure
Data_Structure_17097_I
### Problem Description You are tasked with developing a small cryptographic protocol simulation. Your mission is to write a function that determines both the Euler's totient function and all primitive roots of a given integer \( n \). **Function Signature** ```python def crypto_simulation(n: int) -> Tuple[int, List[...
from typing import Tuple, List def gcd(a: int, b: int) -> int: while b != 0: a, b = b, a % b return a def euler_totient(n: int) -> int: result = n p = 2 while p * p <= n: if n % p == 0: while n % p == 0: n //= p result -= result // p ...
from solution import crypto_simulation def test_crypto_simulation_case_7(): result = crypto_simulation(7) assert result == (6, [3, 5]) def test_crypto_simulation_case_10(): result = crypto_simulation(10) assert result == (4, []) def test_crypto_simulation_case_12(): result = crypto_simulation(12)...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def euler_totient(n):", "function_name": "euler_totient", "parameter_list": "(n)" }, { "docstring": null, ...
[ 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": "from typing import List, Tuple\n\ndef gcd(a: int, b: int) -> int:\n while b:\n a, b = b, a % b\n return a\n\ndef euler_totient(n: int) -> int:\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00017097", "row_id": 17097, "seed_ids": "[160]" }
0.525347
Data_Structure_17097
I
[ "gcd", "euler_totient", "powmod", "find_primitive_roots", "crypto_simulation" ]
5
[ [ "crypto_simulation", "euler_totient" ], [ "crypto_simulation", "find_primitive_roots" ], [ "find_primitive_roots", "euler_totient" ], [ "find_primitive_roots", "gcd" ], [ "find_primitive_roots", "powmod" ] ]
5
[]
false
[]
false
pytest
true
[]
true
2e32dab2d1dfcb25c3f445262a202abe47276efd
f607ff1612dc2b3fdd8d5965ce474d7ec6bfbb15
v1.0
instruct
Data_Structure
Data_Structure_17192_I
### Binary Tree Subtree Check #### Scenario: You are working on a software that needs to determine structural similarities between different hierarchical data. One of the application scenarios is to detect if a certain subset of a large dataset matches another smaller dataset in structure and contents. #### Objectiv...
from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_subtree(big: Optional[TreeNode], small: Optional[TreeNode]) -> bool: if not small: return True if not big: return ...
import pytest from solution import TreeNode, is_subtree def test_example_1(): big = TreeNode(3) big.left = TreeNode(4) big.right = TreeNode(5) big.left.left = TreeNode(1) big.left.right = TreeNode(2) small = TreeNode(4) small.left = TreeNode(1) small.right = TreeNode(2) as...
[]
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import Optional\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017192", "row_id": 17192, "seed_ids": "[288]" }
0.571097
Data_Structure_17192
I
[ "is_subtree", "is_identical" ]
2
[ [ "is_subtree", "is_identical" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
38f81195ba63e8e8391c02ec4ab1e9412ab3758b
6bd415c68083167801182fb38337357c0450f00d
v1.0
instruct
Data_Structure
Data_Structure_17278_I
### Question: Implement an Efficient Nearest Neighbor Algorithm **Context:** You are working on a machine learning problem where you need to classify points based on their nearest neighbors in a training set. The current implementation calculates the Euclidean distance to each point in the training set to find the ne...
import math def euclidean_distance(p1, p2): return math.sqrt(sum((a-b)**2 for a, b in zip(p1, p2))) def efficient_nearest_neighbor(x, tSet): """ Returns the label of the nearest neighbor to the point `x` in the training set `tSet`. Parameters: x (tuple): The input point. tSet (dict): The ...
from solution import efficient_nearest_neighbor def test_efficient_nearest_neighbor_basic(): x = (1, 2) tSet = { (2, 3): 'A', (1, 1): 'B', (4, 5): 'C' } assert efficient_nearest_neighbor(x, tSet) == 'B' def test_efficient_nearest_neighbor_empty_set(): x = (1, 2) tSet = {} assert efficient_near...
[ { "docstring": null, "function_declaration": "def euclidean_distance(p1, p2):", "function_name": "euclidean_distance", "parameter_list": "(p1, p2)" }, { "docstring": "Returns the label of the nearest neighbor to the point `x` in the training set `tSet`.\n\nParameters:\nx (tuple): The input p...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef efficient_nearest_neighbor(x, tSet):\n \"\"\"\n Finds the label of the closest point in the training set to the input point using Euc...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017278", "row_id": 17278, "seed_ids": "[260]" }
0.740406
Data_Structure_17278
I
[ "euclidean_distance", "efficient_nearest_neighbor" ]
2
[ [ "efficient_nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
082aec3156de9ad4dd0888cf85b077dfdcba4894
4a34d496b8e40014cb01f6fe8f456a48cbf7bc18
v1.0
instruct
Data_Structure
Data_Structure_17288_I
### Question: Matrix Transformation Implementation You have been provided with a matrix transformation module that consists of several functions to rotate and invert matrices. Write a Python function `matrix_transform(matrix: List[List[int]], transformation: str) -> List[List[int]]` which takes a `matrix` and a `tran...
from typing import List def rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]: N = len(matrix) return [[matrix[N - j - 1][i] for j in range(N)] for i in range(N)] def rotate_counterclockwise(matrix: List[List[int]]) -> List[List[int]]: N = len(matrix) return [[matrix[j][N - i - 1] for j in ...
from solution import matrix_transform def test_rotate_clockwise(): matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] expected = [ [7, 4, 1], [8, 5, 2], [9, 6, 3] ] assert matrix_transform(matrix, 'rotate_clockwise') == expected def test_rotate_countercloc...
[ { "docstring": null, "function_declaration": "def rotate_clockwise(matrix):", "function_name": "rotate_clockwise", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def rotate_counterclockwise(matrix):", "function_name": "rotate_counterclockwise", "par...
[ 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 rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:\n N = len(matrix)\n return [[matrix[N - j - 1][i] for j in ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017288", "row_id": 17288, "seed_ids": "[337]" }
0.516336
Data_Structure_17288
I
[ "rotate_clockwise", "rotate_counterclockwise", "top_left_invert", "bottom_left_invert", "matrix_transform" ]
5
[ [ "matrix_transform", "bottom_left_invert" ], [ "matrix_transform", "rotate_clockwise" ], [ "matrix_transform", "rotate_counterclockwise" ], [ "matrix_transform", "top_left_invert" ] ]
4
[]
false
[]
false
pytest
true
[]
true
c47beb25eac2e707c592e650b53dbbcb6979735b
c4c1f5c9dca91fe5fde19b05cfe4100b40773afb
v1.0
instruct
Data_Structure
Data_Structure_17293_I
### Problem: KMP Algorithm Application in DNA Sequence Search Researchers are often required to find patterns within DNA sequences for analysis. You are tasked with implementing the Knuth-Morris-Pratt (KMP) string matching algorithm to locate patterns within a DNA sequence. #### Function Signature ```python def find_...
from typing import List def compute_lps_array(pattern: str) -> List[int]: """ Computes the Longest Prefix Suffix (LPS) array with pattern as parameter. LPS array is used to skip characters while matching. """ length = 0 # length of the previous longest prefix suffix lps = [0] * len(pattern)...
from solution import find_dna_patterns def test_exact_match(): assert find_dna_patterns("ACGTACGTACG", "ACG") == [0, 4, 8] def test_no_match(): assert find_dna_patterns("ACGTACGTACG", "TTT") == [] def test_multiple_motifs(): assert find_dna_patterns("ACGTACGTACGTACGT", "ACGT") == [0, 4, 8, 12] def test_...
[ { "docstring": "Computes the Longest Prefix Suffix (LPS) array with pattern as parameter. \nLPS array is used to skip characters while matching. ", "function_declaration": "def compute_lps_array(pattern):", "function_name": "compute_lps_array", "parameter_list": "(pattern)" }, { "docstring":...
[ 0, 0, 0, 0, 1, 1, 0, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_dna_patterns(dna_sequence, motif):\n def compute_lps(pattern):\n lps = [0] * len(pattern)\n length = 0\n i = 1\n while...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00017293", "row_id": 17293, "seed_ids": "[93]" }
0.557784
Data_Structure_17293
I
[ "compute_lps_array", "find_dna_patterns" ]
2
[ [ "find_dna_patterns", "compute_lps_array" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e74a8a348bb5c9b8c8c067798792f3dd302825a9
17bbcaa7326ffcbce8985a12b25c7df39d16bbf0
v1.0
instruct
Data_Structure
Data_Structure_17296_I
### Prime Number Verification and Count You are tasked with writing a function that not only verifies whether given numbers are prime but also counts the number of prime numbers within a specified range. #### Function 1: `is_prime(n)` Implement the provided algorithm to check if a number `n` is a prime number. **Inp...
import math def is_prime(n): """ Returns True if n is a prime number, else False. """ 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 Fa...
# Test cases for is_prime from solution import is_prime, count_primes_in_range def test_is_prime_negative_numbers(): assert is_prime(-1) == False def test_is_prime_zero_and_one(): assert is_prime(0) == False assert is_prime(1) == False def test_is_prime_two_and_three(): assert is_prime(2) == True ...
[ { "docstring": "Returns True if n is a prime number, else False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns the count of prime numbers in the range [start, end].", "function_declaration": "def count_primes...
[ 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 is_prime(n):\n \"\"\"\n Check if a number n is a prime number.\n :param n: Integer to check for primality.\n :return: True if n is prime, Fals...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017296", "row_id": 17296, "seed_ids": "[143]" }
0.707586
Data_Structure_17296
I
[ "is_prime", "count_primes_in_range" ]
2
[ [ "count_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c04d009eeee58eb62d996f64bfe6bfee5bfb9064
4365eb1d126a2d96158fd0246396e7dadc4169f1
v1.0
instruct
Data_Structure
Data_Structure_17305_I
### Linked List Intersection Detection **Problem Statement**: You are given two singly linked lists that potentially share a common tail. Write a function `find_intersection(headA, headB)` which returns the intersected node. If the two linked lists have no intersection at all, return `None`. **Function Signature**: ...
class Node: def __init__(self, value=None): self.val = value self.next = None def get_length(head): length = 0 while head is not None: head = head.next length += 1 return length def find_intersection(headA: Node, headB: Node) -> Node: # Step 1: Get lengths of both l...
from solution import Node, find_intersection def test_intersected_lists(): node1 = Node(1) node3 = Node(3) node5 = Node(5) node7 = Node(7) node9 = Node(9) node11 = Node(11) node2 = Node(2) node4 = Node(4) node6 = Node(6) node1.next = node3 node3.next = node5 node5....
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, value=None):\n self.val = value\n self.next = None\n\ndef get_length(head):\n length = 0\n while head ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017305", "row_id": 17305, "seed_ids": "[245]" }
0.552706
Data_Structure_17305
I
[ "get_length", "find_intersection" ]
2
[ [ "find_intersection", "get_length" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
669d04098faee529d3cbd1897f8c1d3231d1122e
0be91558591e9d954ee0dd5fe66ab6acb60bbeac
v1.0
instruct
Data_Structure
Data_Structure_17313_I
You are given a directed graph data structure that supports adding nodes and edges. Using this structure, implement a function to check if there is a **path** between two given nodes in the graph. ### Function Signature: ```python def is_path(graph, start_node, end_node): """ Determine if there is a path betwe...
class DirectedGraph: def __init__(self, graph_dict=None): self.graph_dict = graph_dict if graph_dict else {} def add_node(self, node): if node not in self.graph_dict: self.graph_dict[node] = [] def add_edge(self, from_node, to_node): if from_node in self.graph_dict: ...
from solution import DirectedGraph, is_path def test_path_exists(): graph_dict = { "A": ["B", "C"], "B": ["C", "D"], "C": ["E"], "D": [], "E": ["B"], "F": ["C"] } graph = DirectedGraph(graph_dict) assert is_path(graph, "A", "E") == True def test_path_doe...
[]
[ 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 DirectedGraph:\n def __init__(self, graph_dict=None):\n \"\"\"\n Initializes the DirectedGraph with an optional adjacency list.\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017313", "row_id": 17313, "seed_ids": "[223]" }
0.561054
Data_Structure_17313
I
[ "is_path", "dfs" ]
2
[ [ "is_path", "dfs" ] ]
1
[]
false
[ "DirectedGraph" ]
true
pytest
true
[]
true
e7c2deaf6a90ece9745293d04fff9fbb59bfa5a5
101e658e9c4a3660c9c85a639604979ee8973acc
v1.0
instruct
Data_Structure
Data_Structure_17342_I
### Coding Challenge You are given an array of integers that needs to be sorted in ascending order. Implement a function `optimized_quick_sort` that sorts the array using the Quick Sort algorithm. Your implementation should include: - The core quick sort mechanism. - A pivot selection strategy to improve average-case ...
from typing import List def median_of_three(arr, low, high): mid = (low + high) // 2 pivot_candidates = [(arr[low], low), (arr[mid], mid), (arr[high], high)] pivot_candidates.sort() return pivot_candidates[1][1] def partition(arr, low, high): pivot_index = median_of_three(arr, low, high) arr[h...
from solution import optimized_quick_sort def test_sorted_array(): assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): assert optimized_quick_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_random_array(): assert optimized_quick_sort([3, 1, 4, 1, 5, 9, 2, 6,...
[ { "docstring": null, "function_declaration": "def median_of_three(arr, low, high):", "function_name": "median_of_three", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter...
[ 1, 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 optimized_quick_sort(arr: List[int], simulation: bool = False) -> List[int]:\n def quick_sort(arr, low, high, simulation, de...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017342", "row_id": 17342, "seed_ids": "[25]" }
0.604152
Data_Structure_17342
I
[ "median_of_three", "partition", "quick_sort_helper", "optimized_quick_sort" ]
4
[ [ "optimized_quick_sort", "quick_sort_helper" ], [ "partition", "median_of_three" ], [ "quick_sort_helper", "partition" ] ]
3
[]
false
[]
false
pytest
true
[]
true
59a1fd9c013ee201920a1612bfcd249f9219abc4
7707fd454dcf18cb2a0ef8c15f36e498daab4378
v1.0
instruct
Data_Structure
Data_Structure_17345_I
### Question: Reconstructing a Full Binary Tree from Preorder and Postorder Traversals **Context**: You are a software engineer tasked with restoring the original structure of a full binary tree from given traversal data. You've been provided two sequences that represent the preorder and postorder traversals of the tr...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def buildTree(preorder, postorder): if not preorder or not postorder: return None root_val = preorder.pop(0) root = TreeNode(root_val) if pr...
def test_reconstruct_inorder_case_1(): preorder = [1, 2, 4, 5, 3, 6, 7] postorder = [4, 5, 2, 6, 7, 3, 1] assert reconstruct_inorder(preorder, postorder) == [4, 2, 5, 1, 6, 3, 7] def test_reconstruct_inorder_single_node(): preorder = [1] postorder = [1] assert reconstruct_inorder(preorder, post...
[]
[ 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 TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017345", "row_id": 17345, "seed_ids": "[300]" }
0.579763
Data_Structure_17345
I
[ "buildTree", "inorderTraversal", "reconstruct_inorder" ]
3
[ [ "reconstruct_inorder", "buildTree" ], [ "reconstruct_inorder", "inorderTraversal" ] ]
2
[]
false
[ "TreeNode" ]
true
pytest
false
[]
true
7214a59c8ac2c5a3a799a0029923a592db6ecfd6
ef100c976e95f2a49d93bfd8ffe6f658f970a43a
v1.0
instruct
Data_Structure
Data_Structure_17371_I
### Coding Challenge: Advanced GCD and Binary Algorithms #### Scenario: Your task is to implement a combined function to compute both the Greatest Common Divisor (GCD) and the Least Common Multiple (LCM) of two non-negative integers using efficient algorithms. Additionally, provide a function to count the trailing zer...
def trailing_zero_count(x): """ Calculate the number of trailing zeros in the binary representation of x. """ if x == 0: return 32 # Assuming 32-bit integer for zero handling count = 0 while (x & 1) == 0: x >>= 1 count += 1 return count def gcd_bitwise(a, b): ""...
from solution import trailing_zero_count, gcd_bitwise, lcm def test_trailing_zero_count(): assert trailing_zero_count(0) == 32 assert trailing_zero_count(1) == 0 assert trailing_zero_count(2) == 1 assert trailing_zero_count(3) == 0 assert trailing_zero_count(4) == 2 assert trailing_zero_count(4...
[ { "docstring": "Calculate the number of trailing zeros in the binary representation of x.", "function_declaration": "def trailing_zero_count(x):", "function_name": "trailing_zero_count", "parameter_list": "(x)" }, { "docstring": "Calculate the GCD of a and b using bitwise operations.", "...
[ 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 trailing_zero_count(x):\n \"\"\"\n Calculate the number of trailing zeros in the binary representation of x.\n \"\"\"\n if x == 0:\n re...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017371", "row_id": 17371, "seed_ids": "[166]" }
0.61372
Data_Structure_17371
I
[ "trailing_zero_count", "gcd_bitwise", "lcm" ]
3
[ [ "gcd_bitwise", "trailing_zero_count" ], [ "lcm", "gcd_bitwise" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7c2f65dbb889974c33c51439b410fbbbe7826e66
d8433fb93de21fa32dad88e6700456a202c82466
v1.0
instruct
Data_Structure
Data_Structure_17376_I
As a data scientist, you are tasked to develop an application that requires matrix inversion for solving linear algebra problems. You are given a helper function to invert an n x n matrix which follows the cofactor method to find the inverse. Your objective is to optimize and ensure that the function handles special sc...
from typing import List def determinant(matrix: List[List[int]]) -> int: n = len(matrix) if n == 1: return matrix[0][0] if n == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] det = 0 for c in range(n): sub_matrix = [ [matrix[r][cc] for c...
from solution import optimized_invert_matrix def test_invert_2x2_matrix(): matrix = [ [4, 7], [2, 6] ] expected_inverse = [ [0.6, -0.7], [-0.2, 0.4] ] assert optimized_invert_matrix(matrix) == expected_inverse def test_invert_3x3_matrix(): matrix = [ [1,...
[ { "docstring": null, "function_declaration": "def determinant(matrix):", "function_name": "determinant", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def get_matrix_of_minors(matrix):", "function_name": "get_matrix_of_minors", "parameter_list": "(...
[ 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 get_cofactor(matrix, i, j):\n return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]\n\ndef determinant(matrix)...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00017376", "row_id": 17376, "seed_ids": "[347]" }
0.542336
Data_Structure_17376
I
[ "determinant", "get_matrix_of_minors", "transpose", "get_cofactor_matrix", "optimized_invert_matrix" ]
5
[ [ "get_cofactor_matrix", "get_matrix_of_minors" ], [ "get_matrix_of_minors", "determinant" ], [ "optimized_invert_matrix", "determinant" ], [ "optimized_invert_matrix", "get_cofactor_matrix" ], [ "optimized_invert_matrix", "transpose" ] ]
5
[]
false
[]
false
pytest
true
[]
true
d92b68647016f5494f3ff341ebeea9a0f7110d50
866c2346c66da044d478aacbc813702aafa0817c
v1.0
instruct
Data_Structure
Data_Structure_17381_I
#### Problem Statement You are given a list of integers and you need to determine how many of them are prime numbers. Implement a function that takes a list of integers and returns a count of the prime numbers in the list. #### Function Signature ```python def count_primes(nums: List[int]) -> int: """ Count th...
from math import isqrt from typing import List def is_prime(n: int) -> bool: """ Helper function to check if a number is prime. Args: n: int - An integer. Returns: bool - True if 'n' is a prime number, False otherwise. """ if n <= 1: return False if n <= 3: return ...
from solution import count_primes, is_prime def test_is_prime(): assert not is_prime(1) assert is_prime(2) assert is_prime(3) assert not is_prime(4) assert is_prime(5) assert not is_prime(9) assert is_prime(17) assert not is_prime(18) def test_count_primes_mixed_numbers(): assert c...
[ { "docstring": "Helper function to check if a number is prime.\n\nArgs:\nn: int - An integer.\n\nReturns:\nbool - True if 'n' is a prime number, False otherwise.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Count the nu...
[ 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(num: int) -> bool:\n \"\"\"\n Check if a number is a prime number.\n \n Args:\n num: int - The number t...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017381", "row_id": 17381, "seed_ids": "[143]" }
0.766262
Data_Structure_17381
I
[ "is_prime", "count_primes" ]
2
[ [ "count_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4007c5c182d64683310eb392327369757629aa89
3a3daa4ba9cc2737896a0c2bbe095306ecc3c062
v1.0
instruct
Data_Structure
Data_Structure_17401_I
#### Background Bitonic Sort is a fast, parallelizable sorting algorithm that works efficiently on arrays of sizes which are a power of two. The main idea is to divide the array into sub-arrays, sort them in opposing orders, and then merge them to form a bitonic sequence that can be recursively sorted. #### Problem St...
from typing import List def bitonic_compare_and_swap(arr: List[int], direction: bool, start: int, length: int): half = length // 2 for i in range(start, start + half): if (arr[i] > arr[i + half]) == direction: arr[i], arr[i + half] = arr[i + half], arr[i] def bitonic_merge(arr: List[int], ...
import pytest from solution import custom_bitonic_sort def test_bitonic_sort_ascending(): arr = [3, 7, 4, 8, 6, 2, 1, 5] sorted_arr = custom_bitonic_sort(arr, True) assert sorted_arr == [1, 2, 3, 4, 5, 6, 7, 8] def test_bitonic_sort_descending(): arr = [3, 7, 4, 8, 6, 2, 1, 5] sorted_arr = custom_...
[ { "docstring": null, "function_declaration": "def bitonic_compare_and_swap(arr, direction, start, length):", "function_name": "bitonic_compare_and_swap", "parameter_list": "(arr, direction, start, length)" }, { "docstring": null, "function_declaration": "def bitonic_merge(arr, direction,...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef bitonic_compare_and_swap(arr: List[int], i: int, j: int, ascending: bool):\n if (arr[i] > arr[j]) == ascending:\n arr...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017401", "row_id": 17401, "seed_ids": "[17]" }
0.657869
Data_Structure_17401
I
[ "bitonic_compare_and_swap", "bitonic_merge", "bitonic_sort_recursive", "custom_bitonic_sort" ]
4
[ [ "bitonic_merge", "bitonic_compare_and_swap" ], [ "bitonic_sort_recursive", "bitonic_merge" ], [ "custom_bitonic_sort", "bitonic_sort_recursive" ] ]
3
[]
false
[]
false
pytest
true
[]
true
dce02ab7fce4242251a6319ceaf0020b485a6e36
588a96a603ebfc719e95200284a9ef7d9e91e8a8
v1.0
instruct
Data_Structure
Data_Structure_17429_I
### RSA Encryption Enhancement The provided RSA encryption implementation has a modular exponentiation mechanism in place but can be inefficient, especially in generating prime numbers and finding modular inverses. To assess your understanding of RSA and algorithm optimization, enhance the provided key generation algo...
import random def is_prime(n, k=5): # Miller-Rabin primality test if n <= 1: return False if n <= 3: return True if n % 2 == 0: return False r, s = 0, n - 1 while s % 2 == 0: r += 1 s //= 2 for _ in range(k): a = random.randint(2, n - 2) ...
from solution import generate_key_enhanced, is_prime, gen_prime, egcd, modinv def test_is_prime(): assert is_prime(2) assert is_prime(11) assert not is_prime(1) assert not is_prime(4) assert is_prime(7919) # Large prime for a quick check def test_gen_prime(): prime_16 = gen_prime(16) asse...
[ { "docstring": null, "function_declaration": "def is_prime(n, k=5):", "function_name": "is_prime", "parameter_list": "(n, k=5)" }, { "docstring": null, "function_declaration": "def gen_prime(bit_length):", "function_name": "gen_prime", "parameter_list": "(bit_length)" }, { ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, gcd\nimport sympy\n\ndef modinv(a, m):\n \"\"\"\n Returns the modular inverse of a under modulo m using the Ex...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00017429", "row_id": 17429, "seed_ids": "[154]" }
0.609182
Data_Structure_17429
I
[ "is_prime", "gen_prime", "egcd", "modinv", "generate_key_enhanced" ]
5
[ [ "gen_prime", "is_prime" ], [ "generate_key_enhanced", "gen_prime" ], [ "generate_key_enhanced", "modinv" ], [ "modinv", "egcd" ] ]
4
[]
false
[]
false
pytest
true
[]
true
00887039e89542931c1168e1c85af6eed935aba5
ba1695ba640571192dc9887cad8002ca69bccee2
v1.0
instruct
Data_Structure
Data_Structure_17451_I
### Diffie-Hellman Key Exchange Enhancement Due to the reliance on the security of the Diffie-Hellman key exchange algorithm, it's essential to handle large primes and ensure efficient calculations. Given the snippets above, your task is to implement an enhanced version of the Diffie-Hellman Key Exchange that ensures ...
import random # Miller-Rabin Primality Test for secure primality check def miller_rabin_test(n, k=40): if n <= 1: return False if n <= 3: return True if n % 2 == 0: return False r, s = 0, n - 1 while s % 2 == 0: r += 1 s //= 2 for _ in range(k): ...
def test_miller_rabin_test(): assert miller_rabin_test(11) == True assert miller_rabin_test(2) == True assert miller_rabin_test(1) == False assert miller_rabin_test(15) == False def test_enhanced_diffie_hellman_key_exchange(): p = 99999989 # A large pseudo prime a = 2 shared_key = enhanced...
[ { "docstring": null, "function_declaration": "def miller_rabin_test(n, k=40):", "function_name": "miller_rabin_test", "parameter_list": "(n, k=40)" }, { "docstring": null, "function_declaration": "def modular_inverse(a, m):", "function_name": "modular_inverse", "parameter_list": ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\n# Miller-Rabin Primality Test for secure primality check\ndef miller_rabin_test(n, k=40):\n if n <= 1:\n return False\n if n <= ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017451", "row_id": 17451, "seed_ids": "[146]" }
0.494074
Data_Structure_17451
I
[ "miller_rabin_test", "modular_inverse", "pollards_rho_order", "enhanced_diffie_hellman_key_exchange" ]
4
[ [ "enhanced_diffie_hellman_key_exchange", "miller_rabin_test" ], [ "enhanced_diffie_hellman_key_exchange", "pollards_rho_order" ] ]
2
[]
false
[]
false
pytest
false
[]
true
f927dedab1fd6484f149cf65866823b6113b751d
cab4bc7aa007be1c417046028de27a43071bb804
v1.0
instruct
Data_Structure
Data_Structure_17495_I
You have been given an implementation of the Interpolation Search algorithm. Your task is to implement a function that uses this algorithm to find multiple search keys in a sorted array. Specifically, you need to return a list of indices corresponding to each search key. If a search key is not present in the array, -1 ...
from typing import List def interpolation_search(array: List[int], key: int) -> int: low = 0 high = len(array) - 1 while low <= high and array[low] <= key <= array[high]: if low == high: if array[low] == key: return low return -1 pos = low + ((high ...
from solution import multi_interpolation_search def test_search_present_keys(): array = [5, 10, 12, 14, 17, 20, 21] search_keys = [10, 12] assert multi_interpolation_search(array, search_keys) == [1, 2] def test_search_absent_keys(): array = [5, 10, 12, 14, 17, 20, 21] search_keys = [55, -5] a...
[ { "docstring": null, "function_declaration": "def interpolation_search(array, key):", "function_name": "interpolation_search", "parameter_list": "(array, key)" }, { "docstring": null, "function_declaration": "def multi_interpolation_search(array, search_keys):", "function_name": "mul...
[ 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 interpolation_search(array: List[int], key: int) -> int:\n low = 0\n high = len(array) - 1\n\n while low <= high and a...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017495", "row_id": 17495, "seed_ids": "[192]" }
0.554847
Data_Structure_17495
I
[ "interpolation_search", "multi_interpolation_search" ]
2
[ [ "multi_interpolation_search", "interpolation_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e255b1b2eac68cd55cd89331f233d022d58d9f51
fc7b4633591cdbbcb013f22e0d719ee03b22532b
v1.0
instruct
Data_Structure
Data_Structure_17526_I
You've been tasked to extend a factorial calculation function to handle a list of integers, each potentially requiring the result to be taken modulo some number. **Task**: Write a function `factorial_list(numbers: List[int], mod: int = None) -> List[int]` that takes a list of non-negative integers and an optional posi...
from typing import List, Optional def factorial(n: int, mod: Optional[int] = None) -> int: result = 1 for i in range(1, n + 1): result *= i if mod: result %= mod return result def factorial_list(numbers: List[int], mod: Optional[int] = None) -> List[int]: return [factorial(...
from solution import factorial_list def test_factorial_list_no_mod(): assert factorial_list([0, 1, 2, 3, 5]) == [1, 1, 2, 6, 120] def test_factorial_list_with_mod(): assert factorial_list([0, 1, 2, 3, 5], mod=100) == [1, 1, 2, 6, 20] assert factorial_list([0, 1, 2, 3, 5], mod=10) == [1, 1, 2, 6, 0] def t...
[ { "docstring": null, "function_declaration": "def factorial(n, mod=None):", "function_name": "factorial", "parameter_list": "(n, mod=None)" }, { "docstring": null, "function_declaration": "def factorial_list(numbers, mod=None):", "function_name": "factorial_list", "parameter_list...
[ 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 factorial(n: int, mod: int = None) -> int:\n \"\"\"\n Returns the factorial of n optionally taken modulo `mod`.\n \"\"...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00017526", "row_id": 17526, "seed_ids": "[139]" }
0.647068
Data_Structure_17526
I
[ "factorial", "factorial_list" ]
2
[ [ "factorial_list", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
69aa44a7b826e37267a83c42a291135f6e3987be
0585767b394394cee2e098913791b8d215b303eb
v1.0
instruct
Data_Structure
Data_Structure_17553_I
You are assigned to implement a prime-checking utility as part of a broader cryptographic application. A prime number is defined as a number that is greater than 1 and is not divisible by any number other than 1 and itself. #### Function Requirements You need to implement the function `find_primes_in_range(start, end...
def is_prime(n): """Check if a number is prime.""" if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def find...
from solution import find_primes_in_range def test_find_primes_in_range_small(): assert find_primes_in_range(1, 10) == [2, 3, 5, 7] assert find_primes_in_range(10, 50) == [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] def test_find_primes_in_range_single_prime(): assert find_primes_in_range(29, 29) == [29] ...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of all prime numbers within the range [start, end].", "function_declaration": "def find_primes_in_range(start, ...
[ 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 is_prime(n):\n \"\"\"\n Determines if n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017553", "row_id": 17553, "seed_ids": "[143]" }
0.665551
Data_Structure_17553
I
[ "is_prime", "find_primes_in_range" ]
2
[ [ "find_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
988323a838db3c93d1cf1be64c4a69890daf5122
9ee89b47469c8f6ea40be55c412c956584017a04
v1.0
instruct
Data_Structure
Data_Structure_17569_I
### Advanced Graph Traversal: Bi-Directional Search #### Context: You are given an undirected graph and need to find the shortest path from a starting node to a target node. While traditional BFS ensures finding the shortest path in unweighted graphs, for very large graphs, it can be more efficient to use a bi-directi...
from collections import deque def bi_directional_search(graph, start, target): """ Performs a bi-directional BFS to find the shortest path from start to target. """ if start == target: return [start] # Initialize BFS queues for forward and backward search forward_queue = deque([start])...
import pytest from solution import bi_directional_search def test_simple_graph(): graph = { 1: [2, 3], 2: [1, 4], 3: [1, 4], 4: [2, 3, 5], 5: [4] } assert bi_directional_search(graph, 1, 5) == [1, 2, 4, 5] or bi_directional_search(graph, 1, 5) == [1, 3, 4, 5] def te...
[ { "docstring": "Performs a bi-directional BFS to find the shortest path from start to target.", "function_declaration": "def bi_directional_search(graph, start, target):", "function_name": "bi_directional_search", "parameter_list": "(graph, start, target)" }, { "docstring": null, "functi...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef bi_directional_search(graph, start, target):\n if start == target:\n return [start]\n \n # Initialize two...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017569", "row_id": 17569, "seed_ids": "[224]" }
0.585217
Data_Structure_17569
I
[ "bi_directional_search", "found_path", "reconstruct_path" ]
3
[ [ "bi_directional_search", "found_path" ], [ "bi_directional_search", "reconstruct_path" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ff3d2a1405ed94f8a3d2d5790c3b9d88a0b99f26
8e563926d79081b143835605dbed5242a7c7c8c9
v1.0
instruct
Data_Structure
Data_Structure_17581_I
You are tasked to write a function that employs the `search_insert` helper method to efficiently insert elements into an already sorted list such that the list remains sorted after each insertion. ### Task Description Write a function `insert_and_sort(sorted_list, values)` that takes a sorted list of integers (`sorte...
def search_insert(array, val): """ Helper function to find the insertion point for `val` in `array`. Uses binary search for efficiency. """ low = 0 high = len(array) - 1 while low <= high: mid = low + (high - low) // 2 if val > array[mid]: low = mid + 1 el...
from solution import search_insert, insert_and_sort def test_search_insert_middle(): assert search_insert([1, 3, 5, 7], 4) == 2 def test_search_insert_smallest(): assert search_insert([1, 3, 5, 7], 0) == 0 def test_search_insert_largest(): assert search_insert([1, 3, 5, 7], 8) == 4 def test_search_inser...
[ { "docstring": "Helper function to find the insertion point for `val` in `array`.\nUses binary search for efficiency.", "function_declaration": "def search_insert(array, val):", "function_name": "search_insert", "parameter_list": "(array, val)" }, { "docstring": "Inserts each value from `val...
[ 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 search_insert(array, val):\n \"\"\"\n A helper function to find the index where the value should be inserted\n to maintain the sorted order.\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017581", "row_id": 17581, "seed_ids": "[199]" }
0.605762
Data_Structure_17581
I
[ "search_insert", "insert_and_sort" ]
2
[ [ "insert_and_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1f4400d6e09ca41011172c5012ac04a30554781c
af1ca1ef7329a3d8f465489ebdb4a7bc9367c9fc
v1.0
instruct
Data_Structure
Data_Structure_17588_I
### Question: You are given an array of integers. Your task is to implement a Max Priority Queue with the following operations using max heap: `insert`, `extract_max`, and `get_max` which must all run in O(log n) time complexity. #### Function Specifications: - **insert(arr, key)**: Takes two parameters, the current ...
def insert(arr, key): """ Inserts a key into the priority queue. """ arr.append(key) _sift_up(arr, len(arr) - 1) return arr def extract_max(arr): """ Extracts the maximum key from the priority queue. """ if len(arr) == 0: return arr, None max_element = arr[0] ar...
from solution import insert, extract_max, get_max def test_insert(): arr = [] arr = insert(arr, 10) assert arr == [10] arr = insert(arr, 5) assert arr == [10, 5] arr = insert(arr, 30) assert arr == [30, 5, 10] def test_extract_max(): arr = [30, 5, 10] arr, max_element = extract_max...
[ { "docstring": "Inserts a key into the priority queue.", "function_declaration": "def insert(arr, key):", "function_name": "insert", "parameter_list": "(arr, key)" }, { "docstring": "Extracts the maximum key from the priority queue.", "function_declaration": "def extract_max(arr):", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def insert(arr, key):\n \"\"\"\n Inserts a new key into the max priority queue.\n \"\"\"\n arr.append(key)\n _heapify_up(arr, len(arr) - 1)\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017588", "row_id": 17588, "seed_ids": "[8]" }
0.628586
Data_Structure_17588
I
[ "insert", "extract_max", "get_max", "_sift_up", "_sift_down" ]
5
[ [ "extract_max", "_sift_down" ], [ "insert", "_sift_up" ] ]
2
[]
false
[]
false
pytest
true
[]
true
15259aab51006bc9f6b86911f0cfa2da4ffaa7c8
9509ced9d990a91c88d5fcbe0d69fe696ec4b1b8
v1.0
instruct
Data_Structure
Data_Structure_17592_I
### RSA Implementation and Encryption/Decryption Implement the RSA algorithm by completing the three functions: `generate_key(bits, seed)`, `encrypt(data, e, n)`, and `decrypt(data, d, n)`. You will follow the principles of RSA encryption/decryption as described. **Function Specifications**: 1. **generate_key(bits, s...
import random from sympy import isprime, mod_inverse def generate_prime(bits, rng): while True: candidate = rng.getrandbits(bits) if isprime(candidate): return candidate def generate_key(bits, seed=None): rng = random.Random(seed) p = generate_prime(bits // 2, rng) q = gene...
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) def test_encrypt_decrypt_small_data(): n, e, d = generate_key(16, seed=42) data = 20 encrypted_data...
[ { "docstring": null, "function_declaration": "def generate_prime(bits, rng):", "function_name": "generate_prime", "parameter_list": "(bits, rng)" }, { "docstring": null, "function_declaration": "def generate_key(bits, seed=None):", "function_name": "generate_key", "parameter_list...
[ 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(bits, seed=None):\n \"\"\"\n Generates RSA keys of specified bit length.\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017592", "row_id": 17592, "seed_ids": "[154]" }
0.607747
Data_Structure_17592
I
[ "generate_prime", "generate_key", "encrypt", "decrypt" ]
4
[ [ "generate_key", "generate_prime" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
27e3f4c13c7ea7cfc881fd095ea0c37e1a6f1941
f55f68fe16dc4aa5b0eb91eb404ec32527b56af3
v1.0
instruct
Data_Structure
Data_Structure_17641_I
#### Context You are given a graph representing a network of water pipes, where each pipe has a specified capacity. The objective is to determine the maximum amount of water that can flow from the source (starting point) to the sink (ending point) by implementing the Edmonds-Karp algorithm, which uses BFS to find augme...
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_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_case...
[ { "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"...
[ 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(residual_graph, source, sink, parent):\n \"\"\"\n Performs BFS on the residual graph to find if there's an augm...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017641", "row_id": 17641, "seed_ids": "[229]" }
0.627314
Data_Structure_17641
I
[ "bfs", "maximum_flow_bfs" ]
2
[ [ "maximum_flow_bfs", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2b1b27dd39a3ba1410b68f89a6b6c57e831ba81b
792a076484b83d945f93bc175dbc794e0788596f
v1.0
instruct
Data_Structure
Data_Structure_17643_I
### Question: Bit Insertion Challenge You are given two functions `insert_one_bit` and `insert_mult_bits` that manipulate bits within a number. Your task is to extend and improve these functions to handle various scenarios and then write a function `bit_insertion_handler`. ### Function Signature ```python def insert_...
def insert_one_bit(num: int, bit: int, pos: int) -> int: """ Insert a single bit at the specified position of the number. """ mask = 1 << pos return (num & ~mask) | ((bit & 1) << pos) def insert_mult_bits(num: int, bits: int, length: int, pos: int) -> int: """ Insert multiple bits at the sp...
from solution import insert_one_bit, insert_mult_bits, bit_insertion_handler def test_insert_one_bit(): assert insert_one_bit(21, 1, 2) == 21 | (1 << 2) assert insert_one_bit(21, 0, 2) == 21 & ~(1 << 2) assert insert_one_bit(0, 1, 0) == 1 assert insert_one_bit(0, 0, 0) == 0 assert insert_one_bit(1,...
[ { "docstring": "Insert a single bit at the specified position of the number.", "function_declaration": "def insert_one_bit(num, bit, pos):", "function_name": "insert_one_bit", "parameter_list": "(num, bit, pos)" }, { "docstring": "Insert multiple bits at the specified position of the number....
[ 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 insert_one_bit(num: int, bit: int, pos: int) -> int:\n \"\"\"\n Inserts a single bit into the number at the specified position.\n \n Parameter...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017643", "row_id": 17643, "seed_ids": "[211]" }
0.628004
Data_Structure_17643
I
[ "insert_one_bit", "insert_mult_bits", "bit_insertion_handler" ]
3
[ [ "bit_insertion_handler", "insert_mult_bits" ], [ "bit_insertion_handler", "insert_one_bit" ] ]
2
[]
false
[]
false
pytest
true
[]
true
efbadfc453485ace976e284fad10c4c175951bfc
d2828f01f5e035a0b7b0870e3168636a3c46a2c2
v1.0
instruct
Data_Structure
Data_Structure_17685_I
### Maximum Flow Problem #### Background You are given a network of pipes represented as a graph where: - Each node represents a junction. - Each edge represents a pipe with a certain capacity. - The first node (index 0) is the source from which water is sent. - The last node (index n-1) is the sink where water is col...
def dfs(capacity, flow, source, sink, visited): stack = [source] parents_map = {source: None} while stack: current_node = stack.pop() if current_node == sink: break for neighbor, cap in enumerate(capacity[current_node]): if cap - flow[current_node, neighb...
from solution import maximum_flow_dfs def test_basic_flow(): graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] assert maximum_flow_dfs(graph) == 23 def test_no_path(): ...
[ { "docstring": null, "function_declaration": "def dfs(capacity, flow, source, sink, visited):", "function_name": "dfs", "parameter_list": "(capacity, flow, source, sink, visited)" }, { "docstring": null, "function_declaration": "def maximum_flow_dfs(adjacency_matrix):", "function_nam...
[ 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 dfs(capacity, flow, source, sink, visited):\n stack = [source]\n parents_map = {source: None}\n \n while stack:\n current_node = stack....
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017685", "row_id": 17685, "seed_ids": "[241]" }
0.617964
Data_Structure_17685
I
[ "dfs", "maximum_flow_dfs" ]
2
[ [ "maximum_flow_dfs", "dfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
50fd1efcbe913bd6267324995a13ee76b6b8fe0d
33bddefba9134626b07517fd3d31fde30353ecf4
v1.0
instruct
Data_Structure
Data_Structure_17718_I
You are given a list of floating-point numbers with values uniformly distributed in the range [0, 1). Your task is to implement the `bucket_sort` algorithm as described, using the `next_sort` function for sorting individual buckets. This question aims to evaluate your understanding of the bucket sort technique, especia...
from typing import List # This function simulates the sorting mechanism within each bucket. # In this example, let's use a simple insertion sort for sorting the buckets. def next_sort(arr: List[float]) -> List[float]: for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key ...
from solution import bucket_sort def test_bucket_sort_sample1(): arr = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68] expected = [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94] assert bucket_sort(arr) == expected def test_bucket_sort_sample2(): arr = [0.4, 0.1, 0.2, 0.3] ...
[ { "docstring": null, "function_declaration": "def next_sort(arr):", "function_name": "next_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 next_sort(bucket: List[float]) -> List[float]:\n \"\"\"\n A simple insertion sort implementation to sort individual bucke...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017718", "row_id": 17718, "seed_ids": "[26]" }
0.500772
Data_Structure_17718
I
[ "next_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "next_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
34ad45b964c81dd9f8b13bddbe7c4dc2df4dd00b
6be626e5e137695076d8052f768a90ba3b8836fe
v1.0
instruct
Data_Structure
Data_Structure_17803_I
You are tasked with implementing a secure communication channel using the Diffie-Hellman key exchange algorithm. This algorithm allows two parties, Alice and Bob, to establish a shared secret over an unsecured channel by leveraging properties of prime numbers and primitive roots. ### Objective Create a function named ...
from random import randint from sympy import isprime, primitive_root def prime_check(num: int) -> bool: return isprime(num) def find_primitive_root(n: int) -> list: try: return [primitive_root(n)] except ValueError: return [] def alice_private_key(p: int) -> int: return randint(2, p-1...
from solution import diffie_hellman_key_exchange def test_valid_diffie_hellman(): assert diffie_hellman_key_exchange(2, 11) == True def test_invalid_prime_p(): assert diffie_hellman_key_exchange(2, 10) == False def test_invalid_primitive_root_a(): assert diffie_hellman_key_exchange(5, 11) == False def t...
[ { "docstring": null, "function_declaration": "def prime_check(num):", "function_name": "prime_check", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def find_primitive_root(n):", "function_name": "find_primitive_root", "parameter_list": "(n)" }, { ...
[ 0, 0, 0, 0, 0, 1, 0, 1, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sympy import isprime, primitive_root\nimport random\n\ndef prime_check(num: int) -> bool:\n return isprime(num)\n\ndef find_primitive_root(n: int) -> ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00017803", "row_id": 17803, "seed_ids": "[146]" }
0.420949
Data_Structure_17803
I
[ "prime_check", "find_primitive_root", "alice_private_key", "alice_public_key", "bob_private_key", "bob_public_key", "alice_shared_key", "bob_shared_key", "diffie_hellman_key_exchange" ]
9
[ [ "diffie_hellman_key_exchange", "alice_private_key" ], [ "diffie_hellman_key_exchange", "alice_public_key" ], [ "diffie_hellman_key_exchange", "alice_shared_key" ], [ "diffie_hellman_key_exchange", "bob_private_key" ], [ "diffie_hellman_key_exchange", "bob_pu...
8
[]
false
[]
false
pytest
true
[ "sympy" ]
false
72ab67fd709079fde6b4316cbbbc70958079aff1
98163a4af2ab9f84e966829b008149c7da7d880f
v1.0
instruct
Data_Structure
Data_Structure_17809_I
**Scenario**: You have been hired by a tech company to optimize their database sorting functionality. The database primarily stores numerical records which need to be sorted frequently for reporting purposes. The current implementation uses Quick Sort but exhibits poor performance with certain datasets such as those th...
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, low, high): mid = (low + high) // 2 if arr[low] > ...
from solution import optimized_quick_sort def test_optimized_quick_sort_sorted_array(): arr = [1, 2, 3, 4, 5] assert optimized_quick_sort(arr) == [1, 2, 3, 4, 5] def test_optimized_quick_sort_reverse_sorted_array(): arr = [5, 4, 3, 2, 1] assert optimized_quick_sort(arr) == [1, 2, 3, 4, 5] def test_op...
[ { "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, low, high):", "function_name": "median_of_three", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def insertion_sort(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_2
{ "original_instruction": "", "prompt_id": "00017809", "row_id": 17809, "seed_ids": "[25]" }
0.55029
Data_Structure_17809
I
[ "insertion_sort", "median_of_three", "partition", "quick_sort", "optimized_quick_sort" ]
5
[ [ "optimized_quick_sort", "quick_sort" ], [ "partition", "median_of_three" ], [ "quick_sort", "insertion_sort" ], [ "quick_sort", "partition" ] ]
4
[]
false
[]
false
pytest
true
[]
true
2723124275504a2b6c5c0fb4cd73ca35a82bd446
9259231077b0a5e3b1299bf3616b5dd92053091f
v1.0
instruct
Data_Structure
Data_Structure_17859_I
#### Job Requirements Implement a function `def intersection(h1: Node, h2: Node) -> Optional[Node]:` which takes two singly linked lists and returns the node where they intersect. If the two linked lists do not intersect, return `None`. To help you understand the problem, consider the example below: ```python class ...
class Node: def __init__(self, val: int): self.val = val self.next = None def get_length_and_tail(node: Node) -> tuple: length = 0 while node: length += 1 if not node.next: return length, node node = node.next return length, None def intersection(h1:...
def test_intersection(): from solution import Node, intersection # Test case 1: Intersecting lists a1 = Node(1) b1 = Node(3) c1 = Node(5) d = Node(7) e = Node(9) f = Node(11) a2 = Node(2) b2 = Node(4) c2 = Node(6) a1.next = b1 b1.next = c1 c1.next = d d...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import Optional\n\nclass Node:\n def __init__(self, val: int):\n self.val = val\n self.next = None\n\ndef intersection(h1: Node, ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017859", "row_id": 17859, "seed_ids": "[245]" }
0.577558
Data_Structure_17859
I
[ "get_length_and_tail", "intersection" ]
2
[ [ "intersection", "get_length_and_tail" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
2f86f1f25f805b7f1fd0b28a541553b0c2039048
776f594a2040bcf79578448d18b6371d59bc3608
v1.0
instruct
Data_Structure
Data_Structure_17871_I
### Scenario You are provided a collection of integers that might contain duplicates. You need to generate all possible subsets (the power set) of these integers such that the solution set does not contain duplicate subsets. Write a function `unique_subsets(nums: List[int]) -> List[List[int]]` that returns all possibl...
from typing import List def unique_subsets(nums: List[int]) -> List[List[int]]: """ Returns all unique subsets of a given list of integers, including handling duplicates. """ nums.sort() # Sort the array to handle duplicates easily result = [] backtrack(nums, 0, [], result) return result ...
from solution import unique_subsets def test_unique_subsets_empty_input(): assert unique_subsets([]) == [[]] def test_unique_subsets_no_duplicates(): assert unique_subsets([1, 2, 3]) == [ [], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3] ]...
[ { "docstring": "Returns all unique subsets of a given list of integers, including handling duplicates.", "function_declaration": "def unique_subsets(nums):", "function_name": "unique_subsets", "parameter_list": "(nums)" }, { "docstring": null, "function_declaration": "def backtrack(nums,...
[ 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 unique_subsets(nums: List[int]) -> List[List[int]]:\n \"\"\"\n Returns all unique subsets of the input list nums.\n \"...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017871", "row_id": 17871, "seed_ids": "[109]" }
0.620677
Data_Structure_17871
I
[ "unique_subsets", "backtrack" ]
2
[ [ "unique_subsets", "backtrack" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b2eab59ec52ad2e3a64477851efd054db7050f4c
0dcfe6e1df238bf8e560e9611698024907be74a4
v1.0
instruct
Data_Structure
Data_Structure_17915_I
### Radix Sort Implementation and Testing Given the radix sort algorithm provided, you are required to implement and test a modified version that can handle a list of non-negative integers. Your function should also handle cases where the list might be empty. Moreover, you need to develop a series of unit tests to ens...
from typing import List def radix_sort(arr: List[int]) -> List[int]: if len(arr) == 0: return arr max_num = max(arr) exp = 1 while max_num // exp > 0: arr = counting_sort(arr, exp) exp *= 10 return arr def counting_sort(arr: List[int], exp: int) -> List[int]: n = len(a...
from solution import radix_sort def test_radix_sort_basic(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_empty(): assert radix_sort([]) == [] def test_radix_sort_single_element(): assert radix_sort([1]) == [1] def test_radix_sort_all_same...
[ { "docstring": null, "function_declaration": "def radix_sort(arr):", "function_name": "radix_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def counting_sort(arr, exp):", "function_name": "counting_sort", "parameter_list": "(arr, exp)" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \n for i in range(n):\n index = arr[i] // exp\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017915", "row_id": 17915, "seed_ids": "[15]" }
0.634208
Data_Structure_17915
I
[ "radix_sort", "counting_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bca60f554d70410fbf3f1342478bc9b8f038dc4e
4c5d602837a4182926979fd3ee2462538e1abe12
v1.0
instruct
Data_Structure
Data_Structure_17955_I
### Radix Sort Challenge #### Scenario You're part of a team working on optimizing the performance of the database of a retail application. Your task is to efficiently sort large sets of transaction IDs consisting of positive integers. The radix sort algorithm has been recommended for this task due to its efficient ha...
def optimized_radix_sort(arr): """ Sorts a list of non-negative integers using an optimized radix sort algorithm. Parameters: arr (List[int]): A list of non-negative integers Returns: List[int]: A list of integers sorted in ascending order """ if len(arr) == 0: return [...
from solution import optimized_radix_sort def test_optimized_radix_sort_regular_cases(): assert optimized_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_optimized_radix_sort_empty_list(): assert optimized_radix_sort([]) == [] def test_optimized_radix_sort_single_e...
[ { "docstring": "Sorts a list of non-negative integers using an optimized radix sort algorithm.\n\nParameters:\narr (List[int]): A list of non-negative integers\n\nReturns:\nList[int]: A list of integers sorted in ascending order", "function_declaration": "def optimized_radix_sort(arr):", "function_name"...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def optimized_radix_sort(arr):\n \"\"\"\n Sorts a list of non-negative integers using an optimized radix sort algorithm.\n \n Parameters:\n arr...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017955", "row_id": 17955, "seed_ids": "[15]" }
0.621158
Data_Structure_17955
I
[ "optimized_radix_sort", "counting_sort_by_digit" ]
2
[ [ "optimized_radix_sort", "counting_sort_by_digit" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ab94fdc6efbea503ab87e8068869739e692f8d92
45ae75054802dba6f0a37ff3e721c9f11e876554
v1.0
instruct
Data_Structure
Data_Structure_17973_I
### Bogo Sort Reimagined for Binary Strings As an exercise in understanding inefficient algorithms, we are going to use an impractical sorting method called Bogo Sort on a collection of binary strings. A binary string is a string consisting only of characters '0' and '1'. Your task is to write a function `bogo_sort_b...
import random from typing import List def is_sorted(binary_strings: List[str]) -> bool: for i in range(len(binary_strings) - 1): if binary_strings[i] > binary_strings[i + 1]: return False return True def bogo_sort_binary_strings(binary_strings: List[str], simulation: bool = False) -> List[...
from solution import bogo_sort_binary_strings def test_bogo_sort_already_sorted(): assert bogo_sort_binary_strings(["001", "010", "011"]) == ["001", "010", "011"] def test_bogo_sort_unsorted(): assert bogo_sort_binary_strings(["110", "101", "111", "100"]) == ["100", "101", "110", "111"] def test_bogo_sort_re...
[ { "docstring": null, "function_declaration": "def is_sorted(binary_strings):", "function_name": "is_sorted", "parameter_list": "(binary_strings)" }, { "docstring": null, "function_declaration": "def bogo_sort_binary_strings(binary_strings, simulation=False):", "function_name": "bogo_...
[ 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 random\n\ndef is_sorted(binary_strings: List[str]) -> bool:\n \"\"\"\n Checks if the list of binary strings is sorted.\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017973", "row_id": 17973, "seed_ids": "[16]" }
0.577176
Data_Structure_17973
I
[ "is_sorted", "bogo_sort_binary_strings" ]
2
[ [ "bogo_sort_binary_strings", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ffa3585b82d87b7dbf3646098a7d88f54cb202ee
16aac776f9643b00237f17697686002019389e35
v1.0
instruct
Data_Structure
Data_Structure_17988_I
### Context You have been tasked with developing a new approach for calculating combinations in statistics. The factorial function, which is fundamental for combinations, is often computed multiple times with high values of `n`. To ensure reliability and performance, you'll enhance it with an additional feature to comp...
def factorial(n): result = 1 for i in range(2, n + 1): result *= i return result def combination(n, k, mod=None): if k < 0 or k > n: raise ValueError("k must be between 0 and n.") if k == 0 or k == n: return 1 num = factorial(n) denom = factorial(k) * factorial(n -...
from solution import combination def test_combination_basic(): assert combination(5, 2) == 10 def test_combination_with_mod(): assert combination(5, 2, 1000) == 10 assert combination(20, 10, 1000) == 184756 % 1000 def test_combination_large_inputs(): assert combination(50, 5, 100000) == 2118760 % 100...
[ { "docstring": null, "function_declaration": "def factorial(n):", "function_name": "factorial", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def combination(n, k, mod=None):", "function_name": "combination", "parameter_list": "(n, k, mod=None)" } ]
[ 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 combination(n: int, k: int, mod: int = None) -> int:\n \"\"\"\n Calculate the number of combinations C(n, k), which is the number of ways to choose\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017988", "row_id": 17988, "seed_ids": "[139]" }
0.609137
Data_Structure_17988
I
[ "factorial", "combination" ]
2
[ [ "combination", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ec8c8ba1a9c73416771167e443268b07b07358c3
2eb6e57362c0d851c771f4b7f0bfbeeaf796b6ac
v1.0
instruct
Data_Structure
Data_Structure_18074_I
You are given a binary tree with integer values in its nodes, and you need to traverse and return the values in the in-order manner, but this time, you need to return a list which represents the level-wise in-order traversal, i.e., For each level of the tree, you will perform an in-order traversal and return nodes pres...
class Node: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def inorder_traversal(root, level, levels): """ Helper method to perform inorder traversal. """ if root is None: return # Ensure the current le...
from solution import Node, level_wise_inorder_traversal def test_level_wise_inorder_traversal_singleton(): root = Node(1) assert level_wise_inorder_traversal(root) == [[1]] def test_level_wise_inorder_traversal_basic(): root = Node(1, Node(2), Node(3)) assert level_wise_inorder_traversal(root) == [[1]...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef level_...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018074", "row_id": 18074, "seed_ids": "[310]" }
0.494389
Data_Structure_18074
I
[ "inorder_traversal", "level_wise_inorder_traversal" ]
2
[ [ "level_wise_inorder_traversal", "inorder_traversal" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
d0b4b0bd440f346b1d7292311b21a1efc0d9bbad
acb8401cdb04d5314b98b579feb33652deef2a7a
v1.0
instruct
Data_Structure
Data_Structure_18092_I
As a software engineer, your task is to create an optimized version of the Insertion Sort algorithm. You will improve the provided baseline insertion sort algorithm by implementing a feature that ensures the function handles large, nearly sorted datasets efficiently. Implement the function `optimized_insertion_sort` t...
def binary_search(arr, val, start, end): # We need to use binary search to find the correct insertion position while start < end: mid = (start + end) // 2 if arr[mid] < val: start = mid + 1 else: end = mid return start def optimized_insertion_sort(arr): "...
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_unsorted_array(): assert optimized_insertion_sort([5, 2,...
[ { "docstring": null, "function_declaration": "def binary_search(arr, val, start, end):", "function_name": "binary_search", "parameter_list": "(arr, val, start, end)" }, { "docstring": "This function sorts an array using an optimized version of insertion sort.\nIt uses binary search to find t...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def binary_search(arr, val, start, end):\n \"\"\"\n Helper function that uses binary search to find the position \n where 'val' should be inserted wi...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018092", "row_id": 18092, "seed_ids": "[7]" }
0.587798
Data_Structure_18092
I
[ "binary_search", "optimized_insertion_sort" ]
2
[ [ "optimized_insertion_sort", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ed6594b7482e7d8d2fa6103f04dc6a924a0827cb
e4699a5ba5197d2f2d989ef713de8c2f4192eb56
v1.0
instruct
Data_Structure
Data_Structure_18122_I
### Sudoku Solver Challenge You are given a partially filled 9x9 Sudoku board. Each cell can contain a digit from 1 to 9 or be empty (denoted by '.'). The objective is to fill the empty cells such that every row, column, and 3x3 subgrid contains the digits 1 to 9 without repetition. Write a function `solve_sudoku(boa...
from typing import List def is_valid(board: List[List[str]], row: int, col: int, num: str) -> bool: """ Helper function to check whether placing a number in a specific cell is valid. """ # Check the row for j in range(9): if board[row][j] == num: return False # ...
from solution import solve_sudoku def test_sudoku_solver(): board = [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["...
[ { "docstring": "Helper function to check whether placing a number in a specific cell is valid.", "function_declaration": "def is_valid(board, row, col, num):", "function_name": "is_valid", "parameter_list": "(board, row, col, num)" }, { "docstring": "Backtracking approach to solve the Sudoku...
[ 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 solve_sudoku(board):\n def is_valid(board, row, col, num):\n # Check if num is not in the current row\n for x in range(9):\n i...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018122", "row_id": 18122, "seed_ids": "[179]" }
0.702922
Data_Structure_18122
I
[ "is_valid", "solve_sudoku" ]
2
[ [ "solve_sudoku", "is_valid" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dfcb12327543bce1261217afcfb59f2dd493447a
938dec4c9918b46f555b0809d56df369324c16a1
v1.0
instruct
Data_Structure
Data_Structure_18123_I
Given a range of integers `[low, high]`, write a function named `find_power_sum_numbers` that finds all integers in this range such that the sum of its digits, each raised to the power of their positions (1-based indexing), equals the number itself. ### Function Signature ```python def find_power_sum_numbers(low: int,...
from typing import List def sum_of_digits_powered(number: int) -> int: digits = str(number) return sum(int(digit) ** (index + 1) for index, digit in enumerate(digits)) def find_power_sum_numbers(low: int, high: int) -> List[int]: result = [] for num in range(low, high + 1): if num == sum_of_di...
from solution import find_power_sum_numbers def test_basic_range(): assert find_power_sum_numbers(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9] def test_range_with_large_numbers(): assert find_power_sum_numbers(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89] def test_single_result(): assert find_power_sum_numbers...
[ { "docstring": null, "function_declaration": "def sum_of_digits_powered(number):", "function_name": "sum_of_digits_powered", "parameter_list": "(number)" }, { "docstring": null, "function_declaration": "def find_power_sum_numbers(low, high):", "function_name": "find_power_sum_numbers...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef find_power_sum_numbers(low: int, high: int) -> List[int]:\n def is_power_sum_number(n: int) -> bool:\n digits = str(n...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00018123", "row_id": 18123, "seed_ids": "[135]" }
0.653808
Data_Structure_18123
I
[ "sum_of_digits_powered", "find_power_sum_numbers" ]
2
[ [ "find_power_sum_numbers", "sum_of_digits_powered" ] ]
1
[]
false
[]
false
pytest
true
[]
true
966dc9c2b9191467a5dacac59274f781bbd190bb
5b6fdf9207301928e5a73c2a3b34b8cf4704b6c0
v1.0
instruct
Data_Structure
Data_Structure_18148_I
You are tasked with ensuring all input arrays provided to the `bitonic_sort` function are valid for the sorting algorithm. To do this, you need to write a helper function `validate_input` that checks whether the input size is a power of two. Additionally, modify the original `bitonic_sort` function to call `validate_in...
def validate_input(arr): """ Validate if the length of the list is a power of two. """ n = len(arr) return (n & (n - 1) == 0) and n != 0 def bitonic_sort(arr): """ Perform the bitonic sort on the input array. """ if not validate_input(arr): raise ValueError("Input size must ...
from solution import validate_input, bitonic_sort def test_validate_input(): assert validate_input([1]) == True assert validate_input([1, 2]) == True assert validate_input([1, 2, 3, 4]) == True assert validate_input([1, 2, 3]) == False assert validate_input([]) == False def test_bitonic_sort_valid...
[ { "docstring": "Validate if the length of the list is a power of two.", "function_declaration": "def validate_input(arr):", "function_name": "validate_input", "parameter_list": "(arr)" }, { "docstring": "Perform the bitonic sort on the input array.", "function_declaration": "def bitonic_...
[ 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 validate_input(arr):\n \"\"\"\n Checks if the length of the input array is a power of two.\n \n Parameters:\n arr (list): The input list of...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018148", "row_id": 18148, "seed_ids": "[17]" }
0.65704
Data_Structure_18148
I
[ "validate_input", "bitonic_sort" ]
2
[ [ "bitonic_sort", "validate_input" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e220429a6c0240b41318adf78142593dc028553d
3abd227eae1ad043464e0985d45e1fad7da2bca8
v1.0
instruct
Data_Structure
Data_Structure_18421_I
You are designing a system that needs to handle large prime numbers. One way to ascertain whether a number is prime is through a probabilistic algorithm known as the Rabin-Miller primality test. Write a function `probable_prime(n: int, k: int) -> bool` that determines if the given integer `n` is probably prime using ...
import random def modular_exponentiation(base, exp, mod): result = 1 while exp > 0: if exp % 2 == 1: result = (result * base) % mod base = (base * base) % mod exp //= 2 return result def rabin_miller_test(n, d, r): a = random.randint(2, n - 2) x = modular_expone...
from solution import probable_prime def test_probable_prime_with_small_primes(): assert probable_prime(5, 5) == True assert probable_prime(7, 10) == True assert probable_prime(11, 5) == True def test_probable_prime_with_small_composites(): assert probable_prime(6, 5) == False assert probable_prime...
[ { "docstring": null, "function_declaration": "def modular_exponentiation(base, exp, mod):", "function_name": "modular_exponentiation", "parameter_list": "(base, exp, mod)" }, { "docstring": null, "function_declaration": "def rabin_miller_test(n, d, r):", "function_name": "rabin_mille...
[ 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 modular_exponentiation(base, exp, mod):\n result = 1\n while exp > 0:\n if exp % 2 == 1:\n result = (result * bas...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00018421", "row_id": 18421, "seed_ids": "[136]" }
0.725178
Data_Structure_18421
I
[ "modular_exponentiation", "rabin_miller_test", "probable_prime" ]
3
[ [ "probable_prime", "rabin_miller_test" ], [ "rabin_miller_test", "modular_exponentiation" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c3607828cf5a89ba6897d541d2fed75522d7a78c
345357b4240e1491fdc6f9b0ed5d357ebc678480