version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | complete | Data_Structure | Data_Structure_4132_C | from typing import List
def optimized_quick_sort(arr: List[int], k: int, simulation: bool=False) -> List[int]:
"""
Optimized Quick Sort algorithm with median-of-three pivot choice,
insertion sort for small arrays, and tail-call optimization.
>>> optimized_quick_sort([5, 2, 9, 1, 5, 6], 10)
[1, 2, ... | from typing import List
def median_of_three(a, b, c):
"""Return the median of the three elements."""
return sorted([a, b, c])[1]
def partition(arr, low, high):
"""
Partition the array using the median-of-three method to choose the pivot.
"""
mid = (low + high) // 2
pivot = median_of_three(... | from solution import optimized_quick_sort
def test_small_array():
arr = [3, 1, 2]
k = 2
assert optimized_quick_sort(arr, k) == [1, 2, 3]
def test_large_array():
arr = [5, 2, 9, 1, 5, 6, 8, 7, -3, -2]
k = 3
assert optimized_quick_sort(arr, k) == [-3, -2, 1, 2, 5, 5, 6, 7, 8, 9]
def test_edge_c... | [
{
"docstring": "Return the median of the three elements.",
"function_declaration": "def median_of_three(a, b, c):",
"function_name": "median_of_three",
"parameter_list": "(a, b, c)"
},
{
"docstring": "Partition the array using the median-of-three method to choose the pivot.",
"function_d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef median_of_three(a, b, c):\n \"\"\"Return the median of the three elements.\"\"\"\n return sorted([a, b, c])[1]\n\ndef par... | trial_gpt4o_0 | {
"original_instruction": "### Context\nThe given code implements the Quick Sort algorithm, a popular and efficient sorting algorithm under average case scenarios. Your task is to further enhance and adapt the Quick Sort implementation to address some common pitfalls and optimize its performance to handle large datas... | 0.577712 | Data_Structure_4132 | C | [
"median_of_three",
"partition",
"insertion_sort",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"insertion_sort"
],
[
"optimized_quick_sort",
"partition"
],
[
"partition",
"median_of_three"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 76b0859986246d72c46adeca3ba2d44bb2d2edf5 | 7b1efad2e9e5a8599881b311c5a9bcaff1ca0040 | |||
v1.0 | complete | Data_Structure | Data_Structure_5935_C | 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 bogo_sort(arr: list, simulation: bool = False) -> list:
"""
Sorts the array using the Bogo Sort algorithm.
>>> bogo_sort([3, 1, 2]) [... | 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 bogo_sort(arr: list, simulation: bool = False) -> list:
"""
Sorts the array using the Bogo Sort algorithm.
"""
if len(arr) <= 1:
... | from solution import bogo_sort
def test_empty_array():
assert bogo_sort([]) == []
def test_single_element_array():
assert bogo_sort([1]) == [1]
def test_already_sorted_array():
assert bogo_sort([1, 2, 3]) == [1, 2, 3]
def test_reverse_sorted_array():
assert bogo_sort([3, 2, 1]) == [1, 2, 3]
def tes... | [
{
"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 the Bogo Sort algorithm.",
"function_declaration": "def bogo_sort(arr, simula... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef bogo_sort(arr: list, simulation: bool = False) -> list:\n def is_sorted(arr):\n for i in range(len(arr) - 1):\n if a... | trial_gpt4o_2 | {
"original_instruction": "#### Context\nYou've recently learned about various sorting algorithms and their efficiency. One of the most inefficient sorts is the Bogo Sort, which relies on random shuffling until the array is sorted. Despite its inefficiency, Bogo Sort can be a valuable educational tool for understandi... | 0.654653 | Data_Structure_5935 | C | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 403f1086e6f9bcadffc3048b010c4d7975ffdd0a | a833b00eab8342c6d20c426da88f5e168cb71a4d | |||
v1.0 | complete | Data_Structure | Data_Structure_4506_C | from typing import List
def enhanced_two_sum(numbers: List[int], target: int) -> List[int]:
""" Select and execute the most efficient two-sum method based on the size of the array.
- Binary Search (`two_sum`) for arrays smaller than 50 elements.
- Hash Table (`two_sum1`) for arrays with 50 to 1000 elements... | def two_sum(numbers, target):
# Binary Search Method
for i in range(len(numbers)):
low, high = i + 1, len(numbers) - 1
while low <= high:
mid = (low + high) // 2
complement = target - numbers[i]
if numbers[mid] == complement:
return [i + 1, mid... | from solution import enhanced_two_sum
def test_small_array():
numbers = [2, 7, 11, 15]
target = 9
assert enhanced_two_sum(numbers, target) == [1, 2]
def test_medium_array():
numbers = [1, 2, 3, 4, 4, 9, 56, 90]
target = 8
assert enhanced_two_sum(numbers, target) == [4, 5]
def test_large_array... | [
{
"docstring": null,
"function_declaration": "def two_sum(numbers, target):",
"function_name": "two_sum",
"parameter_list": "(numbers, target)"
},
{
"docstring": null,
"function_declaration": "def two_sum1(numbers, target):",
"function_name": "two_sum1",
"parameter_list": "(numbe... | [
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 two_sum(numbers, target):\n for i, num in enumerate(numbers):\n left, right = i + 1, len(numbers) - 1\n while left <= right:\n ... | trial_gpt4o_3 | {
"original_instruction": "### Coding Assessement Question\n\nYou have been provided with three different methods to solve the Two-Sum Problem on a sorted array of integers. Write a function `enhanced_two_sum` that selects and executes the most efficient method based on the input size. Specifically, use:\n- Binary Se... | 0.61485 | Data_Structure_4506 | C | [
"two_sum",
"two_sum1",
"two_sum2",
"enhanced_two_sum"
] | 4 | [
[
"enhanced_two_sum",
"two_sum"
],
[
"enhanced_two_sum",
"two_sum1"
],
[
"enhanced_two_sum",
"two_sum2"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 1f16ce1c720731d57275771db5334cd79a43c001 | 124a7155b2bf9f94612b8a24cfdcb4465ac12d99 | |||
v1.0 | complete | Data_Structure | Data_Structure_4686_C | def pad_to_power_of_two(arr: list) -> list:
"""
Pads the input array with `float('inf')` until its length is a power of two.
Args:
arr (list): The input array to be padded.
Returns:
list: A new array padded to the nearest power of two length.
>>> pad_to_power_of_two([3, 7, 2, 8, 1, 5]) ==... | import math
def pad_to_power_of_two(arr):
"""
Pads the input array with `float('inf')` until its length is a power of two.
Args:
arr (list): The input array to be padded.
Returns:
list: A new array padded to the nearest power of two length.
"""
length = len(arr)
next_power... | from solution import pad_to_power_of_two, bitonic_sort
def test_pad_to_power_of_two():
assert pad_to_power_of_two([3, 7, 2, 8, 1, 5]) == [3, 7, 2, 8, 1, 5, float('inf'), float('inf')]
assert pad_to_power_of_two([1]) == [1]
assert pad_to_power_of_two([1, 2, 3]) == [1, 2, 3, float('inf')]
def test_bitonic_s... | [
{
"docstring": "Pads the input array with `float('inf')` until its length is a power of two.\n\nArgs:\narr (list): The input array to be padded.\n\nReturns:\nlist: A new array padded to the nearest power of two length.",
"function_declaration": "def pad_to_power_of_two(arr):",
"function_name": "pad_to_p... | [
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\n\ndef pad_to_power_of_two(arr):\n \"\"\"\n Pads the input array with `float('inf')` until its length is a power of two.\n \n Args:\n ... | trial_gpt4o_0 | {
"original_instruction": "You are provided with a partially implemented Bitonic Sort algorithm. Your task is to extend the functionality to handle arrays of arbitrary lengths by padding them to the nearest power of 2 with a special value that does not interfere with the normal sorting process.\n\n### Instructions\n\... | 0.642981 | Data_Structure_4686 | C | [
"pad_to_power_of_two",
"compare_and_swap",
"bitonic_merge",
"bitonic_sort_util",
"bitonic_sort"
] | 5 | [
[
"bitonic_merge",
"compare_and_swap"
],
[
"bitonic_sort",
"bitonic_sort_util"
],
[
"bitonic_sort",
"pad_to_power_of_two"
],
[
"bitonic_sort_util",
"bitonic_merge"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 96991d5267ecc2300521987c47d6faafdb5c444a | be34c4f0da4c9457908408b8d641d28edaeb17c7 | |||
v1.0 | complete | Data_Structure | Data_Structure_4714_C | def modified_quick_sort(arr: list) -> list:
""" Sort an array of integers using a modified quick sort algorithm with the median-of-three method for pivot selection.
Args:
arr (list): A list of integers to be sorted.
Returns:
list: A new list of integers sorted in ascending orde... | def median_of_three(arr, low, high):
mid = (low + high) // 2
if arr[low] > arr[mid]:
arr[low], arr[mid] = arr[mid], arr[low]
if arr[low] > arr[high]:
arr[low], arr[high] = arr[high], arr[low]
if arr[mid] > arr[high]:
arr[mid], arr[high] = arr[high], arr[mid]
return mid
def p... | from solution import modified_quick_sort
def test_sorted_array():
assert modified_quick_sort([1, 2, 3, 4, 5, 6]) == [1, 2, 3, 4, 5, 6]
def test_reverse_sorted_array():
assert modified_quick_sort([6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6]
def test_unsorted_array():
assert modified_quick_sort([34, 7, 23, 32... | [
{
"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... | [
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 modified_quick_sort(arr: list) -> list:\n if len(arr) <= 1:\n return arr\n\n def median_of_three(lst, left, right):\n mid = (left + ri... | trial_gpt4o_1 | {
"original_instruction": "**Question: Implement a Modified Quick Sort**\n\n### Problem Statement\nYou are required to create a function `modified_quick_sort` that sorts an array of integers. The function must include additional enhancements for optimizing the pivot selection to avoid the worst-case performance. Spec... | 0.652644 | Data_Structure_4714 | C | [
"median_of_three",
"partition",
"quick_sort_helper",
"modified_quick_sort"
] | 4 | [
[
"modified_quick_sort",
"quick_sort_helper"
],
[
"partition",
"median_of_three"
],
[
"quick_sort_helper",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 3ef9c7baec7eb00ac2a219d91e85916f360dd5cb | 9bb9afa476d233e613f303f83e2cbccb613a058f | |||
v1.0 | complete | Data_Structure | Data_Structure_5509_C | from typing import List
def invert_matrix(matrix: List[List[float]]) -> List[List[float]]:
"""
Implement a function to invert an invertible n x n matrix, adhering to the principles of matrix operations, including the use of minors, cofactors, adjugation, and determinant calculations.
Args:
ma... | from typing import List
def determinant(matrix: List[List[float]]) -> float:
"""
Calculate the determinant of a square 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]
det = 0
... | from solution import invert_matrix
def test_invert_2x2_matrix():
matrix = [
[1, 2],
[3, 4]
]
expected = [
[-2.0, 1.0],
[1.5, -0.5]
]
assert invert_matrix(matrix) == expected
def test_invert_3x3_matrix():
matrix = [
[3, 0, 2],
[2, 0, -2],
... | [
{
"docstring": "Calculate the determinant of a square matrix.",
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": "Calculate the minor of a matrix element at a specified row and column.",
"function_declarati... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef determinant(matrix: List[List[float]]) -> float:\n \"\"\"\n Calculate the determinant of a square matrix.\n \"\"\"\n ... | trial_gpt4o_0 | {
"original_instruction": "## Coding Assessment Question\n\n### Matrix Inversion Function Implementation\n\n**Objective**: Implement a function to invert an invertible \\(n \\times n\\) matrix, adhering to the principles of matrix operations, including the use of minors, cofactors, adjugation, and determinant calcula... | 0.570409 | Data_Structure_5509 | C | [
"determinant",
"minor",
"cofactor",
"transpose",
"invert_matrix"
] | 5 | [
[
"cofactor",
"determinant"
],
[
"cofactor",
"minor"
],
[
"invert_matrix",
"cofactor"
],
[
"invert_matrix",
"determinant"
],
[
"invert_matrix",
"transpose"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | bb02ce79e04a072274e8047faee42562cfd2caf4 | 64c90e2f29f1bd404baa0464b74eb8063db7f2e0 | |||
v1.0 | complete | Data_Structure | Data_Structure_3838_C | import math
from typing import Tuple, Dict
def distance(vec1: Tuple[float, ...], vec2: Tuple[float, ...]) -> float:
"""
Calculates the Euclidean distance between two vectors.
Arguments:
vec1 {tuple} -- The first vector.
vec2 {tuple} -- The second vector.
Returns:
{float} -- The Eu... | import math
def distance(vec1, vec2):
"""
Calculates the Euclidean distance between two vectors.
Arguments:
vec1 {tuple} -- The first vector.
vec2 {tuple} -- The second vector.
Returns:
{float} -- The Euclidean distance between the two vectors.
"""
return math.sqrt(sum((a ... | from solution import distance, nearest_neighbor, recommend_movie
def test_distance():
assert distance((1, 2, 3), (4, 5, 6)) == math.sqrt(27)
assert distance((0, 0, 0), (0, 0, 0)) == 0
assert distance((1, 1, 1), (2, 2, 2)) == math.sqrt(3)
def test_nearest_neighbor():
user_pref_vector = (3.5, 4.0, 2.5)
... | [
{
"docstring": "Calculates the Euclidean distance between two vectors.\n\nArguments:\nvec1 {tuple} -- The first vector.\nvec2 {tuple} -- The second vector.\n\nReturns:\n{float} -- The Euclidean distance between the two vectors.",
"function_declaration": "def distance(vec1, vec2):",
"function_name": "dis... | [
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\n\ndef distance(vec1, vec2):\n \"\"\"\n Calculates the Euclidean distance between two vectors.\n \n Arguments:\n vec1 {tuple} -- Th... | trial_gpt4o_0 | {
"original_instruction": "### Nearest Neighbor Classification Implementation\n\n#### Scenario\nImagine you are developing a simple recommendation system for a movie streaming service. Each movie's features (e.g., genre, length, rating) are represented as numerical vectors, and given a user's movie preferences, you n... | 0.590509 | Data_Structure_3838 | C | [
"distance",
"nearest_neighbor",
"recommend_movie"
] | 3 | [
[
"nearest_neighbor",
"distance"
],
[
"recommend_movie",
"nearest_neighbor"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9849f2c78a5386d3cee89ffa7bec347a930001a9 | 189d6c344324bb1214d11ee27f86ae4e53160bcb | |||
v1.0 | complete | Data_Structure | Data_Structure_4918_C | from typing import List
def custom_radix_sort(arr: List[int]) -> List[int]:
"""
Implement the Radix Sort algorithm to sort a list of non-negative integers.
Args:
arr (List[int]): A list of non-negative integers.
Returns:
List[int]: A sorted list of integers.
Examples:
>>... | from typing import List
def counting_sort(arr: List[int], exp: int) -> None:
"""
A function to do counting sort based on the digit represented by exp
"""
n = len(arr)
output = [0] * n # output array
count = [0] * 10 # count array for digits (0 to 9)
# Store count of occurrences in co... | from solution import custom_radix_sort
def test_custom_radix_sort_general_case():
assert custom_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_custom_radix_sort_empty_list():
assert custom_radix_sort([]) == []
def test_custom_radix_sort_single_element():
asser... | [
{
"docstring": "A function to do counting sort based on the digit represented by exp",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "Function to implement the Radix Sort algorithm",
"function_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": "from typing import List\n\ndef custom_radix_sort(arr: List[int]) -> List[int]:\n if not arr:\n return arr # Immediate return for empty list\n ... | trial_gpt4o_2 | {
"original_instruction": "### Coding Challenge: Custom Radix Sort Implementation\n\n#### Scenario\nYou are a software engineer tasked with optimizing the sorting process for a large dataset of integers representing customer IDs. The IDs can be assumed to be non-negative integers. Given that the input list can be ext... | 0.68409 | Data_Structure_4918 | C | [
"counting_sort",
"custom_radix_sort"
] | 2 | [
[
"custom_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cb428a5b7d130c5fedfec09a7c469ce811c4bce1 | 04a21449f758878b9982ac1df684e010900ab975 | |||
v1.0 | complete | Data_Structure | Data_Structure_5936_C | from typing import List
def calculate_max_delivery_flow(capacity: List[List[int]], source: int, sink: int) -> int:
""" Calculates the maximum flow from the source to the sink warehouse using Dinic's algorithm.
>>> capacity = [
... [0, 16, 13, 0, 0, 0],
... [0, 0, 10, 12, 0, 0],
... [0, ... | from typing import List
from collections import deque
def bfs_level_graph(capacity: List[List[int]], source: int, sink: int, level: List[int]) -> bool:
"""
Uses BFS to build level graph and store level of each node in level[] array.
Returns True if there is a path from source to sink, else False.
"""
... | from solution import calculate_max_delivery_flow
def test_example_case():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert calculate_... | [
{
"docstring": "Uses BFS to build level graph and store level of each node in level[] array.\nReturns True if there is a path from source to sink, else False.",
"function_declaration": "def bfs_level_graph(capacity, source, sink, level):",
"function_name": "bfs_level_graph",
"parameter_list": "(capa... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(level: List[int], capacity: List[List[int]], source: int, sink: int, n: int) -> bool:\n q... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nYou are working as a software engineer at a logistics company that is optimizing its network of delivery routes. They need to ensure that they can handle maximum traffic flow through their delivery network efficiently. The delivery routes can be represented as a directed graph... | 0.609245 | Data_Structure_5936 | C | [
"bfs_level_graph",
"dfs_flow",
"calculate_max_delivery_flow"
] | 3 | [
[
"calculate_max_delivery_flow",
"bfs_level_graph"
],
[
"calculate_max_delivery_flow",
"dfs_flow"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f857694442b38b9b692bd26ae781a2b2dfc5aafd | e993698dace36cdd010276a02ccd83f23100b9ba | |||
v1.0 | complete | Data_Structure | Data_Structure_5113_C | import random
from sympy import isprime, mod_inverse
def generate_key(k: int, seed: int = None) -> tuple:
"""
Generate RSA keys for encryption and decryption.
:param k: Number of bits in n.
:param seed: Seed for random prime generation (optional).
:return: Tuple containing (n, e, d) where n i... | import random
from sympy import isprime, mod_inverse
def generate_prime(bits):
while True:
prime_candidate = random.getrandbits(bits)
if isprime(prime_candidate):
return prime_candidate
def generate_key(k, seed=None):
if seed is not None:
random.seed(seed)
p = gene... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16, seed=1234)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_encrypt_decrypt():
n, e, d = generate_key(16, seed=1234)
data = 42
encrypted = encrypt(d... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bits):",
"function_name": "generate_prime",
"parameter_list": "(bits)"
},
{
"docstring": null,
"function_declaration": "def generate_key(k, seed=None):",
"function_name": "generate_key",
"parameter_list": "(k, seed=... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, gcd, mod_inverse\n\n\ndef generate_key(k, seed=None):\n \"\"\"\n Generates the public and private keys for RSA... | trial_gpt4o_2 | {
"original_instruction": "### RSA Encryption and Decryption Implementation (Advanced)\nYou are required to implement the RSA encryption algorithm for a secure communication system. Your task is to provide functions for generating RSA keys, encrypting messages, and decrypting messages, demonstrating a thorough unders... | 0.693888 | Data_Structure_5113 | C | [
"generate_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | c3a6be50897a4097de5ebfb6f763d078e8e15bb1 | 2dab15800ee1c36c90cf46b0e9a80b23c1306a61 | |||
v1.0 | complete | Data_Structure | Data_Structure_4521_C | class Node:
def __init__(self, val=None):
self.val = val
self.next = None
def get_length(node):
length = 0
while node:
length += 1
node = node.next
return length
def find_intersection_node(head1, head2):
"""
Identifies the first common node between two singly li... | class Node:
def __init__(self, val=None):
self.val = val
self.next = None
def get_length(node):
length = 0
while node:
length += 1
node = node.next
return length
def find_intersection_node(head1, head2):
"""
Identifies the first common node between two singly li... | def test_no_intersection():
a1 = Node(1)
b1 = Node(2)
a2 = Node(3)
b2 = Node(4)
a1.next = b1
a2.next = b2
assert find_intersection_node(a1, a2) == None
def test_one_empty_list():
a1 = Node(1)
b1 = Node(2)
a1.next = b1
assert find_intersection_node(a1, Non... | [] | [
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=None):\n self.val = val\n self.next = None\n\ndef get_length(node):\n length = 0\n while node:\n ... | trial_gpt4o_0 | {
"original_instruction": "#### Linked List Intersection Detection\n\nYou are given two singly linked lists. Write a function `find_intersection_node(head1, head2)` that identifies the first common node between the two input linked lists, if any. The linked lists are represented by their head nodes.\n\n### Function S... | 0.524733 | Data_Structure_4521 | C | [
"get_length",
"find_intersection_node"
] | 2 | [
[
"find_intersection_node",
"get_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | false | [] | true | 7800e7b12abc5c38d1ae9f08d62483a7afcbd5a9 | 191cb791f47060433a70e266bd824af769d425a6 | |||
v1.0 | complete | Data_Structure | Data_Structure_5800_C | from typing import List
def bucket_sort(arr: List[int]) -> List[int]:
""" Sort a list of integers using an enhanced bucket sort algorithm with quicksort.
Args:
arr (List[int]): The list of integers to sort.
Returns:
List[int]: The sorted list of integers.
Examples:
>>> bucket... | from typing import List
def quicksort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
else:
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(l... | from solution import bucket_sort
def test_bucket_sort():
assert bucket_sort([29, 25, 3, 49, 37, 21, 43, 31, 33]) == [3, 21, 25, 29, 31, 33, 37, 43, 49]
assert bucket_sort([]) == []
assert bucket_sort([1, 1, 1, 1]) == [1, 1, 1, 1]
assert bucket_sort([3, 3, 3, 1, 1, 1, 2, 2, 2]) == [1, 1, 1, 2, 2, 2, 3, ... | [
{
"docstring": null,
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"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 bucket_sort(arr: List[int]) -> List[int]:\n if not arr:\n return []\n\n # Determine maximum value to identify numb... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement Enhanced Bucket Sort\n\nYou have been provided with the bucket sort algorithm, a technique suitable for sorting an array of numbers by dividing them into several buckets, sorting each bucket, and then combining the sorted buckets. \n\nHowever, the provided implementa... | 0.625828 | Data_Structure_5800 | C | [
"quicksort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5569ee0de92f2320e1a13d4bae597d1a17273738 | eade34341f1c60f26613e0d19f0496aa4314ac7c | |||
v1.0 | complete | Data_Structure | Data_Structure_5057_C | from typing import List
def is_prime(n: int) -> bool:
""" Checks if a number n is prime.
>>> is_prime(23)
True
>>> is_prime(1)
False
"""
# Your code here.
def calculate_primitive_root(p: int) -> List[int]:
""" Finds all the primitive roots of a prime number p.
>>> set(calculate_pri... | from typing import List
import random
def is_prime(n: int) -> bool:
"""
Checks if a number n 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:
... | from solution import is_prime, calculate_primitive_root, diffie_hellman_key_exchange
def test_is_prime():
assert is_prime(2) == True
assert is_prime(11) == True
assert is_prime(23) == True
assert is_prime(1) == False
assert is_prime(10) == False
assert is_prime(0) == False
assert is_prime(-... | [
{
"docstring": "Checks if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Finds all the primitive roots of a prime number p.",
"function_declaration": "def calculate_primitive_root(p):",
"funct... | [
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": "def is_prime(n: int) -> bool:\n \"\"\"\n Determines if a number n is a prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ... | trial_gpt4o_8 | {
"original_instruction": "### Secure Key Exchange using Diffie-Hellman Protocol\n\n**Objective**: Implement a secure key exchange using the Diffie-Hellman protocol.\n\n### Problem Statement\nAlice and Bob want to securely share a secret key over an insecure communication channel using the Diffie-Hellman key exchange... | 0.620936 | Data_Structure_5057 | C | [
"is_prime",
"calculate_primitive_root",
"diffie_hellman_key_exchange"
] | 3 | [
[
"calculate_primitive_root",
"is_prime"
],
[
"diffie_hellman_key_exchange",
"calculate_primitive_root"
],
[
"diffie_hellman_key_exchange",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | cc5f2b62aa73fe4cf9ffe4f2cba659548a3d13a1 | d18e316333ebdd658db9a5ce01d16f8d07810946 | |||
v1.0 | complete | Data_Structure | Data_Structure_5924_C | def generalized_bitonic_sort(arr: list, reverse: bool = False) -> list:
""" Generalized bitonic sort to handle arrays of any size.
Sorts an array of integers in the specified order (ascending by default or descending if reverse is True).
Args:
arr (list): The list of integers to sort.
reverse (... | import math
from typing import List
def bitonic_sort(arr: List[int], low: int, cnt: int, order: bool):
""" Helper function to perform bitonic sort on a subarray """
if cnt > 1:
k = cnt // 2
bitonic_sort(arr, low, k, True) # First half in ascending order
bitonic_sort(arr, low + k, k, Fa... | from solution import generalized_bitonic_sort
def test_empty_array():
assert generalized_bitonic_sort([]) == []
def test_single_element():
assert generalized_bitonic_sort([1]) == [1]
def test_power_of_two_length_array():
assert generalized_bitonic_sort([3, 7, 2, 5], reverse=False) == [2, 3, 5, 7]
ass... | [
{
"docstring": "Helper function to perform bitonic sort on a subarray ",
"function_declaration": "def bitonic_sort(arr, low, cnt, order):",
"function_name": "bitonic_sort",
"parameter_list": "(arr, low, cnt, order)"
},
{
"docstring": "Helper function to merge bitonically sorted subarrays ",
... | [
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 typing import List\n\ndef bitonic_sort(arr: List[int], low: int, cnt: int, order: bool):\n \"\"\" Helper function to perform bitonic sort... | trial_gpt4o_0 | {
"original_instruction": "In this coding task, you are required to implement the bitonic sort algorithm as per the given constraints and further enhance it to handle a broader range of input scenarios.\n\n### Task:\n\n1. **Implement Bitonic Sort**:\n Modify the existing `bitonic_sort` function to sort an array of ... | 0.712797 | Data_Structure_5924 | C | [
"bitonic_sort",
"bitonic_merge",
"generalized_bitonic_sort"
] | 3 | [
[
"bitonic_sort",
"bitonic_merge"
],
[
"generalized_bitonic_sort",
"bitonic_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4fbbbf064873e61cc8f7c01eb3c4f79edd67f75b | d7028e5e657aaf6d5d2a2216c7b1b9b29ce4f1b6 | |||
v1.0 | complete | Data_Structure | Data_Structure_5354_C | import math
from typing import Tuple, Dict, Any
def euclidean_distance(v1: Tuple[float, ...], v2: Tuple[float, ...]) -> float:
"""
Calculate the Euclidean distance between two vectors v1 and v2.
>>> euclidean_distance((0, 0), (3, 4))
5.0
>>> euclidean_distance((1, 2), (1, 2))
0.0
>>> ... | import math
def euclidean_distance(v1, v2):
"""
Calculates the Euclidean distance between two vectors v1 and v2.
"""
sum_squared_diff = sum((a - b) ** 2 for a, b in zip(v1, v2))
return math.sqrt(sum_squared_diff)
def nearest_neighbor(x, tSet):
"""
Finds the nearest neighbor of vector x fro... | from solution import nearest_neighbor, euclidean_distance
def test_euclidean_distance():
assert euclidean_distance((0, 0), (3, 4)) == 5.0
assert euclidean_distance((1, 2), (1, 2)) == 0.0
assert euclidean_distance((1, 2, 3), (4, 5, 6)) == math.sqrt(27)
def test_nearest_neighbor_basic():
x = (2, 3)
... | [
{
"docstring": "Calculates the Euclidean distance between two vectors v1 and v2.",
"function_declaration": "def euclidean_distance(v1, v2):",
"function_name": "euclidean_distance",
"parameter_list": "(v1, v2)"
},
{
"docstring": "Finds the nearest neighbor of vector x from the training set tS... | [
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 euclidean_distance(v1, v2):\n \"\"\"\n Calculate the Euclidean distance between two vectors v1 and v2.\n \"\"\"\n return math.s... | trial_gpt4o_1 | {
"original_instruction": "Implement Nearest Neighbor Classifier\n\n#### Context\nYou are working on a simple classification system that uses a nearest neighbor algorithm to classify data points. Your task is to create a function that finds the nearest neighbor of a given input vector `x` from a training set `tSet`.\... | 0.677593 | Data_Structure_5354 | C | [
"euclidean_distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f7748848360629c80fccd2e839f87e3ebb2e85a2 | 83328ad1db0043276dded87b2028bb5ce8a20cc0 | |||
v1.0 | complete | Data_Structure | Data_Structure_6276_C | def improved_jump_search(arr: List[int], target: int) -> int:
""" Implement an improved jump search algorithm with dynamic block sizes based on the square root of Fibonacci numbers.
>>> improved_jump_search([1, 3, 5, 7, 9, 11, 13, 15, 17, 19], 7)
3
>>> improved_jump_search([1, 3, 5, 7, 9, 11, 13, 15, 17... | from math import sqrt
from typing import List
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def improved_jump_search(arr: List[int], target: int) -> int:
n = len(arr)
if n == 0:
return -1
fib_gen = fibonacci()
fib_m = next(fib_gen) # Fibonacci[m-1]
... | def test_improved_jump_search():
# Test case: target found in the middle
arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
target = 7
assert improved_jump_search(arr, target) == 3
# Test case: target found at the beginning
arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
target = 1
assert improved... | [
{
"docstring": null,
"function_declaration": "def fibonacci():",
"function_name": "fibonacci",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def improved_jump_search(arr, target):",
"function_name": "improved_jump_search",
"parameter_list": "(arr, target... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import sqrt\nfrom typing import List\n\ndef fibonacci_numbers(limit):\n fibs = [1, 2]\n while fibs[-1] <= limit:\n fibs.append(fibs[-1]... | trial_gpt4o_2 | {
"original_instruction": "**Coding Challenge: Implementing Improved Jump Search**\n\n**Scenario**:\nYou are given a sorted list of unique integers representing recorded temperatures over several days. Your goal is to find a particular temperature in the list using a modified version of the jump search algorithm. \n\... | 0.572306 | Data_Structure_6276 | C | [
"fibonacci",
"improved_jump_search"
] | 2 | [
[
"improved_jump_search",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 3b1b0811701a7ff74f4173bf4aa8276679cbfbbc | bef101c79c08952a4da83b8543cc4f7e723260d0 | |||
v1.0 | complete | Data_Structure | Data_Structure_5390_C | def radix_sort(arr: list[int]) -> list[int]:
"""
Performs radix sort on a list of non-negative integers.
>>> radix_sort([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66, 75, 90, 170, 802]
>>> radix_sort([3, 3, 3])
[3, 3, 3]
>>> radix_sort([])
[]
>>> radix_sort([123])
[123]
... | def counting_sort_for_radix(arr, exp):
n = len(arr)
output = [0] * n # output array that will have sorted arr
count = [0] * 10 # count array to store occurrences of digits
# Store count of occurrences in count[]
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
... | from solution import radix_sort
def test_radix_sort_typical_case():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_single_element():
assert radix_sort([123]) == [123]
def test_radix_sort_empty_list():
assert radix_sort([]) == []
def test_rad... | [
{
"docstring": null,
"function_declaration": "def counting_sort_for_radix(arr, exp):",
"function_name": "counting_sort_for_radix",
"parameter_list": "(arr, exp)"
},
{
"docstring": "Performs radix sort on a list of non-negative integers",
"function_declaration": "def radix_sort(arr):",
... | [
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 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) % 10\n ... | trial_gpt4o_2 | {
"original_instruction": "### Radix Sort Implementation\n\n**Scenario**:\nYou are tasked with implementing a sorting module that sorts large lists of non-negative integers efficiently. Your module will use Radix Sort, a highly efficient sorting algorithm for such data. The sorting needs to be stable, ensuring that t... | 0.654987 | Data_Structure_5390 | C | [
"counting_sort_for_radix",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort_for_radix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dd60667a1a1a1a9fd06f56b98e53124e586d0ff2 | f64d4562f9a60a4306635d5c0f1ad338e4028cbf | |||
v1.0 | complete | Data_Structure | Data_Structure_5464_C | def optimized_pancake_sort(arr: list) -> list:
"""Optimized Pancake Sort implementation to sort a list of integers.
The Pancake Sort algorithm sorts an array by repeatedly flipping sections of the array.
Parameters:
arr (list): A list of integers to be sorted, with 0 ≤ len(arr) ≤ 10^5 and -10^9 ≤ ... | def flip(arr, k):
"""
Reverse the order of the first k elements of arr.
"""
return arr[:k][::-1] + arr[k:]
def optimized_pancake_sort(arr):
"""
Sorts the array using an optimized pancake sort method.
"""
n = len(arr)
for i in range(n, 1, -1):
# Find the index of the largest ... | from solution import optimized_pancake_sort
def test_sorted_array():
assert optimized_pancake_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert optimized_pancake_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_unsorted_array():
assert optimized_pancake_sort([3, 2, 4, 1]) ... | [
{
"docstring": "Reverse the order of the first k elements of arr.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Sorts the array using an optimized pancake sort method.",
"function_declaration": "def optimized_panca... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_pancake_sort(arr):\n \"\"\"\n Sorts an array using an optimized version of the Pancake Sort algorithm.\n \"\"\"\n def flip(arr, k):\... | trial_gpt4o_2 | {
"original_instruction": "### Pancake Sort Implementation Challenge\n\nYou are provided with a sorting algorithm called Pancake Sort. This algorithm sorts an array by repeatedly flipping sections of the array. Your task is to modify the given algorithm to improve its efficiency and ensure robust handling of edge cas... | 0.70655 | Data_Structure_5464 | C | [
"flip",
"optimized_pancake_sort"
] | 2 | [
[
"optimized_pancake_sort",
"flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9cf611980ef18c727c1f0e97f0a51bd8e3cce1a9 | 7d19f4887f423cf49d6dd81123c19f8a71efc6ea | |||
v1.0 | complete | Data_Structure | Data_Structure_5370_C | from typing import List
def find_pattern_positions(text: str, pattern: str) -> List[int]:
"""
Given a large text and a pattern string, write a function using the Knuth-Morris-Pratt (KMP) algorithm
that efficiently finds all starting positions of the pattern in the text.
Args:
text (str): A string... | from typing import List
def compute_lps(pattern: str) -> List[int]:
"""
Helper function to compute the longest proper prefix which is also suffix table (lps array)
for the given pattern using KMP algorithm.
"""
lps = [0] * len(pattern)
length = 0 # length of the previous longest prefix suffix
... | import pytest
from solution import find_pattern_positions
def test_single_occurrence():
assert find_pattern_positions("hello world", "world") == [6]
def test_multiple_occurrences():
assert find_pattern_positions("abcabcabc", "abc") == [0, 3, 6]
def test_no_occurrence():
assert find_pattern_positions("abc... | [
{
"docstring": "Helper function to compute the longest proper prefix which is also suffix table (lps array)\nfor the given pattern using KMP algorithm.",
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": "Func... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef find_pattern_positions(text: str, pattern: str) -> List[int]:\n def compute_lps(pattern: str) -> List[int]:\n \"\"\"\... | trial_gpt4o_9 | {
"original_instruction": "### Question: Implement Accelerated Pattern Matching in a Text\n\nGiven a large text and a pattern string, write a function using the Knuth-Morris-Pratt (KMP) algorithm that efficiently finds all starting positions of the pattern in the text.\n\n#### Function Signature\n```python\ndef find_... | 0.601252 | Data_Structure_5370 | C | [
"compute_lps",
"find_pattern_positions"
] | 2 | [
[
"find_pattern_positions",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f62798c1f4912101edf218b51d1c5ef800e59767 | 068c0e2d1ccdb7fd913d2b2b6e944c24e5ed7ddc | |||
v1.0 | complete | Data_Structure | Data_Structure_4894_C | def search_insert(array, target, start, end):
"""
Helper function to find the index where 'target' should be inserted
in the sorted subarray 'array[start:end+1]'.
Parameters:
array (List[int]): The list of integers to be sorted.
target (int): The target value for which the insertion index ... | def search_insert(array, target, start, end):
"""
Helper function to find the index where 'target' should be inserted
in the sorted subarray 'array[start:end+1]'.
Parameters:
array (List[int]): The list of integers to be sorted.
target (int): The target value for which the insertion index ... | from solution import insertion_sort, search_insert
def test_search_insert():
assert search_insert([1, 2, 4, 5], 3, 0, 3) == 2
assert search_insert([1, 3, 5, 7], 6, 0, 3) == 3
assert search_insert([1, 2, 3, 4], 0, 0, 3) == 0
assert search_insert([2, 4, 6, 8], 10, 0, 3) == 4
def test_insertion_sort():
... | [
{
"docstring": "Helper function to find the index where 'target' should be inserted \nin the sorted subarray 'array[start:end+1]'.\n\nParameters:\narray (List[int]): The list of integers to be sorted.\ntarget (int): The target value for which the insertion index is to \n be found.\nstart (int): The... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(arr, left, right, key):\n \"\"\"\n Helper function to determine the index to insert the key using binary search\n \n Parameters:... | trial_gpt4o_1 | {
"original_instruction": "Implement Insertion Sort\n\nInsertion Sort is a simple sorting algorithm that builds the final sorted array one item at a time. In your implementation, use the 'search_insert' function to determine the correct insertion point of each element.\n\n*Implement the following function:*\n\n```pyt... | 0.605793 | Data_Structure_4894 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fa47bb2452c61557cd2abfca1a78e3de92acf6f5 | a7d1e0b7c20ee198730be9af27e57b77f5d5e455 | |||
v1.0 | complete | Data_Structure | Data_Structure_6213_C | from typing import List
def search_insert(sorted_ratings: List[int], new_rating: int) -> int:
"""
Helper function to find the correct insertion position for new_rating
in the sorted list sorted_ratings.
"""
left, right = 0, len(sorted_ratings)
while left < right:
mid = (left + rig... | from typing import List
def search_insert(sorted_ratings: List[int], new_rating: int) -> int:
"""
Helper function to find the correct insertion position for new_rating
in the sorted list sorted_ratings.
"""
left, right = 0, len(sorted_ratings)
while left < right:
mid = (left + rig... | from solution import insert_and_sort
def test_insert_and_sort():
# Test inserting into the middle of the list
sorted_ratings = [1, 3, 5, 6]
new_rating = 2
assert insert_and_sort(sorted_ratings, new_rating) == [1, 2, 3, 5, 6]
# Test inserting at the end of the list
sorted_ratings = [1, 3, 5, 6]... | [
{
"docstring": "Helper function to find the correct insertion position for new_rating \nin the sorted list sorted_ratings.",
"function_declaration": "def search_insert(sorted_ratings, new_rating):",
"function_name": "search_insert",
"parameter_list": "(sorted_ratings, new_rating)"
},
{
"docs... | [
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 search_insert(arr: List[int], target: int) -> int:\n \"\"\"\n Helper function to find the index where the target should b... | trial_gpt4o_2 | {
"original_instruction": "**Scenario**:\n\nImagine you are working on a software tool that requires efficiently managing a sorted list of user ratings. Users frequently add new ratings, and these ratings need to be inserted into the current sorted list quickly without re-sorting the entire list. Your task is to impl... | 0.579663 | Data_Structure_6213 | C | [
"search_insert",
"insert_and_sort"
] | 2 | [
[
"insert_and_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3544accfe7e28011e7d80bec531c17d975c2ca82 | d3e9deea384d74fb29129ea2c22b5f22a0b747a4 | |||
v1.0 | complete | Data_Structure | Data_Structure_6621_C | from typing import List
def sum_digit_lengths(arr: List[int]) -> int:
"""
Returns the sum of the number of digits of all the integers in the given list `arr`.
>>> sum_digit_lengths([123, 4, 56789, -12, 0])
12
>>> sum_digit_lengths([1, -1, 1000000000])
12
>>> sum_digit_lengths([])
0... | from typing import List
def num_digits(n: int) -> int:
"""
Returns the number of digits in an integer n.
For negative numbers, the '-' sign is not counted.
"""
return len(str(abs(n)))
def sum_digit_lengths(arr: List[int]) -> int:
"""
Returns the sum of the number of digits of all the inte... | from solution import sum_digit_lengths
def test_positive_numbers():
assert sum_digit_lengths([123, 4, 56789]) == 9 # 3 + 1 + 5 = 9
def test_negative_numbers():
assert sum_digit_lengths([-123, -4, -56789]) == 9 # 3 + 1 + 5 = 9 (negative sign ignored)
def test_mixed_numbers():
assert sum_digit_lengths([1... | [
{
"docstring": "Returns the number of digits in an integer n. \nFor negative numbers, the '-' sign is not counted.",
"function_declaration": "def num_digits(n):",
"function_name": "num_digits",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of the number of digits of all the inte... | [
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 num_digits(n: int) -> int:\n \"\"\"\n Returns the number of digits in an integer n. \n For negative numbers, the '-' s... | trial_gpt4o_0 | {
"original_instruction": "Sum of Digit Lengths of an Array\n\nYou are given an array of integers, and your task is to write a function that returns the sum of the number of digits of all the integers in the array.\n\n#### Function Signature\n```python\ndef sum_digit_lengths(arr: List[int]) -> int:\n```\n\n#### Input... | 0.72117 | Data_Structure_6621 | C | [
"num_digits",
"sum_digit_lengths"
] | 2 | [
[
"sum_digit_lengths",
"num_digits"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 602214daa6108c39833dd3df5c997cbb16e2f839 | 86cd3905a3dff36565ece900ddb07a6b7a26c8a4 | |||
v1.0 | complete | Data_Structure | Data_Structure_6862_C | def enhanced_euler_totient(n: int) -> int:
""" Computes the Euler's Totient Function in an optimized manner.
>>> enhanced_euler_totient(9)
6
>>> enhanced_euler_totient(1)
1
>>> enhanced_euler_totient(6)
2
""" | def enhanced_euler_totient(n: int) -> int:
"""
Computes Euler's Totient Function in an optimized manner.
"""
if n == 1:
return 1
# Initialize result as n
result = n
# Create a list to store prime numbers up to √n
primes = sieve(int(n**0.5) + 1)
# Check divisibility by pri... | from solution import enhanced_euler_totient
def test_enhanced_euler_totient_basic():
assert enhanced_euler_totient(9) == 6
assert enhanced_euler_totient(1) == 1
assert enhanced_euler_totient(6) == 2
def test_enhanced_euler_totient_large():
assert enhanced_euler_totient(10**7) > 0 # Ensure it does not... | [
{
"docstring": "Computes Euler's Totient Function in an optimized manner.",
"function_declaration": "def enhanced_euler_totient(n):",
"function_name": "enhanced_euler_totient",
"parameter_list": "(n)"
},
{
"docstring": "Helper function to create a list of primes up to limit using Sieve of Er... | [
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 sieve_of_eratosthenes(max_value):\n is_prime = [True] * (max_value + 1)\n is_prime[0] = is_prime[1] = False\n prime_list = []\n\n ... | trial_gpt4o_1 | {
"original_instruction": "### Question\nImplement a function `enhanced_euler_totient(n)` which computes the Euler's Totient Function in an optimized manner. Specifically, your solution should preprocess prime numbers up to √n to speed up the multiple calls to the function.\n\n#### Function Signature\n```python\ndef ... | 0.519066 | Data_Structure_6862 | C | [
"enhanced_euler_totient",
"sieve"
] | 2 | [
[
"enhanced_euler_totient",
"sieve"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1170f5f9715f3f3b5cfefd1adf47c8bee7186a91 | 2e3d6e303b957788cfffc92e8651456d12b767b0 | |||
v1.0 | complete | Data_Structure | Data_Structure_5978_C | def extended_gcd(a, b):
"""Auxiliary function to find the gcd and coefficients (x, y) such that ax + by = gcd(a, b)."""
# Your code here
def find_modular_inverse(a: int, m: int) -> int:
""" Find the modular inverse of `a` modulo `m`.
If the modular inverse does not exist, raise a `ValueError`.
>>> ... | def extended_gcd(a, b):
if a == 0:
return b, 0, 1
gcd, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y
def find_modular_inverse(a: int, m: int) -> int:
gcd, x, y = extended_gcd(a, m)
if gcd != 1:
raise ValueError("Modular inverse doesn't exist ... | from solution import find_modular_inverse
import pytest
def test_modular_inverse_common_case():
assert find_modular_inverse(3, 11) == 4
def test_modular_inverse_large_numbers():
assert find_modular_inverse(17, 3120) == 2753
def test_modular_inverse_not_coprime():
with pytest.raises(ValueError):
f... | [
{
"docstring": null,
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def find_modular_inverse(a, m):",
"function_name": "find_modular_inverse",
"parameter_list": "(a, m... | [
0,
0,
0,
0,
0,
1,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd_extended(a, b):\n if a == 0:\n return b, 0, 1\n gcd, x1, y1 = gcd_extended(b % a, a)\n x = y1 - (b // a) * x1\n y = x1\n return ... | trial_gpt4o_8 | {
"original_instruction": "You are implementing a system that requires modular arithmetic for handling large prime numbers. Given two numbers `a` and `m`, you need to find the modular inverse of `a` modulo `m`.\n\n### Task\nImplement a function `find_modular_inverse(a: int, m: int) -> int` that returns the modular in... | 0.598835 | Data_Structure_5978 | C | [
"extended_gcd",
"find_modular_inverse"
] | 2 | [
[
"find_modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3554d7411a44970867b75ee0e787b43ee3e6b333 | ccb1d8af29c0cae24f211e62c3f86957a9dd98c8 | |||
v1.0 | complete | Data_Structure | Data_Structure_5991_C | def has_permission(permissions: int, position: int) -> bool:
"""Check if a specific permission (given by position) is set in the permissions.
>>> has_permission(0b0001, 0)
True
>>> has_permission(0b0001, 1)
False
"""
pass
def grant_permission(permissions: int, position: int) -> int:
"""... | def has_permission(permissions: int, position: int) -> bool:
"""
Check if a specific permission (given by position) is set in the permissions.
"""
return (permissions & (1 << position)) != 0
def grant_permission(permissions: int, position: int) -> int:
"""
Grant a specific permission (set the b... | from solution import has_permission, grant_permission, revoke_permission, set_permission
def test_has_permission():
permissions = 0b0001
assert has_permission(permissions, 0) == True
assert has_permission(permissions, 1) == False
def test_grant_permission():
permissions = 0b0000
permissions = gran... | [
{
"docstring": "Check if a specific permission (given by position) is set in the permissions.",
"function_declaration": "def has_permission(permissions, position):",
"function_name": "has_permission",
"parameter_list": "(permissions, position)"
},
{
"docstring": "Grant a specific permission ... | [
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 has_permission(permissions: int, position: int) -> bool:\n \"\"\"\n Check if a specific permission (given by position) is set.\n Args:\n - per... | trial_gpt4o_2 | {
"original_instruction": "### Question: Bit Manipulation for Custom Permission System\n\nYou are tasked with developing a simple but efficient permission system using bit manipulation. Each user in your system will have an integer representing their permissions. Each bit in this integer corresponds to a specific per... | 0.494241 | Data_Structure_5991 | C | [
"has_permission",
"grant_permission",
"revoke_permission",
"set_permission"
] | 4 | [
[
"set_permission",
"grant_permission"
],
[
"set_permission",
"revoke_permission"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a4086cbced1d7dbc0d9f7f700746b864740f9d30 | 1452423fb87e885101193a1cd4f5f132c13add7d | |||
v1.0 | complete | Data_Structure | Data_Structure_6532_C | from typing import List, Dict
def search_patterns(text: str, patterns: List[str]) -> Dict[str, List[int]]:
"""
Given a text and a list of patterns, return a dictionary with patterns as keys and lists of starting indices where
patterns appear in the text.
The function uses the Knuth-Morris-Pratt (K... | from typing import List, Dict
def compute_kmp_table(pattern: str) -> List[int]:
"""
This function computes the partial match table (also known as the "next" table or "failure function")
used in KMP algorithm.
"""
m = len(pattern)
kmp_table = [0] * m
length = 0 # length of the previous long... | from solution import search_patterns
def test_single_pattern():
text = 'the quick brown fox jumps over the lazy dog'
patterns = ['the']
expected = {'the': [0, 31]}
assert search_patterns(text, patterns) == expected
def test_multiple_patterns():
text = 'the quick brown fox jumps over the lazy dog'
... | [
{
"docstring": "This function computes the partial match table (also known as the \"next\" table or \"failure function\")\nused in KMP algorithm.",
"function_declaration": "def compute_kmp_table(pattern):",
"function_name": "compute_kmp_table",
"parameter_list": "(pattern)"
},
{
"docstring":... | [
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, Dict\n\ndef search_patterns(text: str, patterns: List[str]) -> Dict[str, List[int]]:\n def compute_lps(pattern):\n lps = [0... | trial_gpt4o_1 | {
"original_instruction": "### Context\nA library search function needs optimizing. Users commonly search for a list of keywords within large texts such as books and articles. Using an efficient pattern matching algorithm can significantly reduce search times and improve user satisfaction.\n\n### Problem Statement\nY... | 0.688623 | Data_Structure_6532 | C | [
"compute_kmp_table",
"kmp_search",
"search_patterns"
] | 3 | [
[
"kmp_search",
"compute_kmp_table"
],
[
"search_patterns",
"kmp_search"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7a51b5b14809acfe3e4c829dcddca6fc9499e334 | 6e9bff61ab7c0473a74b02a203123d9b4969636a | |||
v1.0 | complete | Data_Structure | Data_Structure_6278_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big, small):
""" Determine if `t` is a subtree of `s`.
>>> s = TreeNode(3)
>>> s.left = TreeNode(4)
>>> s.right = TreeNode(5)
>>> s.left.le... | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big, small):
if not small:
return True # An empty tree is always a subtree
if not big:
return Fal... | from solution import TreeNode, is_subtree
def test_subtree_found_case_1():
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.left.right = TreeNode(2)
t = TreeNode(4)
t.left = TreeNode(1)
t.right = TreeNode(2)
assert is_subtree(s, t) == True... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_2 | {
"original_instruction": "### Coding Challenge: Subtree Check\n\nYou are given two binary trees, `s` and `t`. Your task is to write a function to determine if `t` is a subtree of `s`. A subtree of `s` is a node in `s` and all of its descendants that form a tree equivalent to `t`.\n\n### Your Function\nImplement the ... | 0.559698 | Data_Structure_6278 | C | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 9f44e5bc76337ac3f33c153c6f881d9a78cf7e15 | 98a169ab80aa7c9dcd1eb0ff5b6f3a001c7f6dcc | |||
v1.0 | complete | Data_Structure | Data_Structure_6611_C | from typing import List
def kmp_prefix_function(pattern: str) -> List[int]:
"""
Computes the prefix function for KMP algorithm.
>>> kmp_prefix_function("ababc") [0, 0, 1, 2, 0]
"""
pass # Implementation of KMP prefix function
def enhanced_kmp_search(text: str, pattern: str) -> List[int]:
"""
... | from typing import List
def kmp_prefix_function(pattern: str) -> List[int]:
"""
Computes the prefix function for KMP algorithm.
"""
prefix = [0] * len(pattern)
j = 0 # length of previous longest prefix suffix
i = 1
while i < len(pattern):
if pattern[i] == pattern[j]:
j ... | from solution import enhanced_kmp_search
def test_pattern_found_multiple_places():
assert enhanced_kmp_search("hello there hero!", "he") == [0, 7, 12]
def test_pattern_not_found():
assert enhanced_kmp_search("abcdef", "gh") == []
def test_empty_text_or_pattern():
assert enhanced_kmp_search("", "hi") == [... | [
{
"docstring": "Computes the prefix function for KMP algorithm.",
"function_declaration": "def kmp_prefix_function(pattern):",
"function_name": "kmp_prefix_function",
"parameter_list": "(pattern)"
},
{
"docstring": "Searches for all occurrences of the pattern in the text using KMP 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 List\n\ndef kmp_prefix_function(pattern: str) -> List[int]:\n \"\"\"\n Computes the prefix function for KMP algorithm.\n \"\"\"\n ... | trial_gpt4o_0 | {
"original_instruction": "### Problem: Enhanced Substring Search Using KMP\n\nYou are working on a text processing tool that requires efficient substring matching. To accomplish this, you will implement an optimized substring search algorithm using the Knuth-Morris-Pratt (KMP) algorithm. The task is to write a funct... | 0.57194 | Data_Structure_6611 | C | [
"kmp_prefix_function",
"enhanced_kmp_search"
] | 2 | [
[
"enhanced_kmp_search",
"kmp_prefix_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 62016442610c306a9ee2c4be386996f1fe58877b | 62f804d912ff3465a2c7cbc2a4d0bafa44e93a03 | |||
v1.0 | complete | Data_Structure | Data_Structure_6168_C | def gcd(a, b):
"""Helper function to compute gcd of a and b"""
while b:
a, b = b, a % b
return a
def euler_totient(n: int) -> int:
""" Calculate Euler's Totient function ϕ(n) which counts the number of positive integers up to `n` that are coprime with `n`.
Args:
n (int): A positive... | def gcd(a, b):
while b:
a, b = b, a % b
return a
def euler_totient(n: int) -> int:
count = 0
for i in range(1, n + 1):
if gcd(n, i) == 1:
count += 1
return count
def gcd_sum(N: int) -> int:
total = 0
for i in range(1, N + 1):
total += euler_totient(i)
... | from solution import euler_totient, gcd_sum
def test_euler_totient():
assert euler_totient(1) == 1
assert euler_totient(2) == 1
assert euler_totient(3) == 2
assert euler_totient(4) == 2
assert euler_totient(5) == 4
assert euler_totient(6) == 2
assert euler_totient(7) == 6
assert euler_t... | [
{
"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,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def euler_totient(n: int) -> int:\n \"\"\"\n Calculates Euler's Totient function value for a given integer n.\n This counts the number of positive in... | trial_gpt4o_2 | {
"original_instruction": "### Euler's Totient Function and GCD Sum Calculation\n\n#### Problem Statement\nEuler's Totient function, denoted as ϕ(n), counts the number of positive integers up to `n` that are coprime with `n`. Implement the function `euler_totient()` that calculates ϕ(n) as follows:\n\n```python\ndef ... | 0.694553 | Data_Structure_6168 | C | [
"gcd",
"euler_totient",
"gcd_sum"
] | 3 | [
[
"euler_totient",
"gcd"
],
[
"gcd_sum",
"euler_totient"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 614d8ddac908871f1eeae4bd0c6c3e1593ebafc9 | a358eb92085dfaffdb642236e8c0a679a1abb34f | |||
v1.0 | complete | Data_Structure | Data_Structure_7098_C | def is_primitive_root(a: int, n: int) -> bool:
""" Check if a given number a is a primitive root of n.
>>> is_primitive_root(2, 5) True
>>> is_primitive_root(3, 7) True
>>> is_primitive_root(2, 8) False
""" | def gcd(a, b):
"""
Helper function to calculate the greatest common divisor (GCD) of two numbers.
"""
while b:
a, b = b, a % b
return a
def euler_totient(n):
"""
Function to compute Euler's Totient function, φ(n).
"""
result = n # Initialize result as n
p = 2
while... | from solution import is_primitive_root
def test_is_primitive_root_example1():
assert is_primitive_root(2, 5) == True
def test_is_primitive_root_example2():
assert is_primitive_root(3, 7) == True
def test_is_primitive_root_example3():
assert is_primitive_root(2, 8) == False
def test_is_primitive_root_cop... | [
{
"docstring": "Helper function to calculate the greatest common divisor (GCD) of two numbers.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Function to compute Euler's Totient function, φ(n).",
"function_declaration": "... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef euler_totient(n):\n result = n\n p = 2\n while p * p <= n:\n if n %... | trial_gpt4o_7 | {
"original_instruction": "You are given two algorithms: one that computes the Euler's Totient Function (ϕ(n)) and another that finds all primitive roots of a given integer \\( n \\). Your task is to extend this functionality by writing a function that integrates both algorithms to solve the following problem:\n\n###... | 0.671555 | Data_Structure_7098 | C | [
"gcd",
"euler_totient",
"is_primitive_root"
] | 3 | [
[
"is_primitive_root",
"euler_totient"
],
[
"is_primitive_root",
"gcd"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8fdb547f546ee7f8a341978eeb8a581a4b4616cd | 951aa3ff38326061c90a3265b42052d19c04624e | |||
v1.0 | complete | Data_Structure | Data_Structure_5586_C | import math
import random
def prime_check(num):
"""
Returns True if num is a prime number, otherwise False.
>>> prime_check(2) True
>>> prime_check(4) False
>>> prime_check(17) True
>>> prime_check(18) False
"""
def euler_totient(n):
"""
Returns the Euler's totient function value o... | import math
import random
def prime_check(num):
"""
Returns True if num is a prime number, otherwise False.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or n... | import pytest
from solution import (prime_check, euler_totient, find_primitive_root,
alice_private_key, alice_public_key, bob_private_key,
bob_public_key, alice_shared_key, bob_shared_key,
diffie_hellman_key_exchange)
def test_prime_check():
assert... | [
{
"docstring": "Returns True if num is a prime number, otherwise False.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Returns the Euler's totient function value of n.",
"function_declaration": "def euler_to... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport math\n\ndef prime_check(num):\n \"\"\"\n Returns True if the number is prime, False otherwise.\n \"\"\"\n if num < 2:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nYou are working on implementing a secure communication system where two parties need to establish a shared secret key over an insecure network. Your task is to implement the core phases of the Diffie-Hellman key exchange protocol.\n\n### Objective\nWrite functions to carry out... | 0.582193 | Data_Structure_5586 | C | [
"prime_check",
"euler_totient",
"find_primitive_root",
"alice_private_key",
"alice_public_key",
"bob_private_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"diffie_hellman_key_exchange"
] | 10 | [
[
"diffie_hellman_key_exchange",
"alice_private_key"
],
[
"diffie_hellman_key_exchange",
"alice_public_key"
],
[
"diffie_hellman_key_exchange",
"alice_shared_key"
],
[
"diffie_hellman_key_exchange",
"bob_private_key"
],
[
"diffie_hellman_key_exchange",
"bob_pu... | 10 | [] | false | [] | false | pytest | true | [] | true | 0bdf029940b3d5545d6a1a9ca405685e9c846d4c | 6182e8907cd96254a8e172b7b66e088022820a0e | |||
v1.0 | complete | Data_Structure | Data_Structure_5643_C | def hybrid_heap_sort(arr):
"""
Task: Implement a Hybrid Heap Sort Algorithm
Objective:
Using the principles of both Max Heap Sort and Min Heap Sort, develop a hybrid heap sort algorithm that can dynamically switch between Max Heap and Min Heap based on certain conditions, optimizing the overall sorting... | def max_heapify(arr, n, i):
"""
Helper function to maintain the max heap property for the given subtree.
"""
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 = righ... | from solution import hybrid_heap_sort
def test_hybrid_heap_sort_basic():
arr = [4, 10, 3, 5, 1, 7, 9, 6]
assert hybrid_heap_sort(arr) == [1, 3, 4, 5, 6, 7, 9, 10]
def test_hybrid_heap_sort_single_element():
arr = [1]
assert hybrid_heap_sort(arr) == [1]
def test_hybrid_heap_sort_sorted_array():
ar... | [
{
"docstring": "Helper function to maintain the max heap property for the given subtree.",
"function_declaration": "def max_heapify(arr, n, i):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Helper function to maintain the min heap property for the given... | [
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 heapify(arr, n, i, max_heap=True):\n largest_smallest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if max_heap:\n if left < n and arr... | trial_gpt4o_2 | {
"original_instruction": "### Task: Implement a Hybrid Heap Sort Algorithm\n\n#### Objective\nUsing the principles of both Max Heap Sort and Min Heap Sort, develop a hybrid heap sort algorithm that can dynamically switch between Max Heap and Min Heap based on certain conditions, optimizing the overall sorting proces... | 0.613062 | Data_Structure_5643 | C | [
"max_heapify",
"min_heapify",
"max_heap_sort",
"min_heap_sort",
"hybrid_heap_sort"
] | 5 | [
[
"hybrid_heap_sort",
"max_heap_sort"
],
[
"hybrid_heap_sort",
"min_heap_sort"
],
[
"max_heap_sort",
"max_heapify"
],
[
"min_heap_sort",
"min_heapify"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 074f447105b649dd5e08da8e863ddab9be3b0351 | f065f2e8bee75ce9248c1615502942168dc7a139 | |||
v1.0 | complete | Data_Structure | Data_Structure_4997_C | from typing import List, Tuple
def hailstone(n: int) -> List[int]:
"""
Generate the hailstone sequence starting from an integer n.
Parameters:
n (int): A positive integer (1 ≤ n ≤ 10^6).
Returns:
List[int]: A list representing the hailstone sequence starting from n and end... | def hailstone(n):
"""
Generate the hailstone sequence starting from an integer n.
Parameters:
n (int): A positive integer (1 ≤ n ≤ 10^6).
Returns:
List[int]: A list representing the hailstone sequence starting from n and ending at 1.
"""
sequence = []
while n !=... | from solution import hailstone, hailstone_extended_statistics
def test_hailstone_1():
assert hailstone(1) == [1]
def test_hailstone_7():
assert hailstone(7) == [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
def test_hailstone_27():
assert hailstone(27) == [27, 82, 41, 124, 62, 31, 94, 47,... | [
{
"docstring": "Generate the hailstone sequence starting from an integer n.\n\nParameters:\n n (int): A positive integer (1 ≤ n ≤ 10^6).\n \nReturns:\n List[int]: A list representing the hailstone sequence starting from n and ending at 1.",
"function_declaration": "def hailstone(n):",
"function... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def hailstone(n):\n \"\"\"\n Returns the hailstone sequence starting from n and ending at 1.\n \"\"\"\n sequence = []\n while n != 1:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Hailstone Sequence Analysis and Extension\n\n#### Objective:\nImplement and analyze the hailstone sequence generator and write a function to compute statistics on the sequence.\n\n#### Details:\n1. **Function 1**: `hailstone(n)`: Generate the hailstone sequence starting from an integer ... | 0.574773 | Data_Structure_4997 | C | [
"hailstone",
"hailstone_extended_statistics"
] | 2 | [
[
"hailstone_extended_statistics",
"hailstone"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2e18e1bf7f21e7f240a53afd17ca18ff3a5770de | d62148198296f5e39d744b53484e0f3cbe01c114 | |||
v1.0 | complete | Data_Structure | Data_Structure_6706_C | from typing import List
def search_pattern(text: str, pattern: str) -> List[int]:
"""
Uses the KMP algorithm to find all occurrences of the pattern in the text.
Args:
text (str): A string representing the text to search within.
pattern (str): A string representing the pattern to search for.
... | from typing import List
def kmp_prefix_function(pattern: str) -> List[int]:
"""
Builds the prefix function for the KMP algorithm.
"""
m = len(pattern)
prefix = [0] * m
j = 0
for i in range(1, m):
while j > 0 and pattern[i] != pattern[j]:
j = prefix[j - 1]
if... | from solution import search_pattern
def test_search_pattern_basic():
assert search_pattern("hello there hero!", "he") == [0, 7, 12]
assert search_pattern("aaaaa", "aa") == [0, 1, 2, 3]
assert search_pattern("abcdef", "gh") == []
def test_search_pattern_empty_text():
assert search_pattern("", "pat") ==... | [
{
"docstring": "Builds the prefix function for the KMP algorithm.",
"function_declaration": "def kmp_prefix_function(pattern):",
"function_name": "kmp_prefix_function",
"parameter_list": "(pattern)"
},
{
"docstring": "Uses the KMP algorithm to find all occurrences of the pattern in the text.... | [
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 kmp_partial_match_table(pattern: str) -> List[int]:\n \"\"\"\n Generate the partial match table (also known as the \"pref... | trial_gpt4o_1 | {
"original_instruction": "**Scenario**:\nYou are working for a company that provides search functionality for a large text repository. Your task is to optimize the search operations by implementing the Knuth-Morris-Pratt (KMP) algorithm. Your solution should efficiently find all occurrences of a given pattern in a t... | 0.618523 | Data_Structure_6706 | C | [
"kmp_prefix_function",
"search_pattern"
] | 2 | [
[
"search_pattern",
"kmp_prefix_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a9e0f4993c50d40146d7f93cb04a4b9b4fb8ed5b | db30e454004d9b95225558a3b2a2a84679faa7a0 | |||
v1.0 | complete | Data_Structure | Data_Structure_6946_C | def efficient_lcm(a: int, b: int) -> int:
"""Calculate and return the Least Common Multiple (LCM) of two non-zero integers a and b.
>>> efficient_lcm(12, 18)
36
>>> efficient_lcm(-4, 5)
20
>>> efficient_lcm(123456789, 987654321)
13548070123626141
>>> efficient_lcm(7, 7)
7
""" | def gcd(a, b):
"""
Helper function to calculate the greatest common divisor (GCD) using Euclid's Algorithm.
"""
while b:
a, b = b, a % b
return abs(a)
def efficient_lcm(a, b):
"""
Calculate and return the Least Common Multiple (LCM) of two non-zero integers a and b.
"""
# Ca... | from solution import efficient_lcm
def test_lcm_positive_numbers():
assert efficient_lcm(12, 18) == 36
assert efficient_lcm(4, 5) == 20
def test_lcm_negative_positive_numbers():
assert efficient_lcm(-4, 5) == 20
assert efficient_lcm(6, -8) == 24
def test_lcm_both_negative_numbers():
assert effici... | [
{
"docstring": "Helper function to calculate the greatest common divisor (GCD) using Euclid's Algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate and return the Least Common Multiple (LCM) of two non-zero inte... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef efficient_lcm(a: int, b: int) -> int:\n \"\"\"\n Returns the Least Common Multiple (LCM) of two non-zero integers.\n \"\"\"\n r... | trial_gpt4o_2 | {
"original_instruction": "<|Analysis Begin|>\n\n### Algorithm Analysis\n\n#### Core Identification\n- **Algorithm/Data Structure**: \n - **Algorithm 1**: GCD (Greatest Common Divisor) using Euclid’s Algorithm.\n - **Algorithm 2**: LCM (Least Common Multiple).\n - **Algorithm 3**: Counting Trailing Zeroes in Integ... | 0.686083 | Data_Structure_6946 | C | [
"gcd",
"efficient_lcm"
] | 2 | [
[
"efficient_lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5ad01df2fa07c3b3a958d2c7b9c2156545b38eec | 187b317df66441eca45569471bb6f0228c96dbe3 | |||
v1.0 | complete | Data_Structure | Data_Structure_5548_C | def radix_sort(arr: list, simulation: bool = False) -> list:
"""
Implement a function that takes a list of non-negative integers and returns a sorted list using the radix sort algorithm.
Parameters:
arr (list of int): List of non-negative integers to sort.
simulation (bool): If True, print the ... | def counting_sort(arr, exp, simulation=False):
n = len(arr)
output = [0] * n
count = [0] * 10
# Count occurrences of digits
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
# Convert count to position array
for i in range(1, 10):
count[i] += c... | from solution import radix_sort
def test_radix_sort_basic():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_single_element():
assert radix_sort([1]) == [1]
def test_radix_sort_sorted():
assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
d... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation=False):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation=False)"
},
{
"docstring": "Function to perform radix sort on a list of non-negative integers.\n\nParameters:\narr (list of... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp, simulation=False):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \n # Count occurrences of digits\n for... | trial_gpt4o_0 | {
"original_instruction": "### Radix Sort Implementation Challenge\n\n**Scenario**:\nYou are provided with a list of non-negative integers that need to be sorted efficiently. One of the algorithms that excel in this scenario is Radix Sort.\n\n**Task**:\nImplement a function that takes a list of non-negative integers ... | 0.671747 | Data_Structure_5548 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5cd7cab361b1324ce6b1a173e4fe6ebf9cf28712 | edf79a8fd5d055529d7c2b8defead2c4352dc115 | |||
v1.0 | complete | Data_Structure | Data_Structure_6574_C | from typing import List
def calculate_maximum_flow(adjacency_matrix: List[List[int]]) -> int:
""" Calculate the maximum flow from the source node to the sink node using an adjacency matrix.
Args:
adjacency_matrix (List[List[int]]): A n x n matrix where matrix[i][j] represents the capacity of the edge ... | from typing import List
def bfs(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:
visited = [False] * len(residual_graph)
queue = [source]
visited[source] = True
while queue:
u = queue.pop(0)
for ind, val in enumerate(residual_graph[u]):
... | from solution import calculate_maximum_flow
def test_simple_case():
graph = [[0, 1], [0, 0]]
assert calculate_maximum_flow(graph) == 1
def test_sample_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],
... | [
{
"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 calculate_maximum_flow(adjacency_matrix):",
"function... | [
0,
0,
0,
1,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef calculate_maximum_flow(adjacency_matrix: List[List[int]]) -> int:\n \"\"\"\n Uses the Ford-Fulkerson method and BFS for f... | trial_gpt4o_7 | {
"original_instruction": "### Context\n\nYou are developing a transportation network that requires ensuring maximum throughput from a starting point to a destination. By interpreting the capacity limits between multiple transportation hubs (nodes) represented by an adjacency matrix, your task is to calculate the max... | 0.582999 | Data_Structure_6574 | C | [
"bfs",
"calculate_maximum_flow"
] | 2 | [
[
"calculate_maximum_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e263fd080dcfb7a1f353c391c766ef126002d70e | 88750abbb1c464761f49710a13d64a359d02a07b | |||
v1.0 | complete | Data_Structure | Data_Structure_6624_C | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_subtree(big: TreeNode, small: TreeNode) -> bool:
""" Given two binary trees, `big` and `small`, check if `small` is a subtree of `big`.
>>> big = TreeNode(3)
>>> big.left = TreeNode(4)
... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_subtree(big: TreeNode, small: TreeNode) -> bool:
if not small:
return True
if not big:
return False
if is_identical(big, small):
return True
return... | import pytest
from solution import TreeNode, is_subtree
def test_case_1():
"""
big:
3
/ \
4 5
/ \
1 2
small:
4
/ \
1 2
Output should be True
"""
big = TreeNode(3)
big.left = TreeNode(4)
big.right = TreeNode(5)
big.left.le... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n \ndef is_subtree(big: TreeNode... | trial_gpt4o_2 | {
"original_instruction": "Given two binary trees, `big` and `small`, write a function that checks if `small` is a subtree of `big`. A subtree of a tree `T` is a tree consisting of a node in `T` and all of its descendants in `T`.\n\n#### Function Signature\n```python\ndef is_subtree(big: TreeNode, small: TreeNode) ->... | 0.601851 | Data_Structure_6624 | C | [
"is_subtree",
"is_identical"
] | 2 | [
[
"is_subtree",
"is_identical"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | da706fa354b17c4d8ccc5ca3bc911f2691720759 | 3678e1cd3a53cf75cacf8152e861abfee8b5f595 | |||
v1.0 | complete | Data_Structure | Data_Structure_5450_C | def enhanced_sort(arr):
"""
Enhanced sorting function combining cocktail shaker sort with a more efficient algorithm.
Args:
arr (list): A list of integers to be sorted.
Returns:
list: The sorted list.
"""
pass
def cocktail_shaker_sort(arr):
"""
Cocktail shaker sort function to... | def cocktail_shaker_sort(arr):
n = len(arr)
swapped = True
start = 0
end = n - 1
while swapped:
swapped = False
for i in range(start, end):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
swapped = True
if not swappe... | from solution import enhanced_sort
def test_enhanced_sort_small_array():
assert enhanced_sort([3, 2, 5, 4, 1]) == [1, 2, 3, 4, 5]
def test_enhanced_sort_sorted_array():
assert enhanced_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
assert enhanced_sort([10, 20, 30, 40, 50]) == [10, 20, 30, 40, 50]
def test_enh... | [
{
"docstring": null,
"function_declaration": "def cocktail_shaker_sort(arr):",
"function_name": "cocktail_shaker_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Enhanced sorting function combining cocktail shaker sort with a more efficient algorithm.\n\nArgs:\narr (list): A list of 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 cocktail_shaker_sort(arr):\n \"\"\"\n Helper function to perform Cocktail Shaker Sort on the array.\n \"\"\"\n n = len(arr)\n swapped = Tru... | trial_gpt4o_2 | {
"original_instruction": "### Question: Enhanced Sorting Algorithm Implementation\n\nGiven the provided code snippet for the Cocktail Shaker Sort, your task is to implement an enhanced sorting algorithm with the following specifications:\n\n1. **Hybrid Approach**: Combine the Cocktail Shaker Sort with a more efficie... | 0.624944 | Data_Structure_5450 | C | [
"cocktail_shaker_sort",
"enhanced_sort"
] | 2 | [
[
"enhanced_sort",
"cocktail_shaker_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5f8df3d86de06709896ea68292b1dbc51f3b5707 | 3b48bf47a8ad84be56f1ec4ccee1edba9e5715a3 | |||
v1.0 | complete | Data_Structure | Data_Structure_6597_C | def radix_sort(arr: List[int]) -> List[int]:
"""Perform Radix Sort on a list of non-negative integers.
>>> radix_sort([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66, 75, 90, 170, 802]
>>> radix_sort([3, 3, 1, 2])
[1, 2, 3, 3]
>>> radix_sort([42])
[42]
>>> radix_sort([])
[]
>>>... | def radix_sort(arr):
"""
Perform Radix Sort on a list of non-negative integers.
:param arr: List[int] - a list of non-negative integers
:return: List[int] - the sorted list
"""
if not arr:
return arr
# Find the maximum number to know the number of digits
max_num = max(arr)
e... | 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_duplicates():
assert radix_sort([3, 3, 1, 2]) == [1, 2, 3, 3]
def test_radix_sort_single_element():
assert radix_sort([42]) == [4... | [
{
"docstring": "Perform Radix Sort on a list of non-negative integers.\n:param arr: List[int] - a list of non-negative integers\n:return: List[int] - the sorted list",
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
},
{
"docstring": "... | [
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):\n \"\"\"\n Perform radix sort on a list of non-negative integers.\n \n Parameters:\n arr (List[int]): The list of non-nega... | trial_gpt4o_2 | {
"original_instruction": "### Question: Radix Sort Implementation Challenge\n\n**Problem Statement**:\nYou are required to implement the Radix Sort algorithm from scratch. Radix Sort is an efficient, non-comparative sorting algorithm that sorts numbers based on individual digits. The algorithm uses a positional proc... | 0.68796 | Data_Structure_6597 | C | [
"radix_sort",
"counting_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c96f70be91fcba83f9df1f8fae3029a7a04cc10f | fbcbb0e690608fd51769bd4f88ef4ce30130d6ed | |||
v1.0 | complete | Data_Structure | Data_Structure_6915_C | from typing import List
def bucket_sort(arr: List[int]) -> List[int]:
""" Sorts an array of non-negative integers using the bucket sort algorithm.
Args:
arr (List[int]): A list of non-negative integers.
Returns:
List[int]: The sorted list.
Example:
>>> bucket_sort([78... | def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
def bucket_sort(arr):
if len(arr) == 0... | from solution import bucket_sort
def test_bucket_sort_empty_array():
assert bucket_sort([]) == []
def test_bucket_sort_single_element_array():
assert bucket_sort([1]) == [1]
def test_bucket_sort_all_same_elements():
assert bucket_sort([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5]
def test_bucket_sort_already_sort... | [
{
"docstring": null,
"function_declaration": "def quick_sort(arr):",
"function_name": "quick_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def bucket_sort(arr):",
"function_name": "bucket_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) > 1:\n mid = len(arr) // 2\n left_half = arr[:mid]\n ... | trial_gpt4o_2 | {
"original_instruction": "### Bucket Sort Implementation and Optimization\n\n#### Context:\nYou are given an array of non-negative integers. Your task is to implement the bucket sort algorithm to sort the array. Bucket sort works by distributing the elements of an array into several buckets. Each bucket is then sort... | 0.649577 | Data_Structure_6915 | C | [
"quick_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"quick_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4e14989ed078bc24e65a44de15626014fba0b6de | 46aa15bd8c94bdecd1d13c9265db5ec40bd90455 | |||
v1.0 | complete | Data_Structure | Data_Structure_7051_C | def contain_string_kmp(haystack: str, needle: str) -> int:
""" Use the Knuth-Morris-Pratt (KMP) algorithm to search for occurrences of a "word" (needle)
within a main "text" (haystack) efficiently.
>>> contain_string_kmp("hello", "ll")
2
>>> contain_string_kmp("aaaaa", "bba")
-1
>>> co... | def compute_prefix_function(needle):
m = len(needle)
lps = [0] * m
length = 0
i = 1
while i < m:
if needle[i] == needle[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
... | from solution import contain_string_kmp
def test_haystack_contains_needle():
assert contain_string_kmp("hello", "ll") == 2
def test_haystack_does_not_contain_needle():
assert contain_string_kmp("aaaaa", "bba") == -1
def test_empty_haystack_and_needle():
assert contain_string_kmp("", "") == 0
def test_ha... | [
{
"docstring": null,
"function_declaration": "def compute_prefix_function(needle):",
"function_name": "compute_prefix_function",
"parameter_list": "(needle)"
},
{
"docstring": null,
"function_declaration": "def contain_string_kmp(haystack, needle):",
"function_name": "contain_string_... | [
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 create_prefix_table(pattern):\n \"\"\"\n Create prefix table for the given pattern.\n \"\"\"\n prefix_table = [0] * len(pattern)\n j = 0\n ... | trial_gpt4o_2 | {
"original_instruction": "Substring Search Enhancement\n\nIn this task, you are required to enhance the performance of the given substring search algorithm. The existing algorithm uses a simple linear search that results in an O(n*m) time complexity, which can be inefficient for larger texts and patterns. Your objec... | 0.538692 | Data_Structure_7051 | C | [
"compute_prefix_function",
"contain_string_kmp"
] | 2 | [
[
"contain_string_kmp",
"compute_prefix_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c28132b5b3c32b18e34bf495da05750817636763 | ac4b60bad06211c3bc0a0a40c60fc18c6dcab008 | |||
v1.0 | complete | Data_Structure | Data_Structure_6359_C | def gcd_bitwise(a: int, b: int) -> int:
"""
Calculates the greatest common divisor (GCD) of two non-negative integers using bitwise operations.
>>> gcd_bitwise(48, 18) 6
>>> gcd_bitwise(0, 5) 5
>>> gcd_bitwise(7, 0) 7
>>> gcd_bitwise(0, 0) 0
>>> gcd_bitwise(101, 103) 1
"""
def lcm_with... | def gcd_bitwise(a: int, b: int) -> int:
"""
Calculates the greatest common divisor (GCD) of two non-negative integers using bitwise operations.
"""
if a == 0:
return b
if b == 0:
return a
# Finding common factors of 2
shift = 0
while ((a | b) & 1) == 0:
a >>= 1
... | from solution import gcd_bitwise, lcm_with_gcd, count_trailing_zeros
def test_gcd_bitwise():
assert gcd_bitwise(48, 18) == 6
assert gcd_bitwise(0, 5) == 5
assert gcd_bitwise(7, 0) == 7
assert gcd_bitwise(0, 0) == 0
assert gcd_bitwise(101, 103) == 1
def test_lcm_with_gcd():
assert lcm_with_gcd(... | [
{
"docstring": "Calculates the greatest common divisor (GCD) of two non-negative integers using bitwise operations.",
"function_declaration": "def gcd_bitwise(a, b):",
"function_name": "gcd_bitwise",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculates the least common multiple (LCM) of ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd_bitwise(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": "### Problem: Advanced Number Operations\nYou are tasked with implementing a series of functions that perform advanced number operations. These functions will require you to handle integer properties efficiently. Your implementation must account for edge cases carefully and optimize performa... | 0.731551 | Data_Structure_6359 | C | [
"gcd_bitwise",
"lcm_with_gcd",
"count_trailing_zeros"
] | 3 | [
[
"lcm_with_gcd",
"gcd_bitwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d99cf4a11e1e0c6fd1c05633fbfe0ada3db7fca3 | 9302da40571ea33b04f4b1d19e9f701ca33b6483 | |||
v1.0 | complete | Data_Structure | Data_Structure_5725_C | from enum import Enum
class TraversalState(Enum):
WHITE = 0
GRAY = 1
BLACK = 2
def is_in_cycle(graph, traversal_states, vertex):
if traversal_states[vertex] == TraversalState.GRAY:
return True
traversal_states[vertex] = TraversalState.GRAY
for neighbor in graph[vertex]:
if trav... | from enum import Enum
class TraversalState(Enum):
WHITE = 0
GRAY = 1
BLACK = 2
def is_in_cycle(graph, traversal_states, vertex):
if traversal_states[vertex] == TraversalState.GRAY:
return True
traversal_states[vertex] = TraversalState.GRAY
for neighbor in graph[vertex]:
if trav... | def test_contains_cycle_true():
graph = {
'A': ['B'],
'B': ['C'],
'C': ['A']
}
assert contains_cycle(graph) == True
def test_contains_cycle_false():
graph = {
'A': ['B'],
'B': ['C'],
'C': ['D'],
'D': []
}
assert contains_cycle(graph) == Fa... | [] | [
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 enum import Enum\n\nclass TraversalState(Enum):\n WHITE = 0\n GRAY = 1\n BLACK = 2\n\ndef is_in_cycle(graph, traversal_states, vertex):\n if ... | trial_gpt4o_2 | {
"original_instruction": "## Question: Cycle Detection in a Directed Graph\n\n### Objective\nWrite a function to determine whether a given directed graph contains a cycle.\n\n### Input\n- A dictionary representing the directed graph. Each key-value pair represents a vertex and its list of adjacent vertices (the outg... | 0.563002 | Data_Structure_5725 | C | [
"is_in_cycle",
"contains_cycle"
] | 2 | [
[
"contains_cycle",
"is_in_cycle"
]
] | 1 | [] | false | [
"TraversalState"
] | true | pytest | false | [] | true | fe3d63179213d297728597af130b6d74af9bdbd3 | 0846e71549ddda7812839ab7fb64b6f0adeeb4f9 | |||
v1.0 | complete | Data_Structure | Data_Structure_6870_C | from typing import List
def search_pattern(text: str, pattern: str) -> List[int]:
"""
Implements the Knuth-Morris-Pratt (KMP) algorithm to find all occurrences of a pattern in a given text.
Args:
text: str - The text where we search the pattern.
pattern: str - The pattern to search within the text... | from typing import List
def compute_lps(pattern: str) -> List[int]:
"""
Computes the Longest Prefix Suffix (LPS) array using the given pattern.
The LPS array is used to skip characters while matching the pattern in the text.
"""
lps = [0] * len(pattern)
length = 0
i = 1
while i < l... | from solution import search_pattern
def test_search_pattern_example1():
assert search_pattern('abracadabra', 'abra') == [0, 7]
def test_search_pattern_example2():
assert search_pattern('aabaaabaaac', 'aabaaac') == [4]
def test_search_pattern_example3():
assert search_pattern('hello', 'world') == []
def ... | [
{
"docstring": "Computes the Longest Prefix Suffix (LPS) array using the given pattern.\nThe LPS array is used to skip characters while matching the pattern in the text.",
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
... | [
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 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": "from typing import List\n\ndef compute_lps(pattern: str) -> List[int]:\n \"\"\"\n Helper function to preprocess the pattern by ... | trial_gpt4o_4 | {
"original_instruction": "You are given the task of implementing a search feature for a large corpus of text documents. The feature should efficiently find all occurrences of a specified pattern within a given text and return the starting indices of each match.\n\n### Objective\n\nWrite a function `search_pattern` t... | 0.632284 | Data_Structure_6870 | C | [
"compute_lps",
"search_pattern"
] | 2 | [
[
"search_pattern",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3f5e58f28a942fb5ac651b4b7d4eb768b4698f69 | ba9c610552120bdeabdd4669e1e05177727f588c | |||
v1.0 | complete | Data_Structure | Data_Structure_6572_C | import random
def is_sorted(arr):
"""
Helper function to check if an array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def safe_bogo_sort(arr, max_iterations, simulation=False):
"""
Partially utilizes Bogo Sort principle... | import random
def is_sorted(arr):
"""
Helper function to check if an array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def safe_bogo_sort(arr, max_iterations, simulation=False):
"""
Partially utilizes Bogo Sort principle... | from solution import safe_bogo_sort
def test_safe_bogo_sort_sorted_array():
assert safe_bogo_sort([1, 2, 3, 4, 5], 1000) == [1, 2, 3, 4, 5]
def test_safe_bogo_sort_single_iteration():
# Known sorted array should return as is in first iteration
assert safe_bogo_sort([1, 2, 3, 4, 5], 1) == [1, 2, 3, 4, 5]
... | [
{
"docstring": "Helper function to check if an array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Partially utilizes Bogo Sort principles but safely handles large datasets by\nallowing a maximum number ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if an array is sorted.\n \"\"\"\n for i in range(len(arr) - 1):\n ... | trial_gpt4o_0 | {
"original_instruction": "### Problem: Implementation of a Safe Bogo Sort\nBogo Sort is a highly impractical sorting algorithm due to its reliance on sheer luck to sort the array. Your task is to write a function that partially utilizes Bogo Sort principles but safely handles large datasets by allowing a maximum num... | 0.63837 | Data_Structure_6572 | C | [
"is_sorted",
"safe_bogo_sort"
] | 2 | [
[
"safe_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 277e18f66bc6ee79d13d1ce1b2de85bebef4e729 | 1983267d6dff54005344975dec3e82118b381d37 | |||
v1.0 | complete | Data_Structure | Data_Structure_7255_C | def solve_diophantine(a: int, b: int, c: int) -> tuple[int, int] | None:
""" Solves the Linear Diophantine Equation a * x + b * y = c.
Determines whether there exist integer solutions to the equation.
If such solutions exist, return a pair (x, y). If no solutions exist, return None.
>>> solve_... | def extended_gcd(a, b):
"""
Computes the extended GCD of a and b.
Returns a tuple (g, x, y) where g is the GCD of a and b,
and x and y are the coefficients such that a*x + b*y = g.
"""
if b == 0:
return (a, 1, 0)
else:
g, x1, y1 = extended_gcd(b, a % b)
x = y1
... | from solution import solve_diophantine
def test_solve_diophantine_positive_solution():
result = solve_diophantine(30, 20, 10)
assert result is not None
assert 30 * result[0] + 20 * result[1] == 10
def test_solve_diophantine_no_solution():
assert solve_diophantine(35, 15, 1) == None
def test_solve_dio... | [
{
"docstring": "Computes the extended GCD of a and b.\nReturns a tuple (g, x, y) where g is the GCD of a and b, \nand x and y are the coefficients such that a*x + b*y = g.",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"d... | [
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 extended_gcd(a, b):\n \"\"\"\n Returns a tuple (g, x, y) where g is the greatest common divisor of a and b, \n and x, y are the coefficients of B... | trial_gpt4o_1 | {
"original_instruction": "### Extended Euclidean Algorithm Application\n\nYou are provided with an implementation of the extended Euclidean algorithm. The goal is to further comprehend the versatility of this fundamental algorithm by applying it to solve a slightly more complex problem. Your task is to use the exten... | 0.592623 | Data_Structure_7255 | C | [
"extended_gcd",
"solve_diophantine"
] | 2 | [
[
"solve_diophantine",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 74ca78ae6ec6e08e4dbdfe5c59d85a47c52162b3 | 68c4879f8defaf536f4443c3873d26cea24eb1b1 | |||
v1.0 | complete | Data_Structure | Data_Structure_7201_C | def search_insert(array, val):
"""
Helper function that performs a binary search to find the correct insertion index for val in array.
"""
pass
def insertion_sort_with_binary_search(array: list) -> list:
"""
Sorts an array using insertion sort, with binary search to find the correct position f... | def search_insert(array, val):
"""
Helper function that performs a binary search to find the correct insertion index for val in array.
"""
left, right = 0, len(array)
while left < right:
mid = (left + right) // 2
if array[mid] < val:
left = mid + 1
else:
... | from solution import insertion_sort_with_binary_search
def test_insertion_sort_with_binary_search_case1():
assert insertion_sort_with_binary_search([3, 4, 2, 1]) == [1, 2, 3, 4]
def test_insertion_sort_with_binary_search_case2():
assert insertion_sort_with_binary_search([10, -1, 2, 5, 20, -5]) == [-5, -1, 2, ... | [
{
"docstring": "Helper function that performs a binary search to find the correct insertion index for val in array.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "Sorts an array using insertion... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(array, val):\n \"\"\"\n Helper function to find the index where 'val' should be inserted in order to maintain sorted order.\n Uses ... | trial_gpt4o_2 | {
"original_instruction": "## Question\n\n### Context:\nYou are provided with a helper function, `search_insert`, which performs binary search to find the correct position to insert an element into a sorted list. Your task is to use this helper function to implement the full Insertion Sort algorithm.\n\n### Task:\nIm... | 0.634966 | Data_Structure_7201 | C | [
"search_insert",
"insertion_sort_with_binary_search"
] | 2 | [
[
"insertion_sort_with_binary_search",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bcc303933ade29dc454b843643e3d85d280f0d7f | 8fb53e15a18272a806a79c56fdc83ce26b12b431 | |||
v1.0 | complete | Data_Structure | Data_Structure_7335_C | import time
def count_ones_recur(n):
if not n:
return 0
return 1 + count_ones_recur(n & (n - 1))
def count_ones_iter(n):
count = 0
while n:
n &= (n - 1)
count += 1
return count
def compare_performance(test_cases):
""" Compare the performance of count_ones_recur... | import time
def count_ones_recur(n):
if not n:
return 0
return 1 + count_ones_recur(n & (n - 1))
def count_ones_iter(n):
count = 0
while n:
n &= (n - 1)
count += 1
return count
def compare_performance(test_cases):
total_time_recur = 0.0
total_time_iter = 0.... | from solution import compare_performance, count_ones_recur, count_ones_iter
def test_compare_performance_basic():
test_cases = [3, 14, 31, 0, 1023]
faster_func, avg_time = compare_performance(test_cases)
assert faster_func in ['count_ones_recur', 'count_ones_iter']
assert avg_time > 0
def test_compare... | [
{
"docstring": null,
"function_declaration": "def count_ones_recur(n):",
"function_name": "count_ones_recur",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def count_ones_iter(n):",
"function_name": "count_ones_iter",
"parameter_list": "(n)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\n\ndef count_ones_recur(n):\n if not n:\n return 0\n return 1 + count_ones_recur(n & (n-1))\n \ndef count_ones_iter(n):\n c... | trial_gpt4o_2 | {
"original_instruction": "You are provided with two functions implementing an algorithm to count the number of '1' bits in the binary representation of an unsigned integer. Your task is to implement another function that compares the performance (execution time) of these two functions for a series of test cases and ... | 0.529662 | Data_Structure_7335 | C | [
"count_ones_recur",
"count_ones_iter",
"compare_performance"
] | 3 | [
[
"compare_performance",
"count_ones_iter"
],
[
"compare_performance",
"count_ones_recur"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7551addea399d1b6920d543b6390fd69eede23da | 3e0e67559eb18fc8db53bcfdb265f97f977513ff | |||
v1.0 | complete | Data_Structure | Data_Structure_6843_C | def prime_check(n):
""" Returns True if n is a prime number, otherwise 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 False
i ... | def prime_check(n):
""" Returns True if n is a prime number, otherwise 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 False
i ... | from solution import generate_prime_candidates, key_exchange, prime_check
def test_prime_check():
assert prime_check(2) == True
assert prime_check(3) == True
assert prime_check(4) == False
assert prime_check(29) == True
assert prime_check(30) == False
def test_generate_prime_candidates():
asse... | [
{
"docstring": "Returns True if n is a prime number, otherwise False ",
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": "Generates a list of prime numbers within a given range [start, end).",
"function_declaration":... | [
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 prime_check(num):\n \"\"\"\n Given a number, return True if it's prime, else False.\n \"\"\"\n if num <= 1:\n return False\n if num ... | trial_gpt4o_1 | {
"original_instruction": "### Diffie-Hellman Key Exchange Implementation\n\nIn this assessment, you will implement the Diffie-Hellman Key Exchange algorithm to demonstrate your understanding of both cryptographic principles and Python programming.\n\n### Task\n1. Implement a function `generate_prime_candidates(start... | 0.655439 | Data_Structure_6843 | C | [
"prime_check",
"generate_prime_candidates",
"key_exchange"
] | 3 | [
[
"generate_prime_candidates",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 16926873824eb9803f4d17e18a99a986b717e35f | 6f6968229317cba07f1b770f0fb96bd0d48d635b | |||
v1.0 | complete | Data_Structure | Data_Structure_7288_C | def nearest_neighbor(x: tuple, tSet: dict) -> str:
""" Finds the nearest neighbor of the query vector 'x' in the training set 'tSet'
and returns its associated class label.
>>> tSet = {
(1.0, 2.0): "ClassA",
(2.0, 3.0): "ClassB",
(3.0, 4.0): "ClassA"
}
>>> query_vector =... | import math
def distance(v1, v2):
"""
Computes the Euclidean distance between two vectors v1 and v2.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def nearest_neighbor(x: tuple, tSet: dict) -> str:
"""
Finds the nearest neighbor of the query vector 'x' in the training set 'tS... | from solution import nearest_neighbor
def test_nearest_neighbor_single_point():
tSet = {(1.0, 1.0): "ClassA"}
query_vector = (1.0, 1.0)
assert nearest_neighbor(query_vector, tSet) == "ClassA"
def test_nearest_neighbor_multiple_points():
tSet = {
(1.0, 2.0): "ClassA",
(2.0, 3.0): "Class... | [] | [
0,
0,
0,
0,
0,
1,
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": "import math\n\ndef distance(a: tuple, b: tuple) -> float:\n \"\"\"\n Compute the Euclidean distance between two points a and b.\n \"\"\"\n return ... | trial_gpt4o_5 | {
"original_instruction": "### Question:\nYou are provided with a training dataset represented as a dictionary where keys are tuples representing data points, and their corresponding values are the labels associated with them. Implement the `nearest_neighbor` function that takes a query vector and the training datase... | 0.625916 | Data_Structure_7288 | C | [
"distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d127b0b7a222c742600e29a4abec05bad7517558 | 08354e5d961f4ee7c71be2472cde469b46f958cc | |||
v1.0 | complete | Data_Structure | Data_Structure_7218_C | def merge_btrees(btree1: BTree, btree2: BTree) -> BTree:
""" Merge two B-Trees of the same degree into one B-Tree, maintaining the B-Tree properties.
Args:
btree1 (BTree): First B-Tree object.
btree2 (BTree): Second B-Tree object.
Returns:
BTree: A new B-Tree object containing all elem... | class BTreeNode:
def __init__(self, t, leaf=False):
self.t = t # Minimum degree (defines the range for number of keys)
self.leaf = leaf # True if leaf node
self.keys = [] # List of keys in the node
self.children = [] # List of child BTreeNode objects
class BTree:
def __init_... | from solution import BTree, merge_btrees
def test_merge_with_empty_trees():
btree1 = BTree(2)
btree2 = BTree(2)
merged_btree = merge_btrees(btree1, btree2)
assert merged_btree.traverse() == []
def test_merge_with_one_empty_tree():
btree1 = BTree(2)
btree1.insert(10)
btree2 = BTree(2)
m... | [] | [
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 BTreeNode:\n def __init__(self, leaf=False):\n self.leaf = leaf\n self.keys = []\n self.children = []\n\nclass BTree:\n def _... | trial_gpt4o_1 | {
"original_instruction": "### Question\n\nYou are given a B-Tree data structure implementation that supports insertion, deletion, searching, and traversal. Your task is to implement a function that merges two B-Trees of the same degree into one B-Tree, maintaining the B-Tree properties. The merged B-Tree should cont... | 0.433354 | Data_Structure_7218 | C | [
"merge_sorted_lists",
"merge_btrees"
] | 2 | [
[
"merge_btrees",
"merge_sorted_lists"
]
] | 1 | [] | false | [
"BTreeNode",
"BTree"
] | true | pytest | true | [] | true | 0a0abb1f3081f0ac4befdad7d1d8de6752ce62cb | d4824809f547f4b78d484f289ea0a44395bfdc44 | |||
v1.0 | complete | Data_Structure | Data_Structure_7023_C | def extended_gcd(a: int, b: int) -> (int, int, int):
"""
Extended Euclidean Algorithm to find integers s and t such that:
a * s + b * t = gcd(a, b)
Args:
a (int): First integer
b (int): Second integer
Returns:
(int, int, int): A tuple containing the coefficients s, t and gcd(a,... | def extended_gcd(a: int, b: int) -> (int, int, int):
"""
Extended Euclidean Algorithm to find integers s and t such that:
a * s + b * t = gcd(a, b)
"""
if b == 0:
return (1, 0, a)
else:
x1, y1, g = extended_gcd(b, a % b)
return (y1, x1 - (a // b) * y1, g)
def modular_inv... | from solution import extended_gcd, modular_inverse
def test_extended_gcd():
assert extended_gcd(30, 20) == (1, -1, 10)
assert extended_gcd(10, 15) == (-1, 1, 5)
assert extended_gcd(101, 10) == (1, -10, 1)
assert extended_gcd(0, 5) == (0, 1, 5)
assert extended_gcd(5, 0) == (1, 0, 5)
def test_modula... | [
{
"docstring": "Extended Euclidean Algorithm to find integers s and t such that:\na * s + b * t = gcd(a, b)",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Find the modular inverse of a under modulus b, assum... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def extended_gcd(a, b):\n \"\"\"\n Computes the Greatest Common Divisor of a and b, along with\n coefficients for the equation a * s + b * t = gcd(a,... | trial_gpt4o_2 | {
"original_instruction": "You are given two integers `a` and `b`. Your task is to implement the extended Euclidean algorithm to find integers `s` and `t` such that `a * s + b * t = GCD(a, b)`, and also to find the modular inverse of `a` under modulus `b` when they are co-prime.\n\n### Function Signature\n```python\n... | 0.658083 | Data_Structure_7023 | C | [
"extended_gcd",
"modular_inverse"
] | 2 | [
[
"modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9e7d41099775371e26347f426a01e45817611540 | a256f840c13dcdf2cfb1176faaa55d113d951918 | |||
v1.0 | complete | Data_Structure | Data_Structure_7057_C | def smart_heap_sort(arr: list[int], simulation: bool=False) -> list[int]:
""" Sorts the list in ascending order using either max_heap_sort or min_heap_sort
based on the median and mean of the array.
Use `max_heap_sort` if the median of the array is greater than its mean.
Use `min_heap_sort` otherw... | import statistics
def max_heap_sort(arr: list[int]) -> list[int]:
"""
Sorts a list in ascending order using heap sort with a max-heap.
Placeholder function.
"""
import heapq
# Convert array to a max heap by negating all values and using heapq which is a min-heap.
neg_arr = [-a for a in arr]... | from solution import smart_heap_sort, max_heap_sort, min_heap_sort
def test_smart_heap_sort_empty():
assert smart_heap_sort([]) == []
def test_smart_heap_sort_same_elements():
assert smart_heap_sort([5, 5, 5, 5]) == [5, 5, 5, 5]
def test_smart_heap_sort_max_heap_selection():
assert smart_heap_sort([4, 1,... | [
{
"docstring": "Sorts a list in ascending order using heap sort with a max-heap.\nPlaceholder function.",
"function_declaration": "def max_heap_sort(arr):",
"function_name": "max_heap_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts a list in ascending order using heap sort with a m... | [
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 heapq\nfrom statistics import median, mean\n\ndef max_heap_sort(arr):\n # Sort using a max heap\n arr = [-x for x in arr]\n heapq.heapify(arr)... | trial_gpt4o_1 | {
"original_instruction": "You are provided with functions `max_heap_sort` and `min_heap_sort` that sort an array in ascending order using heap sort with a max-heap and min-heap, respectively.\n\nYou need to implement a function `smart_heap_sort` that dynamically selects between `max_heap_sort` and `min_heap_sort` ba... | 0.652789 | Data_Structure_7057 | C | [
"max_heap_sort",
"min_heap_sort",
"smart_heap_sort"
] | 3 | [
[
"smart_heap_sort",
"max_heap_sort"
],
[
"smart_heap_sort",
"min_heap_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 192ad917aecc2cddb5c56c95b8288c907f4203f7 | 6b781a1bfdcfcbc14135beb4d8d1b110feefcd60 | |||
v1.0 | complete | Data_Structure | Data_Structure_6994_C | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
""" Check if t is a subtree of s.
>>> s = TreeNode(3)
>>> s.left = TreeNode(4)
>>> s.right = TreeNode(5)
>>> s.left.left = TreeNode(1)... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
if not t:
return True # An empty tree t is always a subtree
if not s:
return False # If s is empty, t cannot be a subtree of s
... | from solution import TreeNode, is_subtree
def test_is_subtree_true():
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.left.right = TreeNode(2)
t = TreeNode(4)
t.left = TreeNode(1)
t.right = TreeNode(2)
assert is_subtree(s, t) == True
... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef is_same_tree(s: TreeNode, t: Tre... | trial_gpt4o_1 | {
"original_instruction": "### Question Description\nYou are given two binary trees, s and t, represented as instances of a TreeNode class. Your task is to implement a function `is_subtree(s: TreeNode, t: TreeNode) -> bool` that checks if t is a subtree of s. A subtree of a tree t is defined as a tree consisting of a... | 0.573064 | Data_Structure_6994 | C | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 0e2789642f707f52ccb219daeb985c1da64b9e5d | 04614b15c64de8d3852724e99de90fb43400fcf2 | |||
v1.0 | complete | Data_Structure | Data_Structure_6720_C | import math
from typing import List
def is_prime(num: int) -> bool:
""" Check if a number is a prime.
>>> is_prime(2) True
>>> is_prime(4) False
"""
pass
def find_order(a: int, n: int) -> int:
""" Find the order of a number 'a' modulo 'n'.
>>> find_order(2, 5) 4
>>> find_order(2, 16) -... | import math
from typing import List
def is_prime(num: int) -> bool:
"""
Check if a number is a prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (... | from solution import is_prime, find_order, euler_totient, find_primitive_root, diffie_hellman_key_exchange
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(29) == True
assert is_prime(30) == False
def test_find_order():
asse... | [
{
"docstring": "Check if a number is a prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Find the order of a number 'a' modulo 'n'.",
"function_declaration": "def find_order(a, n):",
"function_name": "find... | [
0,
0,
0,
1,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import List\n\ndef is_prime(num: int) -> bool:\n \"\"\" Check if the input number is a prime number. \"\"\"\n if num <= 1:\n ... | trial_gpt4o_8 | {
"original_instruction": "Implement a Secure Communication Setup Using Diffie-Hellman Key Exchange\n\nAs a cybersecurity student, you are tasked with implementing a secure communication setup using the Diffie-Hellman key exchange protocol. This will involve several steps where you incorporate checks and additional f... | 0.628523 | Data_Structure_6720 | C | [
"is_prime",
"find_order",
"euler_totient",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 5 | [
[
"diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"diffie_hellman_key_exchange",
"is_prime"
],
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"is_prime"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 89755ac914f06e4f9157a5778869c45ae6d7e34d | e1179a8527d161095a4415b188c8a4410851ac30 | |||
v1.0 | complete | Data_Structure | Data_Structure_6702_C | def binary_insertion_sort(arr: list) -> list:
"""
Sorts the input list using an optimized insertion sort algorithm employing
binary search to find insertion points.
Args:
- arr (list): A list of comparable elements to be sorted.
Returns:
- list: The sorted list in non-decreasing o... | def binary_search(arr, val, start, end):
"""
Helper function to perform binary search on the sorted part of the array.
"""
if start == end:
if arr[start] > val:
return start
else:
return start + 1
elif start > end:
return start
mid = (start + end)... | from solution import binary_insertion_sort
def test_binary_insertion_sort_with_integers():
assert binary_insertion_sort([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13]
def test_binary_insertion_sort_with_strings():
assert binary_insertion_sort(['banana', 'apple', 'cherry', 'date']) == ['apple', 'banana', 'cherry', ... | [
{
"docstring": "Helper function to perform binary search on the sorted part of the array.",
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "Sorts the input list using an optimi... | [
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 to perform binary search to find the index at which val should be inserted.\n \"\... | trial_gpt4o_1 | {
"original_instruction": "### Question: Refactored Insertion Sort with Binary Insertion\n\nYou are asked to optimize the insertion sort algorithm by reducing the number of comparisons while finding the position to insert the current element. Implement this by using binary search to determine the correct insertion po... | 0.593388 | Data_Structure_6702 | C | [
"binary_search",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 97de1452de6dbfe9c06bf16d85b7e72695722b04 | b5d79a7200b57cb10bb216351ddf78e11c6f8111 | |||
v1.0 | complete | Data_Structure | Data_Structure_7522_C | def augmented_insertion_sort(arr: List[int]) -> List[int]:
"""
Sorts an array using an augmented insertion sort that uses binary search to find
the correct insertion position.
>>> augmented_insertion_sort([64, 34, 25, 12, 22, 11, 90])
[11, 12, 22, 25, 34, 64, 90]
>>> augmented_insertion_sor... | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
"""
left, right = 0, len(array)
while left < right:
... | from solution import augmented_insertion_sort
def test_augmented_insertion_sort_empty():
assert augmented_insertion_sort([]) == []
def test_augmented_insertion_sort_single_element():
assert augmented_insertion_sort([1]) == [1]
def test_augmented_insertion_sort_sorted_array():
assert augmented_insertion_s... | [
{
"docstring": "Given a sorted array and a target value, return the index if the target is found.\nIf not, return the index where it would be if it were inserted in order.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n Helper function to find the index to insert val in the sorte... | trial_gpt4o_2 | {
"original_instruction": "Implement a function that performs an \"augmented insertion sort\" on an array but uses binary search (`search_insert`) to find the correct insertion position for each element.\n\n#### Description\nYou are provided with a function `search_insert(array, val)` that, given a sorted array and a... | 0.669719 | Data_Structure_7522 | C | [
"search_insert",
"augmented_insertion_sort"
] | 2 | [
[
"augmented_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0acb63cb2ebf9d892a1791a0388c365341b76312 | b17902398c461ea03031e265b923fa88e909bf6a | |||
v1.0 | complete | Data_Structure | Data_Structure_7494_C | from typing import List
def is_prime_list(nums: List[int]) -> List[bool]:
"""Given a list of integers, return a list of boolean values indicating if each integer is a prime number.
Args:
nums (List[int]): List of integers to check for primality.
Returns:
List[bool]: List of boolean values... | from typing import List
import math
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
... | from solution import is_prime_list
def test_prime_list_empty():
assert is_prime_list([]) == []
def test_prime_list_single_elements():
assert is_prime_list([1]) == [False]
assert is_prime_list([2]) == [True]
assert is_prime_list([3]) == [True]
assert is_prime_list([4]) == [False]
def test_prime_li... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def is_prime_list(nums):",
"function_name": "is_prime_list",
"parameter_list": "(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 math import isqrt\nfrom typing import List\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n == 2:\n return True\n ... | trial_gpt4o_1 | {
"original_instruction": "### Problem: Prime Number Verifier\n\n#### Context:\nYou are working on a piece of software that requires checking the primality of multiple numbers efficiently. Prime numbers have significant applications in fields like cryptography, number theory, and hashing algorithms. Your task is to i... | 0.830897 | Data_Structure_7494 | C | [
"is_prime",
"is_prime_list"
] | 2 | [
[
"is_prime_list",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7d224ce3b22145361ad259b730b82b582b5b5629 | 90d9c45a219b523ce7a5ac25c578955d50334243 | |||
v1.0 | complete | Data_Structure | Data_Structure_7199_C | from typing import List
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def print_inorder(root, result=None):
if root is None:
return []
if result is None:
result = []
print_inorder(root.left, re... | from typing import List
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(pre, pre_start, post, post_start, size):
if size == 0:
return None
root = TreeNode(pre[pre_start])
if size == 1:
... | from solution import construct_tree
def test_construct_tree_example():
pre = [1, 2, 4, 5, 3, 6, 7]
post = [4, 5, 2, 6, 7, 3, 1]
size = 7
assert construct_tree(pre, post, size) == [4, 2, 5, 1, 6, 3, 7]
def test_construct_tree_single_node():
pre = [1]
post = [1]
size = 1
assert construct... | [] | [
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": "class TreeNode:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef cons... | trial_gpt4o_7 | {
"original_instruction": "### Full Binary Tree Reconstruction \n\nGiven two arrays representing the preorder and postorder traversal of a full binary tree, your task is to construct the full binary tree and print the inorder traversal of that tree.\n\n#### Instructions:\n1. You should implement a function `construct... | 0.533609 | Data_Structure_7199 | C | [
"build_tree",
"print_inorder",
"construct_tree"
] | 3 | [
[
"construct_tree",
"build_tree"
],
[
"construct_tree",
"print_inorder"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 4b40b74f1705c529963c3d7005f312a60b6a225f | 6731e3aa1cfa355268e8ab885b72beb1e37099dc | |||
v1.0 | complete | Data_Structure | Data_Structure_6760_C | def is_prime(n: int) -> bool:
""" Determine if n is a prime number.
>>> is_prime(2)
True
>>> is_prime(4)
False
"""
pass
def order(a: int, n: int) -> int:
""" Compute the order of a modulo n.
>>> order(2, 7)
3
>>> order(3, 7)
6
"""
pass
def euler_totient(n: int) ... | def is_prime(n):
"""
Determines if n is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
retu... | from solution import is_prime, order, euler_totient, primitive_roots, diffie_hellman
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
def test_order():
assert order(2, 7) == 3
ass... | [
{
"docstring": "Determines if n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Computes the order of a modulo n.",
"function_declaration": "def order(a, n):",
"function_name": "order",
"para... | [
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 functools import reduce\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Determine if n is a prime number.\n \"\"\"\n if n <= 1:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Context:\nIn cryptographic protocols, secure key exchange over a public network is essential. The Diffie-Hellman key exchange method enables two parties to securely share a common secret key even if they don't know each other. This shared secret can then be used to encrypt subsequent co... | 0.563565 | Data_Structure_6760 | C | [
"is_prime",
"order",
"euler_totient",
"primitive_roots",
"diffie_hellman"
] | 5 | [
[
"diffie_hellman",
"is_prime"
],
[
"diffie_hellman",
"primitive_roots"
],
[
"order",
"is_prime"
],
[
"primitive_roots",
"euler_totient"
],
[
"primitive_roots",
"is_prime"
],
[
"primitive_roots",
"order"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | d5b8134a10e2acef9eb0a538bcdea142a8e2145d | 7962237a6098d56622dd9de5b02b49bd66a3399d | |||
v1.0 | complete | Data_Structure | Data_Structure_6570_C | from typing import List, Tuple
def dfs(node: int, graph: List[List[int]], reachable: List[List[bool]], visited: List[bool], start: int):
"""
Perform DFS to mark all reachable nodes from the starting node.
"""
pass
def transitive_closure(num_nodes: int, edges: List[Tuple[int, int]]) -> List[List[bool]]... | from typing import List, Tuple
def dfs(node: int, graph: List[List[int]], reachable: List[List[bool]], visited: List[bool], start: int):
"""
Perform DFS to mark all reachable nodes from the starting node.
"""
reachable[start][node] = True
visited[node] = True
for neighbor in graph[node]:
... | from solution import transitive_closure
def test_transitive_closure():
num_nodes = 4
edges = [(0, 1), (1, 2), (2, 3)]
expected_result = [
[True, True, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, False, True],
]
assert transitive... | [
{
"docstring": "Perform DFS to mark all reachable nodes from the starting node.",
"function_declaration": "def dfs(node, graph, reachable, visited, start):",
"function_name": "dfs",
"parameter_list": "(node, graph, reachable, visited, start)"
},
{
"docstring": "Computes the transitive closur... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef transitive_closure(num_nodes: int, edges: List[Tuple[int, int]]) -> List[List[bool]]:\n # Initialize the reachability... | trial_gpt4o_2 | {
"original_instruction": "You are required to implement a function that computes the transitive closure of a directed graph using Depth-First Search (DFS). The transitive closure of a graph is a reachability matrix where each entry (i, j) is True if there is a path from node i to node j (including itself), and False... | 0.612346 | Data_Structure_6570 | C | [
"dfs",
"transitive_closure"
] | 2 | [
[
"transitive_closure",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 58ffaf57c2829da1b64813abd60b00ec2a9f1ab5 | 5f8d0964e45f999744bbb8911372ef7c5ad18566 | |||
v1.0 | complete | Data_Structure | Data_Structure_6490_C | def radix_sort(arr: list, simulation: bool = False) -> list:
"""
Implement the Radix Sort algorithm to sort a list of non-negative integers in ascending order
using the least significant digit (LSD) approach. If simulation is True, print the state
of the list after each significant digit sorting step... | def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[(index) % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] // exp
output[count[... | from solution import radix_sort
def test_radix_sort_basic():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_single_element():
assert radix_sort([5]) == [5]
def test_radix_sort_empty():
assert radix_sort([]) == []
def test_radix_sort_with_zer... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort",
"parameter_list":... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp, simulation):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # Counting occurrences of digits\n for i in r... | trial_gpt4o_1 | {
"original_instruction": "### Radix Sort Function Implementation\n\n#### Context\nYou are given a list of non-negative integers, and your task is to implement the Radix Sort algorithm to sort this list in ascending order. The algorithm should use the least significant digit (LSD) approach.\n\n#### Function Signature... | 0.618337 | Data_Structure_6490 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4ab731a7f0207d10fb1b9812eb446abd2cb82862 | 9662f45528bc86c3bb54bed75078361f2deb83bb | |||
v1.0 | complete | Data_Structure | Data_Structure_7464_C | from typing import List
def matrix_chain_multiplication(arr: List[int]) -> None:
""" Find the minimum cost and optimal order to multiply a sequence of matrices.
Args:
arr (List[int]): List of dimensions for matrices such that matrix Ai has dimension arr[i-1] x arr[i].
Outputs:
Prints the minimum n... | from typing import List
def matrix_chain_multiplication(arr: List[int]) -> None:
n = len(arr) - 1 # Number of matrices
m = [[0] * n for _ in range(n)]
s = [[0] * n for _ in range(n)]
for l in range(2, n + 1):
for i in range(0, n - l + 1):
j = i + l - 1
m[i][j] = fl... | import pytest
from solution import matrix_chain_multiplication
def test_matrix_chain_multiplication_example():
arr = [30, 35, 15, 5, 10, 20, 25]
matrix_chain_multiplication(arr) # Expected to print 15125 and (A1(A2(A3(A4A5))A6))
def test_matrix_chain_multiplication_minimal_case():
arr = [10, 20]
matr... | [
{
"docstring": null,
"function_declaration": "def matrix_chain_multiplication(arr):",
"function_name": "matrix_chain_multiplication",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def _get_optimal_parenthesization(s, i, j):",
"function_name": "_get_optima... | [
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 matrix_chain_multiplication(arr):\n n = len(arr)\n # Initialize the matrix for storing minimum scalar multiplications required\n m = [[0 for _ in... | trial_gpt4o_1 | {
"original_instruction": "You are given a sequence of matrices and you are required to find the most efficient way to multiply these matrices together. Your task is to implement the matrix chain multiplication algorithm using dynamic programming.\n\n### Input\n* An array of integers `arr` of size `n`, where `arr[i]`... | 0.529693 | Data_Structure_7464 | C | [
"matrix_chain_multiplication",
"_get_optimal_parenthesization"
] | 2 | [
[
"matrix_chain_multiplication",
"_get_optimal_parenthesization"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a406a4f9604ed5e34a825e967d93132976010e9c | 400df7e3c7a4554ba01ee686cc7cae35dc016df1 | |||
v1.0 | complete | Data_Structure | Data_Structure_6746_C | def enhanced_gcd(a: int, b: int) -> int:
"""
Compute the greatest common divisor of integers a and b using the Euclidean Algorithm.
Raises a ValueError for invalid inputs.
Parameters:
a (int): First integer
b (int): Second integer
Returns:
int: GCD of a and b
>>> enhanced_gcd(... | def enhanced_gcd(a, b):
"""
Compute the greatest common divisor of integers a and b using the Euclidean Algorithm.
Raises a ValueError for invalid inputs.
Parameters:
a (int): First integer
b (int): Second integer
Returns:
int: GCD of a and b
"""
if not isinstance(a, in... | from solution import enhanced_gcd, enhanced_lcm
import pytest
def test_enhanced_gcd_positive():
assert enhanced_gcd(54, 24) == 6
def test_enhanced_gcd_negative():
assert enhanced_gcd(-54, 24) == 6
assert enhanced_gcd(54, -24) == 6
assert enhanced_gcd(-54, -24) == 6
def test_enhanced_gcd_prime_numbers... | [
{
"docstring": "Compute the greatest common divisor of integers a and b using the Euclidean Algorithm.\nRaises a ValueError for invalid inputs.\n\nParameters:\na (int): First integer\nb (int): Second integer\n\nReturns:\nint: GCD of a and b",
"function_declaration": "def enhanced_gcd(a, b):",
"function_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_gcd(a, b):\n \"\"\"\n Computes the greatest common divisor of integers `a` and `b` using the Euclidean Algorithm.\n Raises a ValueError ... | trial_gpt4o_2 | {
"original_instruction": "Enhanced GCD Function with Improved Error Handling\n\nAs a programmer, you are asked to implement an enhanced version of the `gcd` and `lcm` functions that not only compute the greatest common divisor and least common multiple of two integers but also handle various edge cases and error sce... | 0.73587 | Data_Structure_6746 | C | [
"enhanced_gcd",
"enhanced_lcm"
] | 2 | [
[
"enhanced_lcm",
"enhanced_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8d3cc034ceadb46db7bdecc4a22bbc2497fc4882 | 10e9b42bb7b6c5e779c92136541af0f06811c3da | |||
v1.0 | complete | Data_Structure | Data_Structure_6520_C | import math
from typing import List
def cosine_similarity(u: List[float], v: List[float]) -> float:
"""
Computes the cosine similarity between two vectors u and v.
"""
# Implement the function cosine_similarity here
pass
def cosine_similarity_matrix(vectors: List[List[float]]) -> List[List[float]]... | import math
def cosine_similarity(u, v):
"""
Computes the cosine similarity between two vectors u and v.
"""
dot_product = sum(ui * vi for ui, vi in zip(u, v))
magnitude_u = math.sqrt(sum(ui**2 for ui in u))
magnitude_v = math.sqrt(sum(vi**2 for vi in v))
if magnitude_u == 0 or magnitude_v ... | def test_cosine_similarity():
vector1 = [1, 0, 0]
vector2 = [0, 1, 0]
vector3 = [1, 1, 0]
assert math.isclose(cosine_similarity(vector1, vector1), 1.0, rel_tol=1e-4)
assert math.isclose(cosine_similarity(vector1, vector2), 0.0, rel_tol=1e-4)
assert math.isclose(cosine_similarity(vector1, ve... | [
{
"docstring": "Computes the cosine similarity between two vectors u and v.",
"function_declaration": "def cosine_similarity(u, v):",
"function_name": "cosine_similarity",
"parameter_list": "(u, v)"
},
{
"docstring": "Computes the cosine similarity matrix for given list of vectors.",
"fu... | [
0,
0,
0,
1,
0,
1,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef cosine_similarity(vec1, vec2):\n \"\"\"\n Calculate the cosine similarity between two vectors.\n \"\"\"\n dot_product = sum(a *... | trial_gpt4o_9 | {
"original_instruction": "## Problem:\nYou are given a list of `N` vectors, each consisting of `M` elements (comparable to a matrix of size `N x M`). Your task is to compute the cosine similarity between every pair of vectors and store the results in an `N x N` matrix. Each element (i, j) in this matrix should repre... | 0.591542 | Data_Structure_6520 | C | [
"cosine_similarity",
"cosine_similarity_matrix"
] | 2 | [
[
"cosine_similarity_matrix",
"cosine_similarity"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 5f29cc63ea505508a2f0114dd32acf5bea375c4b | 63447e39ee6c9ebea0afc6bd1fd481fe9e599672 | |||
v1.0 | complete | Data_Structure | Data_Structure_6135_C | class Interval:
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return f"Interval({self.start}, {self.end})"
def __eq__(self, other):
return self.start == other.start and self.end == other.end
def fuse_intervals(intervals):
""" Mer... | class Interval:
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return f"Interval({self.start}, {self.end})"
def __eq__(self, other):
return self.start == other.start and self.end == other.end
def fuse_intervals(intervals):
if not ... | from solution import Interval, fuse_intervals, find_gaps
def test_fuse_intervals_no_intervals():
assert fuse_intervals([]) == []
def test_fuse_intervals_touching_intervals():
intervals = [Interval(1, 5), Interval(5, 10)]
expected = [Interval(1, 10)]
assert fuse_intervals(intervals) == expected
def te... | [] | [
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 Interval:\n def __init__(self, start, end):\n assert start <= end, \"Start should be less or equal to end\"\n self.start = start\n ... | trial_gpt4o_2 | {
"original_instruction": "You are given a class `Interval` with methods to manage intervals of real numbers. The class can determine if a number is included within an interval, merge overlapping intervals, and more. Your task is to enhance this class to include additional functionalities that handle more sophisticat... | 0.660624 | Data_Structure_6135 | C | [
"fuse_intervals",
"find_gaps"
] | 2 | [
[
"find_gaps",
"fuse_intervals"
]
] | 1 | [] | false | [
"Interval"
] | true | pytest | true | [] | true | 00a0014d7fc7879757eb0d97f77a688c3512f34c | e5ebbd9a5d211ca6a9c736c5293dd7173b723859 | |||
v1.0 | complete | Data_Structure | Data_Structure_7937_C | def merge_sort_in_place(arr: list) -> list:
"""
Sorts an array in place using the Merge Sort algorithm.
Parameters:
arr (list): A list of integers to be sorted.
Returns:
list: The sorted list.
Examples:
>>> merge_sort_in_place([38, 27, 43, 3, 9, 82, 10])
[3, 9, 10, 27, 38,... | def merge_sort_in_place(arr):
"""
Sorts the array in place using merge sort algorithm.
Parameters:
arr (list): List of integers to be sorted.
Returns:
list: Sorted list.
"""
if len(arr) > 1:
merge_sort_helper(arr, 0, len(arr) - 1)
return arr
def merge_sort_helper(arr,... | from solution import merge_sort_in_place
def test_merge_sort_empty():
arr = []
sorted_arr = merge_sort_in_place(arr)
assert sorted_arr == []
def test_merge_sort_single_element():
arr = [1]
sorted_arr = merge_sort_in_place(arr)
assert sorted_arr == [1]
def test_merge_sort_already_sorted():
... | [
{
"docstring": "Sorts the array in place using merge sort algorithm.\n\nParameters:\narr (list): List of integers to be sorted.\n\nReturns:\nlist: Sorted list.",
"function_declaration": "def merge_sort_in_place(arr):",
"function_name": "merge_sort_in_place",
"parameter_list": "(arr)"
},
{
"d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort_in_place(arr):\n def merge(start, mid, end):\n left = arr[start:mid+1]\n right = arr[mid+1:end+1]\n k = start\n ... | trial_gpt4o_2 | {
"original_instruction": "### Context\nMerge Sort is a fundamental sorting algorithm commonly used in computer science due to its guarantees in time complexity and sorting stability. Your task is to demonstrate your understanding of this algorithm by implementing it with particular attention to efficient merging and... | 0.702998 | Data_Structure_7937 | C | [
"merge_sort_in_place",
"merge_sort_helper",
"merge"
] | 3 | [
[
"merge_sort_helper",
"merge"
],
[
"merge_sort_in_place",
"merge_sort_helper"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 76c045624efa98a25107ef6e7faee6036c772f9d | 50693e717c6e8dec42e2f2070a5ad70cde5c751a | |||
v1.0 | complete | Data_Structure | Data_Structure_8062_C | def generate_primes(M: int) -> list:
""" Generate a list of prime numbers up to a given number `M` (inclusive).
>>> generate_primes(10) # Returns: [2, 3, 5, 7]
>>> generate_primes(20) # Returns: [2, 3, 5, 7, 11, 13, 17, 19]
>>> generate_primes(1) # Returns: []
>>> generate_primes(0) # Returns: []
... | def is_prime(n):
"""
Check if a number is prime.
Returns True if n is a prime number, otherwise 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) == ... | from solution import generate_primes
def test_generate_primes_zero():
assert generate_primes(0) == []
def test_generate_primes_one():
assert generate_primes(1) == []
def test_generate_primes_two():
assert generate_primes(2) == [2]
def test_generate_primes_ten():
assert generate_primes(10) == [2, 3, ... | [
{
"docstring": "Check if a number is prime.\nReturns True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate a list of all prime numbers up to a given number M (inclusive).",
... | [
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 is prime.\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n ... | trial_gpt4o_0 | {
"original_instruction": "### Prime Number Identification and List Generation\n\nGiven an integer `M`, write a function `generate_primes(M)` that generates a list of prime numbers up to a given number `M` (inclusive).\n\n### Function Signature\n```python\ndef generate_primes(M: int) -> list:\n pass\n```\n\n### In... | 0.721211 | Data_Structure_8062 | C | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d2872ae1b6ab0a1b45442e0a89612ad72df710f2 | 3cbab10cbb60ebc3d15ec777d00f6bb0b1fa42b1 | |||
v1.0 | complete | Data_Structure | Data_Structure_3804_C | def powerset(iterable):
"""Helper function to calculate the powerset."""
from itertools import chain, combinations
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
def optimal_set_cover(universe, subsets, costs):
"""
Find the exact minimal cost set c... | from itertools import chain, combinations
def powerset(iterable):
"""Helper function to calculate the powerset."""
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
def optimal_set_cover(universe, subsets, costs):
min_cost = float('inf')
best_cover = None... | from solution import optimal_set_cover, greedy_set_cover
def test_optimal_set_cover_basic():
universe = {1, 2, 3, 4, 5}
subsets = {'S1': {4, 1, 3}, 'S2': {2, 5}, 'S3': {1, 4, 3, 2}}
costs = {'S1': 5, 'S2': 10, 'S3': 3}
assert set(optimal_set_cover(universe, subsets, costs)) == {'S3', 'S2'}
def test_gr... | [
{
"docstring": "Helper function to calculate the powerset.",
"function_declaration": "def powerset(iterable):",
"function_name": "powerset",
"parameter_list": "(iterable)"
},
{
"docstring": null,
"function_declaration": "def optimal_set_cover(universe, subsets, costs):",
"function_na... | [
0,
0,
0,
1,
0,
0,
0,
0,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import chain, combinations\n\ndef powerset(iterable):\n \"\"\"Helper function to calculate the powerset.\"\"\"\n s = list(iterable)\n ... | trial_gpt4o_9 | {
"original_instruction": "You are assigned the task of developing a software module that implements two different algorithms for solving the Set Cover problem. Your solutions should include:\n1. An exact algorithm that finds the minimal cost set cover using exhaustive search.\n2. An approximate algorithm that finds ... | 0.582499 | Data_Structure_3804 | C | [
"powerset",
"optimal_set_cover",
"greedy_set_cover"
] | 3 | [
[
"optimal_set_cover",
"powerset"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2e4bc07539c3387efae42f43841a1563837032fa | 6fc1ced9c8617a954239f209d7e61f7cbd1b761d | |||
v1.0 | complete | Data_Structure | Data_Structure_6661_C | def multiply(matA, matB):
"""
Multiplies two 2x2 matrices.
Parameters:
matA (list): A 2D list representing the first matrix of size 2x2.
matB (list): A 2D list representing the second matrix of size 2x2.
Returns:
list: The resulting 2x2 matrix after multiplication.
"""
pass... | def multiply(matA, matB):
"""
Multiplies two 2x2 matrices.
"""
return [
[
matA[0][0] * matB[0][0] + matA[0][1] * matB[1][0],
matA[0][0] * matB[0][1] + matA[0][1] * matB[1][1]
],
[
matA[1][0] * matB[0][0] + matA[1][1] * matB[1][0],
m... | def test_multiply():
matA = [[1, 2], [3, 4]]
matB = [[2, 0], [1, 2]]
expected = [[4, 4], [10, 8]]
assert multiply(matA, matB) == expected
def test_identity():
expected = [[1, 0], [0, 1]]
assert identity(2) == expected
def test_matrix_exponentiation():
mat = [[2, 0], [0, 2]]
power = 3
... | [
{
"docstring": "Multiplies two 2x2 matrices.",
"function_declaration": "def multiply(matA, matB):",
"function_name": "multiply",
"parameter_list": "(matA, matB)"
},
{
"docstring": "Creates an identity matrix of size n x n.",
"function_declaration": "def identity(n):",
"function_name"... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply(matA, matB):\n \"\"\"\n Multiplies two 2x2 matrices.\n \"\"\"\n return [\n [matA[0][0]*matB[0][0] + matA[0][1]*matB[1][0], mat... | trial_gpt4o_1 | {
"original_instruction": "### Advanced Matrix Question\n\nYou are required to implement matrix multiplication and matrix exponentiation efficiently for solving a problem in computer graphics transformations.\n\n#### Problem Statement:\n\nYou are given two essential functions:\n1. `multiply(matA: list, matB: list) ->... | 0.536461 | Data_Structure_6661 | C | [
"multiply",
"identity",
"matrix_exponentiation",
"transform_point"
] | 4 | [
[
"matrix_exponentiation",
"identity"
],
[
"matrix_exponentiation",
"multiply"
],
[
"transform_point",
"matrix_exponentiation"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | ae6b66b057cf36084eb42b5e4e660712924a3992 | e4c58c320178ec7e21d6a4714b48466169b01d44 | |||
v1.0 | complete | Data_Structure | Data_Structure_6399_C | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def is_palindrome_efficient(head: ListNode) -> bool:
""" Verify if the linked list is a palindrome without using extra space.
Given a singly linked list of integers, this function determines i... | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def find_middle(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def reverse_list(head):
prev = None
current = head
... | from solution import is_palindrome_efficient, ListNode
def create_linked_list(values):
if not values:
return None
head = ListNode(values[0])
current = head
for value in values[1:]:
current.next = ListNode(value)
current = current.next
return head
def test_empty_list():
... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef is_palindrome_efficient(head: ListNode) ->... | trial_gpt4o_2 | {
"original_instruction": "### Question: Verify Linked List Palindrome Without Space Overhead\n\nGiven a singly linked list of integers, implement a function to determine if it reads the same backwards as forwards without using additional data structures (such as stacks or dictionaries). You should do this in \\(O(n)... | 0.633356 | Data_Structure_6399 | C | [
"find_middle",
"reverse_list",
"is_palindrome_efficient"
] | 3 | [
[
"is_palindrome_efficient",
"find_middle"
],
[
"is_palindrome_efficient",
"reverse_list"
]
] | 2 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | 168b0b3b9d746bb7ffbb60593e42238b175ffe13 | 5af681ab5e097ecf97b96ce2865ba6bb20de86c5 | |||
v1.0 | complete | Data_Structure | Data_Structure_7907_C | def list_gcd_bitwise(numbers: list) -> int:
"""
Given a list of non-negative integers, return their greatest common divisor using the bitwise method.
Parameters
----------
numbers : list of int
A list containing non-negative integers.
Returns
-------
int
The... | def gcd_bit(a, b):
# Base cases for the bitwise GCD algorithm
if a == 0: return b
if b == 0: return a
# Finding common factors of 2
if a == b: return a
if a == 1 or b == 1: return 1
# Reducing both a and b while both are even
if ~a & 1: # a is even
if ~b & 1: # b is e... | from solution import list_gcd_bitwise
def test_list_gcd_bitwise_basic():
assert list_gcd_bitwise([24, 36, 60]) == 12
assert list_gcd_bitwise([16, 32, 96]) == 16
assert list_gcd_bitwise([7, 14, 21]) == 7
def test_list_gcd_bitwise_with_zeros():
assert list_gcd_bitwise([0, 0, 5]) == 5
assert list_gcd... | [
{
"docstring": null,
"function_declaration": "def gcd_bit(a, b):",
"function_name": "gcd_bit",
"parameter_list": "(a, b)"
},
{
"docstring": "Given a list of non-negative integers, return their greatest common divisor using the bitwise method.",
"function_declaration": "def list_gcd_bitwi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd_bit(x, y):\n \"\"\"\n Compute the GCD of x and y using bitwise operations.\n \"\"\"\n if x == 0:\n return y\n if y == 0:\n ... | trial_gpt4o_1 | {
"original_instruction": "### Scenario\nYou are developing a software library that includes functions for performing various mathematical computations. Leveraging your understanding of algorithms and bitwise operations, you need to implement an optimized function to calculate the greatest common divisor (GCD) of a l... | 0.758517 | Data_Structure_7907 | C | [
"gcd_bit",
"list_gcd_bitwise"
] | 2 | [
[
"list_gcd_bitwise",
"gcd_bit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bf0f5bd9a0b3fd9d757b470d7aa197e31e67b522 | 06a5b150a8b452053dabeb43759c5b870b9a619e | |||
v1.0 | complete | Data_Structure | Data_Structure_8296_C | def is_match_rle(encoded_data: str, target_string: str) -> bool:
""" Checks whether RLE encoded data can be decoded to match a given target string.
>>> is_match_rle("3a2b1c", "aaabbc") == True
>>> is_match_rle("3a1b1c", "aaaabc") == False
>>> is_match_rle("", "") == True
>>> is_match_rle("10a", "aaa... | def decode_rle(encoded_data):
decoded = []
count = 0
for char in encoded_data:
if char.isdigit():
count = count * 10 + int(char) # Accommodates multi-digit numbers
else:
decoded.append(char * count)
count = 0
return ''.join(decoded)
def is_... | from solution import is_match_rle
def test_is_match_rle_basic_match():
assert is_match_rle("3a2b1c", "aaabbc") == True
def test_is_match_rle_basic_no_match():
assert is_match_rle("3a1b1c", "aaaabc") == False
def test_is_match_rle_empty_strings():
assert is_match_rle("", "") == True
def test_is_match_rle... | [
{
"docstring": null,
"function_declaration": "def decode_rle(encoded_data):",
"function_name": "decode_rle",
"parameter_list": "(encoded_data)"
},
{
"docstring": null,
"function_declaration": "def is_match_rle(encoded_data, target_string):",
"function_name": "is_match_rle",
"para... | [
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 is_match_rle(encoded_data: str, target_string: str) -> bool:\n \"\"\"\n Checks if the RLE encoded data can be decoded to match the target string.\n ... | trial_gpt4o_2 | {
"original_instruction": "You are required to implement a function that checks whether RLE encoded data can be decoded to match a given target string. \n\n### Detailed Description:\nYou need to write a function `is_match_rle(encoded_data, target_string)` that receives two parameters:\n1. `encoded_data`: A string rep... | 0.55621 | Data_Structure_8296 | C | [
"decode_rle",
"is_match_rle"
] | 2 | [
[
"is_match_rle",
"decode_rle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f1f85a5185b1e3385a4f19f4b61d8d2d8180bbcb | c2362aa0acc53aed9d358295dfa5e9d36b2595e9 | |||
v1.0 | complete | Data_Structure | Data_Structure_7692_C | import math
def _l2_distance(vec):
"""
Helper function to calculate the L2 norm of a vector.
:param vec: list of integers/floats
:return: float
"""
norm = 0.
for element in vec:
norm += element * element
return math.sqrt(norm)
def cosine_similarity(vec1, vec2):
"""
Func... | import math
def _l2_distance(vec):
"""
Helper function to calculate the L2 norm of a vector.
:param vec: list of integers/floats
:return: float
"""
norm = 0.
for element in vec:
norm += element * element
return math.sqrt(norm)
def cosine_similarity(vec1, vec2):
"""
Func... | from solution import cosine_similarity
def test_cosine_similarity_same_vector():
assert math.isclose(cosine_similarity([1, 1, 1], [1, 1, 1]), 1.0, rel_tol=1e-9)
def test_cosine_similarity_orthogonal_vectors():
assert math.isclose(cosine_similarity([1, 0, 0], [0, 1, 0]), 0.0, rel_tol=1e-9)
def test_cosine_sim... | [
{
"docstring": "Helper function to calculate the L2 norm of a vector.\n:param vec: list of integers/floats\n:return: float",
"function_declaration": "def _l2_distance(vec):",
"function_name": "_l2_distance",
"parameter_list": "(vec)"
},
{
"docstring": "Function to calculate cosine similarity... | [
0,
0,
0,
1,
0,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef _l2_distance(vec):\n \"\"\"\n Helper function to calculate the L2 norm of a vector.\n :param vec: list of integers/floats\n :re... | trial_gpt4o_7 | {
"original_instruction": "**Problem Statement**:\n\nYou are implementing a machine learning pipeline, and one of the requirements is to compute the cosine similarity between pairs of document vectors. Given the importance of this measure in evaluating the similarity between documents, your task is to write a functio... | 0.59494 | Data_Structure_7692 | C | [
"_l2_distance",
"cosine_similarity"
] | 2 | [
[
"cosine_similarity",
"_l2_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a33ad8241547dc76c18addf7909b85252524a037 | f612d46f3d8ed48aa0f81d5bbbe3bc5adf9e48cd | |||
v1.0 | complete | Data_Structure | Data_Structure_7561_C | from typing import List
def radix_sort(arr: List[int], simulation: bool=False) -> List[int]:
""" Sorts an array of non-negative integers using radix sort algorithm.
This function also has a simulation feature to display the array at each stage of sorting.
Args:
arr (List[int]): A list of non-... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - ... | from solution import radix_sort
def test_radix_sort_single_element():
arr = [10]
assert radix_sort(arr) == [10]
def test_radix_sort_sorted_array():
arr = [1, 2, 3, 4, 5, 6]
assert radix_sort(arr) == [1, 2, 3, 4, 5, 6]
def test_radix_sort_duplicate_values():
arr = [7, 7, 7, 7, 7]
assert radix_... | [
{
"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,
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 counting_sort(arr: List[int], exp: int, simulation: bool):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \... | trial_gpt4o_0 | {
"original_instruction": "### Radix Sort Implementation and Simulation\n\n#### Context: \n\nImagine you are building a data processing system that needs to handle large sets of integer data efficiently. Radix Sort is particularly well-suited for this task as it sorts integers in linear time for small ranges of digit... | 0.690462 | Data_Structure_7561 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f955876ae8f9b8b3e4d610fed9a6a848b6136183 | 5b44251fdeffdb9f3abac2c43d65a760168996e9 | |||
v1.0 | complete | Data_Structure | Data_Structure_5870_C | from typing import List
def optimized_insertion_sort(arr: List[int], threshold: int) -> List[int]:
""" Sorts an array of integers using an optimized sorting method that switches
between insertion sort and quicksort based on a given threshold.
If the length of the array is less than or equal to the thr... | from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
"""
Simple insertion sort algorithm for reasonably small arrays.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
... | from solution import optimized_insertion_sort
def test_example_case_1():
arr = [5, 2, 9, 1, 5, 6]
threshold = 10
assert optimized_insertion_sort(arr, threshold) == [1, 2, 5, 5, 6, 9]
def test_example_case_2():
arr = [50, 23, 93, 17, 77, 31, 44, 55, 20, 27]
threshold = 5
assert optimized_insert... | [
{
"docstring": "Simple insertion sort algorithm for reasonably small arrays.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Quicksort algorithm for larger arrays.",
"function_declaration": "def quickso... | [
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 optimized_insertion_sort(arr, threshold):\n def insertion_sort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort Enhancement\n\nAs a software developer at an e-commerce company, you've been tasked to optimize the sorting algorithm for various data-intensive reporting features. The current implementation of the Insertion Sort works fine; however, it struggles with large datasets. \n\... | 0.585828 | Data_Structure_5870 | C | [
"insertion_sort",
"quicksort",
"optimized_insertion_sort"
] | 3 | [
[
"optimized_insertion_sort",
"insertion_sort"
],
[
"optimized_insertion_sort",
"quicksort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e1dcc9d16e9f8b3ac8a87a7848ec3488f89b62a8 | f2e3bb823f86b47ee6caf59d669353e023d759c5 | |||
v1.0 | complete | Data_Structure | Data_Structure_6461_C | from typing import List
def enhanced_invert_matrix(matrix: List[List[int]]) -> List[List[float]]:
""" Write a function `enhanced_invert_matrix(matrix)` that takes a square matrix as input and returns its inverse.
This function should handle larger matrices more efficiently and accurately. Utilize cache me... | from typing import List
def get_matrix_minor(matrix, i, j):
return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]
def get_matrix_determinant(matrix):
# Base case for 2x2 matrix
if len(matrix) == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
determinant = 0
... | from solution import enhanced_invert_matrix
def test_invert_matrix_2x2():
matrix = [
[4, 7],
[2, 6]
]
expected = [
[0.6, -0.7],
[-0.2, 0.4]
]
assert enhanced_invert_matrix(matrix) == expected
def test_invert_matrix_3x3():
matrix = [
[1, 2, 3],
[0... | [
{
"docstring": null,
"function_declaration": "def get_matrix_minor(matrix, i, j):",
"function_name": "get_matrix_minor",
"parameter_list": "(matrix, i, j)"
},
{
"docstring": null,
"function_declaration": "def get_matrix_determinant(matrix):",
"function_name": "get_matrix_determinant"... | [
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, Optional\n\ndef enhanced_invert_matrix(matrix: List[List[int]]) -> Optional[List[List[float]]]:\n def determinant(matrix, cache={}... | trial_gpt4o_1 | {
"original_instruction": "### Matrix Inversion Enhancement\n\n#### Objective\nYou are tasked with enhancing the provided matrix inversion function to handle larger matrices more efficiently and accurately. Your solution should aim to reduce the computational overhead and manage error scenarios robustly.\n\n#### Prob... | 0.537077 | Data_Structure_6461 | C | [
"get_matrix_minor",
"get_matrix_determinant",
"get_matrix_inverse",
"enhanced_invert_matrix"
] | 4 | [
[
"enhanced_invert_matrix",
"get_matrix_inverse"
],
[
"get_matrix_determinant",
"get_matrix_minor"
],
[
"get_matrix_inverse",
"get_matrix_determinant"
],
[
"get_matrix_inverse",
"get_matrix_minor"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 3d193a9acb1bf97de68f36c7f5df2acd7d3d37c8 | 13844fa1beec4e6a19a3d72968f01d8757668cdb | |||
v1.0 | complete | Data_Structure | Data_Structure_6423_C | from typing import List
def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
"""
Sort a list of non-negative integers using radix sort algorithm.
Args:
arr (List[int]): A list of non-negative integers.
simulation (bool): Optional; if True, print intermediate iterations.
... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool, iteration: int) -> None:
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 - ... | from solution import radix_sort
def test_radix_sort_unsorted():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_partially_sorted():
assert radix_sort([3, 0, 2, 5, 4, 1]) == [0, 1, 2, 3, 4, 5]
def test_radix_sort_empty():
assert radix_s... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation, iteration):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation, iteration)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"funct... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool, iteration: int) -> None:\n n = len(arr)\n output = [0] * n\n ... | trial_gpt4o_0 | {
"original_instruction": "You are provided with a list of non-negative integers. Your task is to implement the `radix_sort` function. This function will sort the integers using the radix sort algorithm and return the sorted list.\n\n### Function Signature\n```python\ndef radix_sort(arr: List[int], simulation: bool =... | 0.683417 | Data_Structure_6423 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 30b73af4a9ad74062351c80d1a642593ffffe09e | fb30b3c9b40c5d6bef4670bb3d79e0e4ae3ee4bd | |||
v1.0 | complete | Data_Structure | Data_Structure_7011_C | from typing import List, Tuple
def interval_merge(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
"""
Merges overlapping intervals.
>>> interval_merge([]) == []
>>> interval_merge([(1, 3)]) == [(1, 3)]
>>> interval_merge([(1, 3), (2, 4), (5, 7)]) == [(1, 4), (5, 7)]
>>> interval_mer... | def interval_merge(intervals):
"""
Merges overlapping intervals.
"""
if not intervals:
return []
# Sort intervals based on the start time
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
# if merged list is empty or last interval in merged d... | from solution import interval_merge, non_overlapping_intervals
def test_interval_merge():
assert interval_merge([]) == []
assert interval_merge([(1, 3)]) == [(1, 3)]
assert interval_merge([(1, 3), (2, 4), (5, 7)]) == [(1, 4), (5, 7)]
assert interval_merge([(1, 5), (2, 3), (3, 4)]) == [(1, 5)]
asser... | [
{
"docstring": "Merges overlapping intervals.",
"function_declaration": "def interval_merge(intervals):",
"function_name": "interval_merge",
"parameter_list": "(intervals)"
},
{
"docstring": "Finds candidate intervals that do not overlap with any of the main intervals.",
"function_declar... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef interval_merge(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]] :\n if not intervals:\n return []\n\... | trial_gpt4o_2 | {
"original_instruction": "### Merging Intervals and Finding Non-overlapping Intervals\n\n**Objective:**\n\nDesign a Python function to merge overlapping intervals and another to find intervals that do not overlap with any in a given list of intervals.\n\n**Background:**\n\nIn calendar systems, reservation platforms,... | 0.703768 | Data_Structure_7011 | C | [
"interval_merge",
"non_overlapping_intervals"
] | 2 | [
[
"non_overlapping_intervals",
"interval_merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5b4a0089ce8ca4871c09b68175e4ff49bd3cfd10 | 5648d57dafa5c3fdb8725fe38cc183396554e614 | |||
v1.0 | complete | Data_Structure | Data_Structure_7801_C | def find_element(arr, target, simulation=False):
""" Implement a function that uses Bubble Sort to sort the input
array, then performs a binary search to find a target element.
Args:
arr: List of integers.
target: Integer to find.
simulation: A boolean indicating whether to print the Bubbl... | def bubble_sort(arr, simulation):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
if simulation:
print(f"Step {i * n + j + 1}: {arr}")
def binary_search(arr, tar... | def test_find_element_sorted_array():
arr = [1, 2, 3, 4, 5]
target = 3
assert find_element(arr, target) == 2
def test_find_element_unsorted_array():
arr = [5, 2, 9, 1, 5, 6]
target = 5
index = find_element(arr, target)
assert arr[index] == 5
def test_find_element_not_present():
arr = [... | [
{
"docstring": null,
"function_declaration": "def bubble_sort(arr, simulation):",
"function_name": "bubble_sort",
"parameter_list": "(arr, simulation)"
},
{
"docstring": null,
"function_declaration": "def binary_search(arr, target):",
"function_name": "binary_search",
"parameter_... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bubble_sort(arr, simulation):\n n = len(arr)\n for i in range(n):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n ... | trial_gpt4o_0 | {
"original_instruction": "**Question**: \n\nImplement a function `find_element(arr, target, simulation=False)` that uses Bubble Sort to sort the input array, then performs a binary search to find a target element.\n\n### Input:\n- `arr`: A list of integers that may be unsorted.\n- `target`: An integer to find in the... | 0.627744 | Data_Structure_7801 | C | [
"bubble_sort",
"binary_search",
"find_element"
] | 3 | [
[
"find_element",
"binary_search"
],
[
"find_element",
"bubble_sort"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 99ff850b09eb91e784c98233241995c58dcd3d03 | 14b067aff11c4b0bc3852d6341fa53da4635adff | |||
v1.0 | complete | Data_Structure | Data_Structure_6585_C | def classify_query_point(query_point: tuple, training_set: dict) -> any:
"""Classifies the query point based on the nearest neighbor in the training set.
Arguments:
query_point (tuple): The point to classify.
training_set (dict): A dictionary where keys are tuples representing points and values are... | import math
def euclidean_distance(point1, point2):
"""
Calculates the Euclidean distance between two N-dimensional points.
Arguments:
point1 (tuple): The first point.
point2 (tuple): The second point.
Returns:
float: The Euclidean distance between the points.
"""
return m... | from solution import classify_query_point
def test_single_point_training_set():
query_point = (2, 3)
training_set = {(1, 2): 'ClassA'}
assert classify_query_point(query_point, training_set) == 'ClassA'
def test_multiple_points_training_set():
query_point = (2, 3)
training_set = {
(1, 2): '... | [
{
"docstring": "Calculates the Euclidean distance between two N-dimensional points.\n\nArguments:\npoint1 (tuple): The first point.\npoint2 (tuple): The second point.\n\nReturns:\nfloat: The Euclidean distance between the points.",
"function_declaration": "def euclidean_distance(point1, point2):",
"func... | [
0,
0,
0,
0,
1,
1,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Computes the Euclidean distance between two N-dimensional points.\n \"\"\"\n ret... | trial_gpt4o_8 | {
"original_instruction": "### Question\n\nYou are given a training dataset of labeled N-dimensional points, and a single query point. Implement a function to classify the query point using the nearest neighbor algorithm as described above. Your implementation should read an input of N-dimensional points, compute the... | 0.572629 | Data_Structure_6585 | C | [
"euclidean_distance",
"classify_query_point"
] | 2 | [
[
"classify_query_point",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2ebb42053a4c3548c3a11123762b695a79153d0d | 3d31361d7a9f09f376cac53f4e1871c3fe8588ea | |||
v1.0 | complete | Data_Structure | Data_Structure_7878_C | def gcd_optimal(a: int, b: int) -> int:
""" Computes the GCD of two non-negative integers using bitwise operations.
>>> gcd_optimal(48, 18)
6
>>> gcd_optimal(0, 10)
10
>>> gcd_optimal(101, 103)
1
"""
def lcm_using_gcd(a: int, b: int) -> int:
""" Computes the LCM of two non-negative ... | def gcd_optimal(a, b):
"""
Computes the GCD of two non-negative integers using bitwise operations.
"""
if a == 0:
return b
if b == 0:
return a
# Both a and b are even
if (a & 1) == 0 and (b & 1) == 0:
return gcd_optimal(a >> 1, b >> 1) << 1
# a is even, b is... | from solution import gcd_optimal, lcm_using_gcd, trailing_zero_bits
def test_gcd_optimal():
assert gcd_optimal(48, 18) == 6
assert gcd_optimal(0, 10) == 10
assert gcd_optimal(10, 0) == 10
assert gcd_optimal(0, 0) == 0
assert gcd_optimal(101, 103) == 1
assert gcd_optimal(56, 98) == 14
def test_... | [
{
"docstring": "Computes the GCD of two non-negative integers using bitwise operations.",
"function_declaration": "def gcd_optimal(a, b):",
"function_name": "gcd_optimal",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the LCM of two non-negative integers using the GCD calculated fro... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd_optimal(a, b):\n \"\"\"\n Returns the greatest common divisor (GCD) of two non-negative integers using bitwise operations.\n \"\"\"\n if a... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\n\nYou have been hired by a large organization to assist in processing significant amounts of data related to their inventory system. A crucial part of this system is determining optimal batch sizes for manufacturing. To achieve this, you need to compute the Greatest Common Div... | 0.691706 | Data_Structure_7878 | C | [
"gcd_optimal",
"lcm_using_gcd",
"trailing_zero_bits"
] | 3 | [
[
"lcm_using_gcd",
"gcd_optimal"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9ac5d03998b4c7cb0ed2b755636b72d73533362b | 213b5ab7d3299536f033cdea6e34ac1433468fa5 | |||
v1.0 | complete | Data_Structure | Data_Structure_6013_C | def quick_sort(arr: list, left: int, right: int) -> None:
"""
Sorts the array in-place from index 'left' to index 'right' using Quick Sort algorithm.
Parameters:
arr: list - list of elements to be sorted.
left: int - starting index of the segment of the list to be sorted.
right: int - endin... | def quick_sort(arr, left, right):
"""
Sorts the array in-place from index 'left' to index 'right' using Quick Sort algorithm.
Parameters:
arr: list - list of elements to be sorted.
left: int - starting index of the segment of the list to be sorted.
right: int - ending index of the segment o... | from solution import quick_sort
def test_sorted_array():
arr = [1, 2, 3, 4, 5]
quick_sort(arr, 0, len(arr) - 1)
assert arr == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
arr = [5, 4, 3, 2, 1]
quick_sort(arr, 0, len(arr) - 1)
assert arr == [1, 2, 3, 4, 5]
def test_unsorted_array():
ar... | [
{
"docstring": "Sorts the array in-place from index 'left' to index 'right' using Quick Sort algorithm.\n\nParameters:\narr: list - list of elements to be sorted.\nleft: int - starting index of the segment of the list to be sorted.\nright: int - ending index of the segment of the list to be sorted.",
"funct... | [
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 quick_sort(arr: list, left: int, right: int) -> None:\n \"\"\"\n Sorts the array in-place from index 'left' to index 'right' using Quick Sort algori... | trial_gpt4o_2 | {
"original_instruction": "Efficient Sorting Function\n\n#### Scenario\nYou have been provided with a legacy sorting function in a project, called Stooge Sort, which is seen to be highly inefficient for practical use due to its very high time complexity. Your task is to implement a more efficient sorting algorithm to... | 0.602307 | Data_Structure_6013 | C | [
"quick_sort",
"partition"
] | 2 | [
[
"quick_sort",
"partition"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e8d04117a643ddd14c7fddbddcdccb747b9a0f0c | 9ff7b72c5ddda5952217e44867bd7fb4914339f0 | |||
v1.0 | complete | Data_Structure | Data_Structure_7384_C | def custom_merge_sort(arr):
"""
Sorts an array while maintaining the relative order of equal elements.
This function should use the Merge Sort algorithm.
Args:
arr (List[int]): A list of integers to be sorted.
Returns:
List[int]: The sorted list.
"""
pass
def merge(left, r... | def custom_merge_sort(arr):
"""
Sorts an array while maintaining the relative order of equal elements.
This function uses the Merge Sort algorithm.
Args:
arr (List[int]): A list of integers to be sorted.
Returns:
List[int]: The sorted list.
"""
if len(arr) <= 1:
ret... | from solution import custom_merge_sort
def test_custom_merge_sort_basic():
assert custom_merge_sort([3, 2, 1, 4, 2, 3]) == [1, 2, 2, 3, 3, 4]
def test_custom_merge_sort_single_element():
assert custom_merge_sort([1]) == [1]
def test_custom_merge_sort_two_elements():
assert custom_merge_sort([2, 1]) == [1... | [
{
"docstring": "Sorts an array while maintaining the relative order of equal elements.\nThis function uses the Merge Sort algorithm.\n\nArgs:\narr (List[int]): A list of integers to be sorted.\n\nReturns:\nList[int]: The sorted list.",
"function_declaration": "def custom_merge_sort(arr):",
"function_nam... | [
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 custom_merge_sort(arr):\n \"\"\"\n Sorts an array while maintaining the relative order of equal elements.\n This function should use the Merge So... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with implementing a custom sorting function for a dataset that frequently contains duplicate values and requires the preservation of the original order of those duplicates. This sorting is critical for maintaining the data's integrity in a large-scale distributed system.\n\n*... | 0.688395 | Data_Structure_7384 | C | [
"custom_merge_sort",
"merge"
] | 2 | [
[
"custom_merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0c5a3fbec52e4a9da37431d7e03bd0cc8953dbd1 | bc1b3d020fd24a36adbeadd18775992f85dd9b3f | |||
v1.0 | complete | Data_Structure | Data_Structure_7407_C | from typing import List
def gen_strobogrammatic(n: int) -> List[str]:
""" Generate all strobogrammatic numbers of length n.
>>> gen_strobogrammatic(1)
['0', '1', '8']
>>> gen_strobogrammatic(2)
['11', '69', '88', '96']
"""
pass
def strobogrammatic_in_range(low: str, high: str) -> int:
... | def gen_strobogrammatic(n):
"""
Generate all strobogrammatic numbers of length n.
"""
def helper(n, total_length):
if n == 0:
return [""]
if n == 1:
return ["0", "1", "8"]
middles = helper(n - 2, total_length)
result = []
... | from solution import gen_strobogrammatic, strobogrammatic_in_range
def test_gen_strobogrammatic_length_1():
assert set(gen_strobogrammatic(1)) == {"0", "1", "8"}
def test_gen_strobogrammatic_length_2():
expected = {"11", "69", "88", "96"}
assert set(gen_strobogrammatic(2)) == expected
def test_gen_strobo... | [
{
"docstring": "Generate all strobogrammatic numbers of length n.",
"function_declaration": "def gen_strobogrammatic(n):",
"function_name": "gen_strobogrammatic",
"parameter_list": "(n)"
},
{
"docstring": "Count strobogrammatic numbers within the range [low, high].",
"function_declaratio... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gen_strobogrammatic(n):\n \"\"\"\n Generates all strobogrammatic numbers of length n.\n \"\"\"\n def helper(m, is_final):\n if m == 0:\... | trial_gpt4o_3 | {
"original_instruction": "### Strobogrammatic Number Challenge\n\n### Objective\nWrite a Python function that generates all strobogrammatic numbers of length `n` and another function that counts how many strobogrammatic numbers exist within a given range `[low, high]`.\n\n### Function Specifications\n1. `gen_strobog... | 0.527978 | Data_Structure_7407 | C | [
"gen_strobogrammatic",
"strobogrammatic_in_range"
] | 2 | [
[
"strobogrammatic_in_range",
"gen_strobogrammatic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9c5ee9d3b64b8b58fc32b75430c116754b032b96 | 7f33a50108edf24c56df772fd33a0970599541f1 | |||
v1.0 | complete | Data_Structure | Data_Structure_8688_C | def search_insert(array, val):
"""
Binary search helper function to locate the index where `val` should be inserted
to maintain sorted order in `array`.
"""
lo, hi = 0, len(array)
while lo < hi:
mid = (lo + hi) // 2
if array[mid] < val:
lo = mid + 1
else:
... | def search_insert(array, val):
"""
Binary search helper function to locate the index where `val` should be inserted
to maintain sorted order in `array`.
"""
lo, hi = 0, len(array)
while lo < hi:
mid = (lo + hi) // 2
if array[mid] < val:
lo = mid + 1
else:
... | def test_insertion_sort_empty():
assert insertion_sort([]) == []
def test_insertion_sort_single_element():
assert insertion_sort([1]) == [1]
def test_insertion_sort_multiple_elements():
assert insertion_sort([3, 1, 2]) == [1, 2, 3]
assert insertion_sort([4, 7, 5, 2, 6]) == [2, 4, 5, 6, 7]
assert i... | [
{
"docstring": "Binary search helper function to locate the index where `val` should be inserted\nto maintain sorted order in `array`.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "Sorts an ar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(array, val):\n \"\"\"\n Helper function to perform binary search to find the index where 'val' should be inserted in 'array'.\n \"\... | trial_gpt4o_2 | {
"original_instruction": "### Question: Insertion Sort Implementation Using Binary Search\n\n#### Objective\nWrite a function that uses the `search_insert` helper method to implement the Insertion Sort algorithm. The function should sort an array of integers in ascending order.\n\n#### Detailed Description\nThe Inse... | 0.632697 | Data_Structure_8688 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 5b482ccc5c5e012e95fa76313ba83e6c6d6b40db | 217bf35195353970e9f509f67a7b197bc7c1b4fe | |||
v1.0 | complete | Data_Structure | Data_Structure_8283_C | from typing import List
def enhanced_insertion_sort(arr: List[int]) -> List[int]:
""" Enhanced Insertion Sort for Improved Performance.
This function sorts a list of integers using an improved version of the
insertion sort algorithm. It applies the binary search technique to find
the correct inser... | def binary_search(arr, val, start, end):
"""
Perform a binary search to find the correct position of an element to be inserted.
"""
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
start = mid + 1
else:
end = mid
return start
def enhance... | from solution import enhanced_insertion_sort
def test_enhanced_insertion_sort_random_list():
assert enhanced_insertion_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
def test_enhanced_insertion_sort_empty_list():
assert enhanced_insertion_sort([]) == []
def test_enhanced_inserti... | [
{
"docstring": "Perform a binary search to find the correct position of an element to be inserted.",
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "Sorts an array using an enh... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_insertion_sort(arr):\n \"\"\"\n An enhanced version of the insertion sort algorithm using binary search\n to find the correct position f... | trial_gpt4o_2 | {
"original_instruction": "### Question: Enhanced Insertion Sort for Improved Performance\n\n#### Context\nYou are working as a software engineer at a tech company where optimal performance of algorithms is crucial. Your team identifies that the existing Insertion Sort algorithm works inefficiently for larger dataset... | 0.645097 | Data_Structure_8283 | C | [
"binary_search",
"enhanced_insertion_sort"
] | 2 | [
[
"enhanced_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b459532cc32519b26f779c5df2b4f555b23808c8 | c01ad6bb15c86f06a746adc80f6c4d7c469e386a | |||
v1.0 | complete | Data_Structure | Data_Structure_7188_C | import math
from typing import List, Tuple
def vector_to_index_value_list(vector: List[float]) -> List[Tuple[int, float]]:
""" Convert a full vector to its sparse representation using an index-value list.
>>> vector_to_index_value_list([0.0, 1.0, 0.0, 2.0])
[(1, 1.0), (3, 2.0)]
>>> vector_to_index_valu... | import math
def vector_to_index_value_list(vector):
"""
Convert a full vector to its sparse representation using an index-value list.
"""
return [(index, value) for index, value in enumerate(vector) if value != 0]
def dot_product(iv_list1, iv_list2):
"""
Compute the dot product between two spa... | from solution import vector_to_index_value_list, dot_product, magnitude, cosine_similarity
def test_vector_to_index_value_list():
assert vector_to_index_value_list([0.0, 1.0, 0.0, 2.0]) == [(1, 1.0), (3, 2.0)]
assert vector_to_index_value_list([0.0, 0.0, 0.0, 0.0]) == []
assert vector_to_index_value_list([... | [
{
"docstring": "Convert a full vector to its sparse representation using an index-value list.",
"function_declaration": "def vector_to_index_value_list(vector):",
"function_name": "vector_to_index_value_list",
"parameter_list": "(vector)"
},
{
"docstring": "Compute the dot product between tw... | [
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 math\n\ndef vector_to_index_value_list(vector):\n \"\"\"\n Converts a full vector to its sparse representation in the form of an index-value list... | trial_gpt4o_1 | {
"original_instruction": "Sparse Vector Representation and Operations\n\n#### Scenario\nYou are given a large dataset represented by high-dimensional vectors. Most elements in these vectors are zeros, making direct computation costly in terms of space and time. To optimize performance, you would use sparse represent... | 0.532877 | Data_Structure_7188 | C | [
"vector_to_index_value_list",
"dot_product",
"magnitude",
"cosine_similarity"
] | 4 | [
[
"cosine_similarity",
"dot_product"
],
[
"cosine_similarity",
"magnitude"
],
[
"cosine_similarity",
"vector_to_index_value_list"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | afd3b00a7dc4b000e76571238553765d59cffd7d | 3c82a8325aea8f4116301b51a9e8cfb1fc485290 | |||
v1.0 | complete | Data_Structure | Data_Structure_7909_C | from typing import List
def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
"""Sorts a given list of non-negative integers using the radix sort algorithm.
Args:
arr (List[int]): A list of non-negative integer IDs (0 ≤ ID ≤ 1,000,000)
simulation (bool): A boolean flag which, if s... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool=False) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
# Store count of occurrences in count[]
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
# Change... | import pytest
from solution import radix_sort
def test_radix_sort_empty():
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort([5]) == [5]
def test_radix_sort_already_sorted():
assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_radix_sort_small_list():
ass... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation=False):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name":... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool=False) -> List[int]:\n n = len(arr)\n output = [0] * n \n co... | trial_gpt4o_0 | {
"original_instruction": "**Scenario:**\n\nYou are working on an inventory management system that handles a large amount of product data. Each product has a unique integer ID. To efficiently sort the product IDs for better access and retrieval, you decided to implement a radix sort.\n\n### Task:\n\n**Function to imp... | 0.66617 | Data_Structure_7909 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bf04a2954fafb0339bf5fe9fb3e1794c57e98641 | bbcf4afc719a6c6efc358bd161f9435d1e29bf30 | |||
v1.0 | complete | Data_Structure | Data_Structure_9200_C | def primitive_root_presence(n: int) -> bool:
""" Determine whether a given integer n (n > 1) has any primitive roots.
>>> primitive_root_presence(10)
False
>>> primitive_root_presence(17)
True
""" | from math import gcd
def euler_totient(n):
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1
if n > 1:
result -= result // n
return result
def find_order(a, n):
if gcd(a, n) !... | from solution import primitive_root_presence
def test_primitive_root_presence_for_prime():
assert primitive_root_presence(7) == True, "Test case for prime number 7 failed."
def test_primitive_root_presence_for_non_prime():
assert primitive_root_presence(10) == False, "Test case for non-prime number 10 failed.... | [
{
"docstring": null,
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def find_order(a, n):",
"function_name": "find_order",
"parameter_list": "(a, n)"
},
{
"docstri... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def euler_totient(n):\n \"\"\"\n Compute the Euler's Totient function ϕ(n) for a given integer n.\n \"\"\"\n if n == 1:\n return 1\n res... | trial_gpt4o_5 | {
"original_instruction": "### Primitive Root Determination and Totient Calculation\n\n#### Problem Statement\nYou are given a series of functions related to primitive root determination and Euler's totient function. These functions can be very useful in fields such as cryptography. Your task is to write a function t... | 0.543184 | Data_Structure_9200 | C | [
"euler_totient",
"find_order",
"find_primitive_root",
"primitive_root_presence"
] | 4 | [
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"find_order"
],
[
"primitive_root_presence",
"find_primitive_root"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 31b605aaf538bab9c53b836ddcd2db69302b1eee | a929f5b6b4b2ab8a7a563be11863ed229cd2346b | |||
v1.0 | complete | Data_Structure | Data_Structure_7267_C | from typing import List
def adaptive_heap_sort(arr: List[int]) -> List[int]:
"""
Sorts an array in ascending order using an adaptive combination
of heap sort and insertion sort.
Args:
- arr: List[int] : The input array to sort.
Returns:
- List[int]: The sorted array.
"""
... | from typing import List
def insertion_sort(arr: List[int], start: int, end: int) -> None:
"""Utility function to perform insertion sort on subarray arr[start:end+1]."""
for i in range(start + 1, end + 1):
key = arr[i]
j = i - 1
while j >= start and key < arr[j]:
arr[j + 1] =... | def test_insertion_sort():
arr = [5, 2, 9, 1, 5, 6]
insertion_sort(arr, 0, len(arr) - 1)
assert arr == [1, 2, 5, 5, 6, 9]
def test_heap_sort():
arr = [12, 11, 13, 5, 6, 7]
heap_sort(arr)
assert arr == [5, 6, 7, 11, 12, 13]
def test_adaptive_heap_sort_empty():
assert adaptive_heap_sort([]) ... | [
{
"docstring": "Utility function to perform insertion sort on subarray arr[start:end+1].",
"function_declaration": "def insertion_sort(arr, start, end):",
"function_name": "insertion_sort",
"parameter_list": "(arr, start, end)"
},
{
"docstring": "Utility function to heapify a subtree rooted ... | [
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 adaptive_heap_sort(arr):\n \"\"\"\n Sorts an array in ascending order using an adaptive combination \n of heap sort and insertion sort.\n \n ... | trial_gpt4o_2 | {
"original_instruction": "### Coding Challenge: Adaptive Heap Sort\n\n**Context**: While the typical heap sort algorithm performs well under normal conditions (O(n log(n))), certain input patterns can still cause unnecessary overhead. To improve performance, you are tasked to implement an adaptive heap sort that red... | 0.632691 | Data_Structure_7267 | C | [
"insertion_sort",
"heapify",
"heap_sort",
"adaptive_heap_sort"
] | 4 | [
[
"adaptive_heap_sort",
"insertion_sort"
],
[
"heap_sort",
"heapify"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | a7706777d5a47eac68c053a8beb23aec81d07fb4 | 5b43aa587b2a151d8f968857fb872313ee7db8f9 | |||
v1.0 | complete | Data_Structure | Data_Structure_7722_C | from typing import List
def search_insert(sorted_sublist: List[int], x: int) -> int:
"""
Helper function to find the index where x should be inserted in sorted_sublist
to maintain sorted order.
"""
low, high = 0, len(sorted_sublist)
while low < high:
mid = (low + high) // 2
if s... | from typing import List
def search_insert(sorted_sublist: List[int], x: int) -> int:
"""
Helper function to find the index where x should be inserted in sorted_sublist
to maintain sorted order.
"""
low, high = 0, len(sorted_sublist)
while low < high:
mid = (low + high) // 2
if s... | from solution import insertion_sort
def test_insertion_sort_example_1():
assert insertion_sort([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12]
def test_insertion_sort_example_2():
assert insertion_sort([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13]
def test_insertion_sort_example_3():
assert inserti... | [
{
"docstring": "Helper function to find the index where x should be inserted in sorted_sublist\nto maintain sorted order.",
"function_declaration": "def search_insert(sorted_sublist, x):",
"function_name": "search_insert",
"parameter_list": "(sorted_sublist, x)"
},
{
"docstring": "Sorts 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": "from typing import List\n\ndef search_insert(arr: List[int], x: int) -> int:\n \"\"\"\n Helper function to find the insertion point for x in a sorted ar... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort with Efficient Insertion Point Search\n\n**Problem Statement**:\nUsing the provided `search_insert` helper function, implement an insertion sort algorithm that sorts an array of integers in ascending order. Your implementation should efficiently find the insertion point f... | 0.654887 | Data_Structure_7722 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ba11b12b2cf06d6f4b1e54dd8c19144721ef2b58 | 2cd486e71be4d14dec14ce9c4295ede0e7608e68 | |||
v1.0 | complete | Data_Structure | Data_Structure_7648_C | from typing import List
def heapify(arr: List[int], n: int, i: int, simulation: bool) -> None:
""" Helper function to maintain the heap property.
"""
pass
def heap_sort(arr: List[int], simulation: bool = False) -> List[int]:
""" Sort an array in ascending order using the heap sort algorithm.
... | from typing import List
def heapify(arr: List[int], n: int, i: int, simulation: bool) -> None:
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest !=... | from solution import heap_sort
def test_heap_sort():
# Test with an unsorted array
arr = [4, 10, 3, 5, 1]
assert heap_sort(arr, simulation=False) == [1, 3, 4, 5, 10]
# Test with an already sorted array
arr = [1, 2, 3, 4, 5]
assert heap_sort(arr, simulation=False) == [1, 2, 3, 4, 5]
# Test... | [
{
"docstring": null,
"function_declaration": "def heapify(arr, n, i, simulation):",
"function_name": "heapify",
"parameter_list": "(arr, n, i, simulation)"
},
{
"docstring": null,
"function_declaration": "def heap_sort(arr, simulation=False):",
"function_name": "heap_sort",
"para... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef heap_sort(arr: List[int], simulation: bool=False) -> List[int]:\n \n def heapify(arr: List[int], n: int, i: int):\n ... | trial_gpt4o_1 | {
"original_instruction": "### Question\n\nYou are required to implement a **Heap Sort** function that sorts an array in ascending order using a **max heap** approach. To assess your understanding of the algorithm and its properties, you should provide a detailed implementation of the core functions and handle variou... | 0.664794 | Data_Structure_7648 | C | [
"heapify",
"heap_sort"
] | 2 | [
[
"heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 84567ee3007aae3f80d4f9f317693177fbbdde39 | b746a11725db38d3603f45d7f3e32ade6914588b | |||
v1.0 | complete | Data_Structure | Data_Structure_7690_C | def optimized_matrix_exponentiation(mat: list, n: int) -> list:
"""
Exponentiates a matrix mat to the power n efficiently.
Parameters:
mat (list of list of int): a 2D list representing a square matrix.
n (int): a non-negative integer which represents the exponent.
Returns:
list of list of ... | def matrix_multiply(A, B):
"""Multiplies two square matrices A and B."""
size = len(A)
result = [[0] * size for _ in range(size)]
for i in range(size):
for j in range(size):
for k in range(size):
result[i][j] += A[i][k] * B[k][j]
return result
def identity_matrix... | def test_matrix_multiply():
A = [
[1, 2],
[3, 4]
]
B = [
[5, 6],
[7, 8]
]
expected = [
[19, 22],
[43, 50]
]
assert matrix_multiply(A, B) == expected
def test_identity_matrix():
assert identity_matrix(3) == [
[1, 0, 0],
[0, ... | [
{
"docstring": "Multiplies two square matrices A and B.",
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": "Creates an identity matrix of given size.",
"function_declaration": "def identity_matrix(size)... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "def optimized_matrix_exponentiation(mat, n):\n def matrix_mult(A, B):\n \"\"\" Multiplies two matrices A and B \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement and Optimize Matrix Operations\n\nYou are required to write a Python function that efficiently performs matrix exponentiation for large powers. While the provided snippets of the matrix multiplication, identity matrix generation, and matrix exponentiation do the job,... | 0.492111 | Data_Structure_7690 | C | [
"matrix_multiply",
"identity_matrix",
"matrix_power",
"optimized_matrix_exponentiation"
] | 4 | [
[
"matrix_power",
"identity_matrix"
],
[
"matrix_power",
"matrix_multiply"
],
[
"optimized_matrix_exponentiation",
"identity_matrix"
],
[
"optimized_matrix_exponentiation",
"matrix_power"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 90ef133541221b73507306f9a576e5332ac9ded4 | c57198dd8612b8959477cf457f6bfb575f3de926 | |||
v1.0 | complete | Data_Structure | Data_Structure_8238_C | from typing import List, Tuple
def gcd_bit(a: int, b: int) -> int:
while b:
a, b = b, a % b
return a
def pairwise_gcd(nums: List[int]) -> List[Tuple[int, int, int]]:
"""
Calculate the GCD for each possible pair of integers in the list.
Parameters:
nums (List[int]): A list of posit... | from typing import List, Tuple
def gcd_bit(a: int, b: int) -> int:
while b:
a, b = b, a % b
return a
def pairwise_gcd(nums: List[int]) -> List[Tuple[int, int, int]]:
"""
Calculate the GCD for each possible pair of integers in the list.
Parameters:
nums (List[int]): A list of posit... | from solution import pairwise_gcd
def test_pairwise_gcd_example_case():
nums = [10, 15, 25]
result = pairwise_gcd(nums)
expected = [(10, 15, 5), (10, 25, 5), (15, 25, 5)]
assert result == expected
def test_pairwise_gcd_single_element():
nums = [4]
result = pairwise_gcd(nums)
expected = []
... | [
{
"docstring": null,
"function_declaration": "def gcd_bit(a, b):",
"function_name": "gcd_bit",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate the GCD for each possible pair of integers in the list.\n\nParameters:\nnums (List[int]): A list of positive integers\n\nReturns:\nList[Tuple... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef gcd_bit(a: int, b: int) -> int:\n \"\"\"\n Compute the GCD of two integers using bitwise operations.\n \"\"\"\n... | trial_gpt4o_2 | {
"original_instruction": "### Question: Optimizing GCD Calculation with Enhanced Requirements\n\nYou've learned about the Euclid's algorithm and a bitwise variant of it for calculating the Greatest Common Divisor (GCD) of two integers. Now, let's take this a step further. We will enhance the requirements to handle a... | 0.74558 | Data_Structure_8238 | C | [
"gcd_bit",
"pairwise_gcd"
] | 2 | [
[
"pairwise_gcd",
"gcd_bit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cd7a1377abd601e16b8ec9a3dcb2fdfe058f2d6a | 10129fb0e3cb8d1744ad8f84d7024651dcee8f34 | |||
v1.0 | complete | Data_Structure | Data_Structure_8776_C | def validate_diffie_hellman(a: int, p: int) -> bool:
""" Secure Key Exchange with Diffie-Hellman
Given a candidate primitive root `a` and a large prime number `p`, validate the process of securely generating
and exchanging keys between two parties, Alice and Bob.
Returns `True` if the key exchange proce... | def is_prime(n):
"""Check if a number is a 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 po... | from solution import validate_diffie_hellman, is_prime, find_primitive_root, diffie_hellman_key_exchange
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(23) == True
assert is_prime(24) == False
def test_find_primitive_root():
... | [
{
"docstring": "Check if a number is a prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Compute (base^exp) % mod efficiently.",
"function_declaration": "def power_modulo(base, exp, mod):",
"function_name": "p... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Checks if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n ... | trial_gpt4o_5 | {
"original_instruction": "Secure Key Exchange with Diffie-Hellman\n\nGiven an implementation of the Diffie-Hellman key exchange protocol, you need to write a function that validates the process of securely generating and exchanging keys between two parties, Alice and Bob.\n\n#### Function Signature\n```python\ndef v... | 0.482316 | Data_Structure_8776 | C | [
"is_prime",
"power_modulo",
"find_primitive_root",
"diffie_hellman_key_exchange",
"validate_diffie_hellman"
] | 5 | [
[
"diffie_hellman_key_exchange",
"is_prime"
],
[
"diffie_hellman_key_exchange",
"power_modulo"
],
[
"find_primitive_root",
"is_prime"
],
[
"find_primitive_root",
"power_modulo"
],
[
"validate_diffie_hellman",
"diffie_hellman_key_exchange"
],
[
"validat... | 7 | [] | false | [] | false | pytest | true | [] | true | f36a5b842a0cfef352a1e741cf4b1a8688574d69 | 5ed307b761eedf7d22dc049f077131b772ce010c | |||
v1.0 | complete | Data_Structure | Data_Structure_7912_C | from typing import List
def ternary_search(left: int, right: int, key: int, arr: List[int]) -> int:
""" Perform ternary search on a sorted array.
Args:
left (int): The left index of the search range.
right (int): The right index of the search range.
key (int): The value to search for.
arr (List... | from typing import List
import time
def ternary_search(left: int, right: int, key: int, arr: List[int]) -> int:
if right >= left:
mid1 = left + (right - left) // 3
mid2 = right - (right - left) // 3
if arr[mid1] == key:
return mid1
if arr[mid2] == key:
... | from solution import ternary_search, binary_search
import random
def test_ternary_search_exists():
arr = sorted(random.sample(range(1, 10**5), 10**3))
key = arr[500] # Guarantee key exists
assert ternary_search(0, len(arr)-1, key, arr) != -1
def test_ternary_search_not_exists():
arr = sorted(random.s... | [
{
"docstring": null,
"function_declaration": "def ternary_search(left, right, key, arr):",
"function_name": "ternary_search",
"parameter_list": "(left, right, key, arr)"
},
{
"docstring": null,
"function_declaration": "def binary_search(left, right, key, arr):",
"function_name": "bin... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nfrom typing import List\n\ndef ternary_search(left: int, right: int, key: int, arr: List[int]) -> int:\n \"\"\"\n Perform ternary search on... | trial_gpt4o_1 | {
"original_instruction": "### Ternary Search vs Binary Search: Performance Comparison\n\n#### Objective\nImplement a function to perform ternary search and compare its performance with binary search on large sorted arrays. Your task is to write effective search functions for both algorithms and determine which is fa... | 0.616843 | Data_Structure_7912 | C | [
"ternary_search",
"binary_search",
"compare_search_performance"
] | 3 | [
[
"compare_search_performance",
"binary_search"
],
[
"compare_search_performance",
"ternary_search"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 69c7db00859b8259af461c8facd2b197bebcfc2d | 71b0996ac2382b8507fa5bcb4ac1a2956c68c646 | |||
v1.0 | complete | Data_Structure | Data_Structure_7422_C | from typing import List
def counting_sort(arr, exp):
"""
Perform a counting sort on arr based on the digit represented by exp.
"""
pass
def radix_sort(arr: List[int]) -> List[int]:
"""
Given an array of non-negative integers, implement the Radix Sort algorithm
to sort the array in ascendi... | def counting_sort(arr, exp):
"""
Perform a counting sort on arr based on the digit represented by exp.
"""
n = len(arr)
output = [0] * n
count = [0] * 10
# Store the count of occurrences of digits
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
... | from solution import radix_sort
def test_radix_sort_example():
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([5]) == [5]
def test_radix_sort_identi... | [
{
"docstring": "Perform a counting sort on arr based on the digit represented by exp.",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "Perform LSD Radix Sort on arr.",
"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": "from typing import List\n\ndef counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \n for i in range(n):\n i... | trial_gpt4o_2 | {
"original_instruction": "### Question\nGiven an array of non-negative integers, implement the Radix Sort algorithm to sort the array in ascending order. Your implementation should follow the least significant digit (LSD) radix sort approach. Write a Python function `radix_sort(arr)` which takes an array `arr` as an... | 0.669556 | Data_Structure_7422 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e2e6d9b0ef2aa66d38d90d874f1e372840af1ae1 | 3143592c18928b351067229d24b88df4f0e643ef | |||
v1.0 | complete | Data_Structure | Data_Structure_8944_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""Sorts the array using merge sort algorithm.
>>> merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
>>> merge_sort([]) == []
>>> merge_sort([1]) == [1]
>>> merge_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
>>>... | from typing import List
def merge(left: List[int], right: List[int], merged: List[int]) -> None:
"""Merge two sorted sublists left and right into merged in sorted order."""
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged[k] = left[i]
i +=... | from solution import merge_sort
def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_identical_elements():
assert merge_sort([7, 7, 7, 7, 7]) == [7, 7, 7, 7, 7]
def test_merge_sort_sorted_array():
asser... | [
{
"docstring": "Merge two sorted sublists left and right into merged in sorted order.",
"function_declaration": "def merge(left, right, merged):",
"function_name": "merge",
"parameter_list": "(left, right, merged)"
},
{
"docstring": "Sorts the array using merge sort algorithm.",
"functio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_ha... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Implementation Exercise\n\n**Background**:\nMerge Sort is a classic sorting algorithm that employs a divide-and-conquer approach to sort elements in an array. The algorithm recursively splits the array into smaller subarrays until subarrays of size one are obtained. It then m... | 0.640696 | Data_Structure_8944 | C | [
"merge",
"merge_sort"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | edd3dafa023ed77ed5970f0d5392a4a5fdebf918 | 0562e777be14a1814c70179a6a27b857b62f3b85 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.