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_37311_C | def hybrid_quick_sort(arr):
""" Implement a hybrid Quicksort which improves the standard Quicksort by incorporating
Insertion Sort for small partitions and selecting a median-of-three pivot to avoid
worst-case performance.
:param arr: A list of integers to be sorted
:return: A list of integ... | def insertion_sort(arr, left, right):
"""
Performs insertion sort on the subarray of arr from index left to right.
"""
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + ... | from solution import hybrid_quick_sort
def test_hybrid_quick_sort_normal_case():
assert hybrid_quick_sort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10]
def test_hybrid_quick_sort_empty_list():
assert hybrid_quick_sort([]) == []
def test_hybrid_quick_sort_single_element():
assert hybrid_quick_sort([1]... | [
{
"docstring": "Performs insertion sort on the subarray of arr from index left to right.",
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": "Returns the index of the median of the firs... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insertion_sort(arr, left, right):\n \"\"\"\n Performs insertion sort on the subarray of arr from index left to right.\n \"\"\"\n for i in rang... | trial_gpt4o_0 | {
"original_instruction": "Implement a Hybrid Quicksort\n\n#### Objective\nImplement a hybrid Quicksort which improves the standard Quicksort by incorporating Insertion Sort for small partitions and selecting a median-of-three pivot to avoid worst-case performance.\n\n#### Problem Statement\nWrite a function `hybrid_... | 0.6054 | Data_Structure_37311 | C | [
"insertion_sort",
"median_of_three",
"quick_sort",
"hybrid_quick_sort"
] | 4 | [
[
"hybrid_quick_sort",
"quick_sort"
],
[
"quick_sort",
"insertion_sort"
],
[
"quick_sort",
"median_of_three"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 4e2bc3e4569579c9659959036c7860dfad6101fe | 886f673d76340405b09a63e0e8e3a7f5c40eb92b | |||
v1.0 | complete | Data_Structure | Data_Structure_36664_C | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def rotate_right(head: ListNode, k: int) -> ListNode:
""" Rotate the singly linked list to the right by `k` places.
Args:
head (ListNode): The head node of the singly linked list.
k (int): An integ... | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def get_length(head):
count = 0
while head:
count += 1
head = head.next
return count
def rotate_right(head, k):
if not head or not head.next or k == 0:
return head
# G... | from solution import ListNode, rotate_right
def linked_list_to_list(head):
""" Helper function to convert linked list to list """
lst = []
while head:
lst.append(head.val)
head = head.next
return lst
def list_to_linked_list(lst):
""" Helper function to convert list to linked list "... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef get_length(head):\n count = 0\n whil... | trial_gpt4o_0 | {
"original_instruction": "### Rotation of Singly Linked List\n\n#### Context:\nGiven a singly linked list, you are tasked with rotating the list to the right by a given number of places `k`. This problem is crucial for understanding the manipulation of linked list structures and optimizing rotational computations.\n... | 0.632581 | Data_Structure_36664 | C | [
"get_length",
"rotate_right"
] | 2 | [
[
"rotate_right",
"get_length"
]
] | 1 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | 5259e1440b6982127d44f5f80ed298b36598e85f | fe993c785cb4d10231c7fcc60426eb4521aeca65 | |||
v1.0 | complete | Data_Structure | Data_Structure_36938_C | def enhanced_sort(arr, T):
""" Implement an enhanced version of Pancake Sort with customizable threshold.
The function should sort the input list `arr` using Pancake Sort. If the length of `arr` exceeds the threshold `T`,
it should first sort the array using another sorting algorithm like QuickSort be... | def pancake_sort(arr):
def flip(sublist, k):
return sublist[:k][::-1] + sublist[k:]
n = len(arr)
for i in range(n, 1, -1):
max_idx = arr.index(max(arr[:i]))
if max_idx != i - 1:
if max_idx != 0:
arr = flip(arr, max_idx + 1)
arr = flip(arr, i)
... | from solution import enhanced_sort
def test_enhanced_sort_small_array_no_threshold():
assert enhanced_sort([3, 1, 2], 3) == [1, 2, 3]
def test_enhanced_sort_small_array_with_threshold():
assert enhanced_sort([3, 1, 2], 2) == [1, 2, 3]
def test_enhanced_sort_large_array_with_threshold():
assert enhanced_s... | [
{
"docstring": null,
"function_declaration": "def pancake_sort(arr):",
"function_name": "pancake_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"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 pancake_sort(arr):\n def flip(sublist, k):\n sublist[:k] = reversed(sublist[:k])\n\n n = len(arr)\n for size in range(n, 1, -1):\n ... | trial_gpt4o_2 | {
"original_instruction": "### Pancake Sort Enhancement\n\nYou are required to implement an enhanced version of the Pancake Sort algorithm. The goal is to incorporate the following additional functionality:\n* **Enhanced Performance**: Implement a preliminary step that uses a more efficient sorting method (e.g., Quic... | 0.718404 | Data_Structure_36938 | C | [
"pancake_sort",
"quicksort",
"enhanced_sort"
] | 3 | [
[
"enhanced_sort",
"pancake_sort"
],
[
"enhanced_sort",
"quicksort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 55a1c4dd5e95bfa89999ec592825346661723995 | 7b735f5cfdb3ede9ea04ef31efc4b17da166dd67 | |||
v1.0 | complete | Data_Structure | Data_Structure_37764_C | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_subtree(big: TreeNode, small: TreeNode) -> bool:
""" Return True if 'small' is a subtree of 'big', False otherwise. """ | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_subtree(big, small):
if not small:
return True
if not big:
return False
if is_same_tree(big, small):
return True
return is_subtree(big.left, small) or i... | from solution import TreeNode, is_subtree
def test_same_tree_structure1():
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
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": "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": "### Function Implementation: Subtree Checker\n\n**Context**:\nConsider a scenario where you are working with hierarchical data representations using binary trees. With given two binary trees s and t, you need to verify if t is a subtree of s. A subtree of s is defined as a tree consisting o... | 0.492913 | Data_Structure_37764 | C | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 4e7684ad4fcc9001e5534c04b1a6fc639f2b7a7e | e76602e57ec972160907b822e2b66294f7cc4bf0 | |||
v1.0 | complete | Data_Structure | Data_Structure_36870_C | def exchange_sort(arr: list) -> list:
"""
Sorts the list arr using the Exchange Sort algorithm.
:param arr: List of integers to sort.
:return: Sorted list of integers.
"""
# Your implementation here
def optimized_sort(arr: list) -> list:
"""
Sorts the list arr using an optimized sortin... | def exchange_sort(arr: list) -> list:
"""
Sorts the list arr using the Exchange Sort algorithm.
:param arr: List of integers to sort.
:return: Sorted list of integers.
"""
# Exchange Sort Implementation
n = len(arr)
for i in range(n):
for j in range(i+1, n):
if arr[i... | from solution import exchange_sort, optimized_sort
def test_exchange_sort_empty():
assert exchange_sort([]) == []
def test_exchange_sort_single_element():
assert exchange_sort([1]) == [1]
def test_exchange_sort_sorted_list():
assert exchange_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_exchange_sor... | [
{
"docstring": "Sorts the list arr using the Exchange Sort algorithm.\n\n:param arr: List of integers to sort.\n:return: Sorted list of integers.",
"function_declaration": "def exchange_sort(arr):",
"function_name": "exchange_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the list... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def exchange_sort(arr):\n \"\"\"\n Sorts the list arr using the Exchange Sort algorithm.\n \n :param arr: List of integers to sort.\n :return: ... | trial_gpt4o_2 | {
"original_instruction": "### Sorting Adventure: Implementing and Enhancing the Exchange Sort Algorithm\n\nOne day, you're approached by a friend who is learning about sorting algorithms. They have written a simple sorting algorithm called \"Exchange Sort\" but are curious about its efficiency and possible improveme... | 0.597228 | Data_Structure_36870 | C | [
"exchange_sort",
"optimized_sort",
"merge"
] | 3 | [
[
"optimized_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 72ec5fb32a9b93c6310770a6f8211fedf95648cc | 40b35b580a441477589db899b42a3a4e4bc2eee1 | |||
v1.0 | complete | Data_Structure | Data_Structure_37340_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
""" Sorts an array of integers in ascending order using the merge sort algorithm.
>>> merge_sort([4, 1, 3, 9, 7])
[1, 3, 4, 7, 9]
>>> merge_sort([])
[]
>>> merge_sort([1])
[1]
>>> merge_sort([1, 2, 3, 4... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers in ascending order using the merge sort algorithm.
"""
if len(arr) <= 1: # Base case: arrays with 0 or 1 element are already sorted
return arr
# Find the middle point to divide the... | from solution import merge_sort
def test_merge_sort_unsorted_array():
assert merge_sort([4, 1, 3, 9, 7]) == [1, 3, 4, 7, 9]
def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merge_sort_single_element_array():
assert merge_sort([1]) == [1]
def test_merge_sort_already_sorted_array():... | [
{
"docstring": "Sorts an array of integers in ascending order using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into a single sorted list.",
"function_decla... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sort the array in ascending order using the merge sort algorithm.\n ... | trial_gpt4o_1 | {
"original_instruction": "### Merge Sort Implementation Challenge\n\n**Context**:\nA software company is building an application to handle large datasets efficiently. One crucial feature is to ensure data is sorted rapidly, regardless of the input's initial order. Merge Sort is selected for its predictable performan... | 0.641691 | Data_Structure_37340 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1c1e9d3b93beaf6308a2754a9daa9a2ea6b02e83 | 5b504e35ac5c261c20ab63469f9462d04a2e954b | |||
v1.0 | complete | Data_Structure | Data_Structure_36897_C | from typing import List
def search_insert(array: List[int], value: int) -> int:
"""
Finds the index where the value should be inserted to keep the array sorted.
"""
pass
def optimized_insertion_sort(array: List[int]) -> List[int]:
"""
Sorts an array of integers using an optimized insertion so... | from bisect import bisect_left
from typing import List
def search_insert(array: List[int], value: int) -> int:
"""
Finds the index where the value should be inserted to keep the array sorted.
"""
return bisect_left(array, value)
def optimized_insertion_sort(array: List[int]) -> List[int]:
"""
... | from solution import optimized_insertion_sort
def test_optimized_insertion_sort_basic():
assert optimized_insertion_sort([4, 2, 9, 1]) == [1, 2, 4, 9]
assert optimized_insertion_sort([3, 3, 3]) == [3, 3, 3]
assert optimized_insertion_sort([]) == []
assert optimized_insertion_sort([10, -1, 2]) == [-1, 2... | [
{
"docstring": "Finds the index where the value should be inserted to keep the array sorted.",
"function_declaration": "def search_insert(array, value):",
"function_name": "search_insert",
"parameter_list": "(array, value)"
},
{
"docstring": "Sorts an array of integers using an optimized ins... | [
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], value: int) -> int:\n \"\"\"\n Helper function to find the insertion index of value withi... | trial_gpt4o_2 | {
"original_instruction": "### Coding Challenge: Optimized Insertion Sort\n\nYou are tasked with implementing an optimized version of the Insertion Sort algorithm using the provided `search_insert` helper function to find the correct position for each element during sorting.\n\n#### Function Specification\nDefine a f... | 0.665484 | Data_Structure_36897 | C | [
"search_insert",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 529187950c39cf5612cc197f0f669d61284dbbaf | 8496e3ef7c205a0fccacd6feb385c97c4e1aad15 | |||
v1.0 | complete | Data_Structure | Data_Structure_37227_C | def compute_gcd(a, b):
"""
Returns the greatest common divisor of a and b using the Euclidean algorithm.
>>> compute_gcd(14, 21) 7
>>> compute_gcd(100, 10) 10
>>> compute_gcd(-14, 21) 7
>>> compute_gcd(0, 5) 5
>>> compute_gcd(5, 0) 5
"""
def compute_lcm(a, b):
"""
Returns the le... | def compute_gcd(a, b):
"""
Returns the greatest common divisor of a and b using the Euclidean algorithm.
"""
a, b = abs(a), abs(b)
while b:
a, b = b, a % b
return a
def compute_lcm(a, b):
"""
Returns the least common multiple of a and b.
"""
a, b = abs(a), abs(b)
ret... | from solution import compute_gcd, compute_lcm, count_trailing_zeros, compute_gcd_bit
def test_compute_gcd():
assert compute_gcd(14, 21) == 7
assert compute_gcd(100, 10) == 10
assert compute_gcd(-14, 21) == 7
assert compute_gcd(0, 5) == 5
assert compute_gcd(5, 0) == 5
def test_compute_lcm():
as... | [
{
"docstring": "Returns the greatest common divisor of a and b using the Euclidean algorithm.",
"function_declaration": "def compute_gcd(a, b):",
"function_name": "compute_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the least common multiple of a and b.",
"function_declar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def compute_gcd(a, b):\n \"\"\"\n Returns the greatest common divisor of a and b using the Euclidean algorithm.\n \"\"\"\n a, b = abs(a), abs(b)\n... | trial_gpt4o_2 | {
"original_instruction": "### Question:\nAs a software developer, you are tasked with implementing a custom utility that performs multiple numerical computations. Specifically, your utility should include functions for calculating the GCD, LCM, and the number of trailing zeros of binary representations of integers. ... | 0.732366 | Data_Structure_37227 | C | [
"compute_gcd",
"compute_lcm",
"count_trailing_zeros",
"compute_gcd_bit"
] | 4 | [
[
"compute_lcm",
"compute_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 69a8e2b9010b6a0028e6eb09454ab73f1812b952 | 878d4c47ab38d50d744fe5c77035f91a34287db2 | |||
v1.0 | complete | Data_Structure | Data_Structure_37757_C | from typing import List
def gcd(a, b):
"""Compute the Greatest Common Divisor of a and b."""
while b:
a, b = b, a % b
return a
def are_pairwise_coprime(nums: List[int]) -> bool:
"""Check if a list of numbers are pairwise coprime."""
pass
def extended_gcd(a, b):
"""Extended Euclidean A... | from typing import List
def gcd(a, b):
while b:
a, b = b, a % b
return a
def are_pairwise_coprime(nums: List[int]) -> bool:
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if gcd(nums[i], nums[j]) != 1:
return False
return True
def extended_g... | import pytest
from solution import efficient_solve_chinese_remainder, gcd, are_pairwise_coprime
def test_gcd():
assert gcd(48, 18) == 6
assert gcd(101, 103) == 1
assert gcd(20, 8) == 4
def test_are_pairwise_coprime():
assert are_pairwise_coprime([3, 5, 7]) == True
assert are_pairwise_coprime([4, 5... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def are_pairwise_coprime(nums):",
"function_name": "are_pairwise_coprime",
"parameter_list": "(nums)"
},
{
"d... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom math import gcd\n\ndef pairwise_coprime(nums: List[int]) -> bool:\n for i in range(len(nums)):\n for j in range(i + 1,... | trial_gpt4o_6 | {
"original_instruction": "### Coding Challenge: Efficient CRT Solver with Pairwise Coprime Check\n\n**Scenario**:\nIn a digital security exercise, you need to solve a series of simultaneous congruences using the Chinese Remainder Theorem (CRT). The system is secure only when the moduli of the congruences are pairwis... | 0.657874 | Data_Structure_37757 | C | [
"gcd",
"are_pairwise_coprime",
"extended_gcd",
"efficient_solve_chinese_remainder"
] | 4 | [
[
"are_pairwise_coprime",
"gcd"
],
[
"efficient_solve_chinese_remainder",
"are_pairwise_coprime"
],
[
"efficient_solve_chinese_remainder",
"extended_gcd"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | c59e72678842dbad4481df5a042bb676d01dfcdf | e33f368d2b94223162ecefa57cef217720d54342 | |||
v1.0 | complete | Data_Structure | Data_Structure_36970_C | from typing import List, Tuple
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
""" Compute the Extended GCD of two numbers, `a` and `b`.
Returns a tuple of three integers: coefficients of Bézout's identity and the gcd of `a` and `b`.
>>> extended_gcd(30, 20) (1, -1, 10)
>>> extended_gcd(... | from typing import List, Tuple
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
old_s, s = 1, 0
old_t, t = 0, 1
old_r, r = a, b
while r != 0:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t = t, old_t - quoti... | from solution import modular_inverse_message, extended_gcd, modular_inverse
def test_extended_gcd():
assert extended_gcd(30, 20) == (1, -1, 10)
assert extended_gcd(240, 46) == (-9, 47, 2)
def test_modular_inverse():
assert modular_inverse(3, 11) == 4
assert modular_inverse(10, 17) == 12
def test_modu... | [
{
"docstring": null,
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def modular_inverse(a, m):",
"function_name": "modular_inverse",
"parameter_list": "(a, m)"
},
... | [
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": "from typing import List, Tuple\n\ndef modular_inverse_message(a: int, m: int, encrypted_message: List[int]) -> Tuple[int, List[int]]:\n # Extended GCD func... | trial_gpt4o_7 | {
"original_instruction": "Your task is to implement a function that will secure communication in a simple text-based encryption system. The system encrypts messages using modular arithmetic. To do so, you need to:\n\n1. Compute the inverse of a given number `a` under modulo `m`.\n2. Use the Extended Euclidean Algori... | 0.642824 | Data_Structure_36970 | C | [
"extended_gcd",
"modular_inverse",
"modular_inverse_message"
] | 3 | [
[
"modular_inverse",
"extended_gcd"
],
[
"modular_inverse_message",
"modular_inverse"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | becff8f75f8cb28454401de6cb8904b5ebfaf9b7 | 63270858a76280160be41210fd35c70d542e0c98 | |||
v1.0 | complete | Data_Structure | Data_Structure_37985_C | import random
from typing import Optional, Tuple
def generate_key(k: int, seed: Optional[int] = None) -> Tuple[int, int, int]:
"""
Enhanced RSA key generating algorithm.
k : int : the number of bits in n.
seed : int, optional : Seed for reproducibility.
Returns tuple(n, e, d)
>>> n, e, d = gen... | import random
from sympy import isprime
def generate_key(k, seed=None):
"""
Enhanced RSA key generating algorithm.
k : int : the number of bits in n.
seed : int, optional : Seed for reproducibility.
Returns tuple(n, e, d)
"""
if seed is not None:
random.seed(seed)
def gener... | from solution import generate_key, modinv
def test_generate_key():
n, e, d = generate_key(16, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
data = 20
encrypted = pow(data, e, n)
decrypted = pow(encrypted, d, n)
assert decrypted == data
def test_... | [
{
"docstring": "Enhanced RSA key generating algorithm.\nk : int : the number of bits in n.\nseed : int, optional : Seed for reproducibility.\nReturns tuple(n, e, d)",
"function_declaration": "def generate_key(k, seed=None):",
"function_name": "generate_key",
"parameter_list": "(k, seed=None)"
},
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime\nfrom sympy.ntheory import nextprime\n\ndef generate_prime_candidate(bit_size):\n \"\"\" Generate an odd integer r... | trial_gpt4o_2 | {
"original_instruction": "### Context\nYou are tasked with improving the RSA encryption key generation process to address two primary issues: performance and security.\n\n### Problem Statement\nEnhance the `generate_key` function to make the RSA key generation process more efficient and secure. Specifically, you nee... | 0.689261 | Data_Structure_37985 | C | [
"generate_key",
"modinv",
"extended_gcd"
] | 3 | [
[
"generate_key",
"modinv"
],
[
"modinv",
"extended_gcd"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | fde897863913096d2a5a93d4fdec0d2ccf85e377 | b11796ac47aebe8785a70b897d9bacde35176edc | |||
v1.0 | complete | Data_Structure | Data_Structure_37824_C | from typing import List
def enhanced_invert_matrix(matrix: List[List[float]]) -> List[List[float]]:
""" Enhance the existing algorithm to improve performance and handle additional edge cases
when inverting an n x n matrix.
Arguments:
matrix -- A 2D list of floats representing an n x n matrix.
... | from typing import List
def calculate_determinant(matrix: List[List[float]]) -> float:
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
determinant = 0
for c in range(n):
determinant += ((-1) ** c... | from solution import enhanced_invert_matrix
def test_non_square_matrix():
matrix = [
[1, 2],
[3, 4, 5]
]
assert enhanced_invert_matrix(matrix) == [[0]]
def test_singular_matrix():
matrix = [
[4, 2],
[2, 1]
]
assert enhanced_invert_matrix(matrix) == [[1]]
def te... | [
{
"docstring": null,
"function_declaration": "def calculate_determinant(matrix):",
"function_name": "calculate_determinant",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def get_minor(matrix, i, j):",
"function_name": "get_minor",
"parameter_list"... | [
0,
0,
0,
1,
1,
0,
1,
0,
1,
1
] | 5 | medium | 0.5 | {
"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 matrix_determinant(matrix: List[List[float]], n: int) -> float:\n if n == 1:\n return matrix[0][0]\n if ... | trial_gpt4o_9 | {
"original_instruction": "### Matrix Inversion\n\nYou are provided with an algorithm that inverts an \\(n \\times n\\) matrix. The matrix inversion algorithm includes calculating the matrix of minors, creating the matrix of cofactors, adjugating, and scaling by the inverse of the determinant. Your task is to enhance... | 0.542125 | Data_Structure_37824 | C | [
"calculate_determinant",
"get_minor",
"transpose",
"cofactor",
"enhanced_invert_matrix"
] | 5 | [
[
"calculate_determinant",
"get_minor"
],
[
"cofactor",
"calculate_determinant"
],
[
"cofactor",
"get_minor"
],
[
"enhanced_invert_matrix",
"calculate_determinant"
],
[
"enhanced_invert_matrix",
"cofactor"
],
[
"enhanced_invert_matrix",
"transpose"... | 6 | [] | false | [] | false | pytest | true | [] | true | 789582c17230443dc8e69b590ced3cf897bdf48d | b810121cdc8c6bed950d5985f47d298ed2c979a4 | |||
v1.0 | complete | Data_Structure | Data_Structure_37877_C | from typing import List
def optimized_quick_sort(arr: List[int]) -> List[int]:
"""
Sort an array using an optimized Quick Sort algorithm.
This optimization involves using a median-of-three method to choose the pivot
and switching to Insertion Sort when the subarray size falls below a certain threshold... | def insertion_sort(arr, low, high):
for i in range(low + 1, high + 1):
key = arr[i]
j = i - 1
while j >= low and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def median_of_three(arr, low, high):
mid = (low + high) // 2
if arr[low] > arr[m... | from solution import optimized_quick_sort
def test_single_element():
assert optimized_quick_sort([1]) == [1]
def test_already_sorted():
assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted():
assert optimized_quick_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_rand... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, low, high):",
"function_name": "insertion_sort",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
... | [
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 insertion_sort(arr, low, high):\n for i in range(low + 1, high + 1):\n key = arr[i]\n j = i - 1\n while j >= low and key < arr[j]:... | trial_gpt4o_2 | {
"original_instruction": "You are given an array of integers. Your task is to implement an optimized Quick Sort algorithm. The optimization should involve using a median-of-three method to choose the pivot and switching to Insertion Sort when the subarray size falls below a certain threshold.\n\n### Input:\n* An int... | 0.639235 | Data_Structure_37877 | C | [
"insertion_sort",
"median_of_three",
"quick_sort",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"quick_sort"
],
[
"quick_sort",
"insertion_sort"
],
[
"quick_sort",
"median_of_three"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ccd7d7aad0af2e1d404223e535082fa77ba9e3e0 | d3f848be2506f5e01bb60002b67055a0f16b0a30 | |||
v1.0 | complete | Data_Structure | Data_Structure_37430_C | from typing import List
def advanced_radix_sort(arr: List[int], simulation=False) -> List[int]:
"""
Implement a specialized version of the radix sort algorithm that handles
both positive and negative integers. The function should arrange all negative
numbers before positive numbers, with both groups so... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool = False) -> List[int]:
n = len(arr)
output = [0] * n # output array that will have the sorted elements
count = [0] * 10 # count array to store count of occurrences of each digit
# Count occurrences of each digit
... | from solution import advanced_radix_sort
def test_basic():
arr = [3, -1, 2]
assert advanced_radix_sort(arr) == [-1, 2, 3]
def test_mixed():
arr = [170, -45, 75, -90, 802, 24, 2, 66]
assert advanced_radix_sort(arr) == [-90, -45, 2, 24, 66, 75, 170, 802]
def test_all_negative():
arr = [-5, -1, -3, ... | [
{
"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":... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr, exp, simulation=False):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \n if simulati... | trial_gpt4o_6 | {
"original_instruction": "You are tasked with implementing a specialized version of the radix sort algorithm that deals with positive and negative integers. Your solution should handle input arrays containing both types of integers, correctly ordering them such that all negative numbers appear before the positive nu... | 0.663428 | Data_Structure_37430 | C | [
"counting_sort",
"radix_sort",
"advanced_radix_sort"
] | 3 | [
[
"advanced_radix_sort",
"radix_sort"
],
[
"radix_sort",
"counting_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b8c20c79966ea7501855e83b6344c3a6e86e77b8 | 3a8a6f78702ddad212d0c6a911679c1e718b3a96 | |||
v1.0 | complete | Data_Structure | Data_Structure_38143_C | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def check_palindrome(head: ListNode) -> bool:
""" Determine if a singly linked list is a palindrome.
Given a singly linked list, determine if the list is a palindrome.
A list is considered a palin... | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_list(head: ListNode) -> ListNode:
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
... | from solution import ListNode, check_palindrome
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_single_element():
hea... | [] | [
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 check_palindrome(head: ListNode) -> bool:\... | trial_gpt4o_2 | {
"original_instruction": "### Linked List Palindrome Checker\n\n#### Objective\nGiven a singly linked list, you need to determine if the list is a palindrome. A list is considered a palindrome if it reads the same forwards and backwards.\n\n#### Function Specifications\nImplement the function `def check_palindrome(h... | 0.697789 | Data_Structure_38143 | C | [
"reverse_list",
"check_palindrome"
] | 2 | [
[
"check_palindrome",
"reverse_list"
]
] | 1 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | 715e546b4c551764b7dd02d3bec837fae9984d43 | 2944687d007706aacfbe4ef7cd77af20abcc1196 | |||
v1.0 | complete | Data_Structure | Data_Structure_37439_C | def optimized_quick_sort(arr):
"""
Sorts an array using the optimized quick sort algorithm.
Arguments:
arr : list of integers -- the array to be sorted.
Returns:
list of integers -- the sorted array.
"""
pass
# Helper functions (you may modify if necessary)
def median_of_three... | def optimized_quick_sort(arr):
"""
Sorts an array using the optimized quick sort algorithm.
Arguments:
arr : list of integers -- the array to be sorted.
Returns:
list of integers -- the sorted array.
"""
if len(arr) <= 1:
return arr
_quick_sort(arr, 0, len(arr) - 1)... | from solution import optimized_quick_sort
def test_optimized_quick_sort_empty():
assert optimized_quick_sort([]) == []
def test_optimized_quick_sort_single_element():
assert optimized_quick_sort([1]) == [1]
def test_optimized_quick_sort_sorted():
assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, ... | [
{
"docstring": "Sorts an array using the optimized quick sort algorithm.\n\nArguments:\narr : list of integers -- the array to be sorted.\n\nReturns:\nlist of integers -- the sorted array.",
"function_declaration": "def optimized_quick_sort(arr):",
"function_name": "optimized_quick_sort",
"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 optimized_quick_sort(arr):\n \"\"\"\n Sorts an array using the optimized quick sort algorithm.\n \n Arguments:\n arr : list of integers -- ... | trial_gpt4o_1 | {
"original_instruction": "### Coding Task: Implement Optimized Quick Sort with Improved Pivot Selection\n\n#### Scenario\nYou are tasked to implement an optimized version of the Quick Sort algorithm. Your implementation should address potential performance bottlenecks related to pivot selection and small arrays. \n\... | 0.611232 | Data_Structure_37439 | C | [
"optimized_quick_sort",
"_quick_sort",
"median_of_three",
"partition",
"insertion_sort"
] | 5 | [
[
"_quick_sort",
"insertion_sort"
],
[
"_quick_sort",
"median_of_three"
],
[
"_quick_sort",
"partition"
],
[
"optimized_quick_sort",
"_quick_sort"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | dbec8faec4957f08583d850e63e31da7b0ab3129 | 5ed426347fe25a548a0309d5f83e89104d14c735 | |||
v1.0 | complete | Data_Structure | Data_Structure_37197_C | import random
from math import gcd
from sympy import isprime, totient
def prime_check(num):
""" Check if a given number is prime.
>>> prime_check(11)
True
>>> prime_check(10)
False
"""
def find_order(a, n):
""" Returns the order of `a` modulo `n`. If it does not exist, return -1.
>>> f... | import random
from math import gcd
from sympy import isprime, totient, primerange
def prime_check(num):
return isprime(num)
def find_order(a, n):
if gcd(a, n) != 1:
return -1
order = 1
current = a % n
while current != 1:
current = (current * a) % n
order += 1
return ord... | import pytest
from solution import (
prime_check,
find_order,
euler_totient,
find_primitive_root,
alice_private_key,
alice_public_key,
bob_private_key,
bob_public_key,
alice_shared_key,
bob_shared_key,
diffie_hellman_key_exchange
)
def test_prime_check():
asser... | [
{
"docstring": null,
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def find_order(a, n):",
"function_name": "find_order",
"parameter_list": "(a, n)"
},
{
"docstri... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom math import gcd\nfrom sympy import isprime, totient, primerange\n\ndef prime_check(num):\n return isprime(num)\n\ndef find_order(a, n):... | trial_gpt4o_0 | {
"original_instruction": "**Diffie-Hellman Key Exchange Implementation**\n\nAlice and Bob want to establish a shared secret key using the Diffie-Hellman key exchange protocol. Given a large prime number `p` and a number `a` which is a primitive root of `p`, they want to perform the key exchange securely.\n\nYou are ... | 0.588718 | Data_Structure_37197 | C | [
"prime_check",
"find_order",
"euler_totient",
"find_primitive_root",
"alice_private_key",
"alice_public_key",
"bob_private_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"diffie_hellman_key_exchange"
] | 11 | [
[
"diffie_hellman_key_exchange",
"alice_private_key"
],
[
"diffie_hellman_key_exchange",
"alice_public_key"
],
[
"diffie_hellman_key_exchange",
"alice_shared_key"
],
[
"diffie_hellman_key_exchange",
"bob_private_key"
],
[
"diffie_hellman_key_exchange",
"bob_pu... | 11 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 42baa0d9cb33f9f0c58e2f0d1dddeee921f79c24 | 7c027ce95c25478817a9b3aef1b327fa3f4c8c2d | |||
v1.0 | complete | Data_Structure | Data_Structure_36607_C | def select_max_flow_algorithm(capacity, source, sink, algorithm):
""" Determines and computes the maximum flow from source to sink using the specified algorithm.
Parameters:
capacity (List[List[int]]): A 2D list representing the capacity matrix of the graph.
source (int): The source vertex.
sink (i... | def ford_fulkerson(capacity, source, sink):
# Use DFS for Ford-Fulkerson
n = len(capacity)
residual = [row[:] for row in capacity]
parent = [-1] * n
def dfs_flow(u, flow):
if u == sink:
return flow
for v in range(n):
if parent[v] == -1 and residual[u][v] ... | from solution import select_max_flow_algorithm
def test_ford_fulkerson():
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 =... | [
{
"docstring": null,
"function_declaration": "def ford_fulkerson(capacity, source, sink):",
"function_name": "ford_fulkerson",
"parameter_list": "(capacity, source, sink)"
},
{
"docstring": null,
"function_declaration": "def edmonds_karp(capacity, source, sink):",
"function_name": "e... | [
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 ford_fulkerson(capacity, source, sink):\n def dfs(flow, capacity, source, sink, visited):\n visited[source] = True\n if source == sink:\n... | trial_gpt4o_1 | {
"original_instruction": "### Maximum Flow Calculation\n\n#### Problem Description\nYou have been provided with the implementation of three different maximum flow algorithms: Ford-Fulkerson using DFS, Edmonds-Karp using BFS, and Dinic's algorithm. To test your understanding, you are required to implement an addition... | 0.583227 | Data_Structure_36607 | C | [
"ford_fulkerson",
"edmonds_karp",
"dinic",
"select_max_flow_algorithm"
] | 4 | [
[
"select_max_flow_algorithm",
"dinic"
],
[
"select_max_flow_algorithm",
"edmonds_karp"
],
[
"select_max_flow_algorithm",
"ford_fulkerson"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | c133a3c1018133da9d4b44af9555c942ebe3715f | 210b0cd0a6eb53d20971a07589e62761570bbb34 | |||
v1.0 | complete | Data_Structure | Data_Structure_38034_C | from typing import List
import random
import time
def is_sorted(arr: List[int]) -> bool:
"""
Check if the array is sorted in ascending order.
Args:
arr (List[int]): The list of integers to check.
Returns:
bool: True if the list is sorted, False otherwise.
"""
return all(arr[i] <= arr[... | import random
import time
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Check if the array is sorted in ascending order.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def bogo_sort_timed(arr: List[int], timeout: int = 10) -> List[int]:
"""
Sorts the arr... | from solution import bogo_sort_timed
def test_bogo_sort_already_sorted():
assert bogo_sort_timed([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]
def test_bogo_sort_reverse_order():
res = bogo_sort_timed([5, 4, 3, 2, 1], 5)
assert res == sorted(res) # Since it might timeout, we check for being sorted
def test_bog... | [
{
"docstring": "Check if the array is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the array using Bogo Sort algorithm with added timeout functionality.\nIf the array cannot be sor... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport time\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Check if the array is sorted in ascending order... | trial_gpt4o_0 | {
"original_instruction": "### Bogo Sort Timing Challenge\n\nGiven the inefficiency and randomness of the Bogo Sort algorithm, it is critical to handle edge cases and understand its limitations. Your task is to implement an improved version of Bogo Sort that can identify certain optimizations and handle typical scena... | 0.623299 | Data_Structure_38034 | C | [
"is_sorted",
"bogo_sort_timed"
] | 2 | [
[
"bogo_sort_timed",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3d6a77c3117b80545ce84a7f19a6f06168ca9864 | 7db43a22fb068b8ceb3e602fa2efc0501bb6ea1c | |||
v1.0 | complete | Data_Structure | Data_Structure_37806_C | def reverse_string_recursive(s):
""" Reverse the string `s` using a recursive approach.
>>> reverse_string_recursive("") ""
>>> reverse_string_recursive("a") "a"
>>> reverse_string_recursive("ab") "ba"
>>> reverse_string_recursive("hello") "olleh"
>>> reverse_string_recursive("1234567890") "0987... | def reverse_string_recursive(s):
"""
Reverse the string `s` using a recursive approach.
Time complexity: O(n)
Space complexity: O(n) due to the recursive call stack
"""
if len(s) == 0:
return ""
else:
return s[-1] + reverse_string_recursive(s[:-1])
def reverse_string_iterati... | def test_reverse_string_recursive():
assert reverse_string_recursive("") == ""
assert reverse_string_recursive("a") == "a"
assert reverse_string_recursive("ab") == "ba"
assert reverse_string_recursive("hello") == "olleh"
assert reverse_string_recursive("1234567890") == "0987654321"
def test_rev... | [
{
"docstring": "Reverse the string `s` using a recursive approach.\nTime complexity: O(n)\nSpace complexity: O(n) due to the recursive call stack",
"function_declaration": "def reverse_string_recursive(s):",
"function_name": "reverse_string_recursive",
"parameter_list": "(s)"
},
{
"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 reverse_string_recursive(s):\n \"\"\"\n Returns the reverse of the string s using a recursive approach.\n \"\"\"\n if len(s) == 0:\n re... | trial_gpt4o_2 | {
"original_instruction": "**String Manipulation**: Write a function `reverse_string` that takes a single argument `s` (a string) and returns the string reversed.\n\n### Requirements\n1. Implement the function using at least three different methods: recursive, iterative, and a built-in Python function.\n2. Ensure you... | 0.705468 | Data_Structure_37806 | C | [
"reverse_string_recursive",
"reverse_string_iterative",
"reverse_string_builtin",
"reverse_string"
] | 4 | [
[
"reverse_string",
"reverse_string_builtin"
],
[
"reverse_string",
"reverse_string_iterative"
],
[
"reverse_string",
"reverse_string_recursive"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 252ae89ce59536cfa809f480fc56e425b998f832 | 81d543ceb30d429a2591f033004dcfe56bab39d7 | |||
v1.0 | complete | Data_Structure | Data_Structure_38340_C | from typing import List
def search_insert(arr: List[int], val: int, start: int, end: int) -> int:
"""
Uses binary search to find the index at which val should be inserted
in the subarray arr[start:end].
"""
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
s... | from typing import List
def search_insert(arr: List[int], val: int, start: int, end: int) -> int:
"""
Uses binary search to find the index at which val should be inserted
in the subarray arr[start:end].
"""
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
s... | from solution import binary_insertion_sort
def test_binary_insertion_sort_general_case():
assert binary_insertion_sort([4, 2, 9, 1, 5]) == [1, 2, 4, 5, 9]
def test_binary_insertion_sort_already_sorted():
assert binary_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_binary_insertion_sort_reverse_s... | [
{
"docstring": "Uses binary search to find the index at which val should be inserted\nin the subarray arr[start:end].",
"function_declaration": "def search_insert(arr, val, start, end):",
"function_name": "search_insert",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "Sorts th... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef binary_search(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Helper function to perform binary search... | trial_gpt4o_2 | {
"original_instruction": "You're given an integer array `arr` which needs to be sorted using a variant of insertion sort that employs binary search to find the correct insertion point efficiently. The overall algorithm should refine the searching step, though the insertion step remains standard. Implement the functi... | 0.672951 | Data_Structure_38340 | C | [
"search_insert",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4a02f3992e75d64c505e8963a1b4165e1e67bfa5 | e9a9027108d4ce786f0d609b54737a28d0e9730f | |||
v1.0 | complete | Data_Structure | Data_Structure_37218_C | from typing import List
def bitonic_sort(arr: List[int], reverse: bool = False) -> List[int]:
"""
Sort an array of numbers using the bitonic sort algorithm.
The function sorts the array in ascending order by default. If the reverse parameter is set to True, the array is sorted in descending order.
:... | from typing import List
def bitonic_merge(arr: List[int], low: int, cnt: int, direction: bool):
if cnt > 1:
k = cnt // 2
for i in range(low, low + k):
if (direction and arr[i] > arr[i + k]) or (not direction and arr[i] < arr[i + k]):
arr[i], arr[i + k] = arr[i + k], arr[... | def test_bitonic_sort_ascending():
assert bitonic_sort([3, 7, 4, 8, 6, 2, 1, 5], reverse=False) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_bitonic_sort_descending():
assert bitonic_sort([3, 7, 4, 8, 6, 2, 1, 5], reverse=True) == [8, 7, 6, 5, 4, 3, 2, 1]
def test_bitonic_sort_edge_case_single_element():
assert b... | [
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, low, cnt, direction):",
"function_name": "bitonic_merge",
"parameter_list": "(arr, low, cnt, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_sort_rec(arr, low, cnt, direction):",
"function_n... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bitonic_compare_and_swap(arr, i, j, ascending):\n if (ascending and arr[i] > arr[j]) or (not ascending and arr[i] < arr[j]):... | trial_gpt4o_1 | {
"original_instruction": "### Bitonic Sort Implementation\n\n#### Context:\nYou have a large dataset with a size that is guaranteed to be a power of two. This dataset can be sorted effectively using the bitonic sort algorithm, which divides and merges the array using the bitonic sequences for sorting. However, you n... | 0.689265 | Data_Structure_37218 | C | [
"bitonic_merge",
"bitonic_sort_rec",
"bitonic_sort"
] | 3 | [
[
"bitonic_sort",
"bitonic_sort_rec"
],
[
"bitonic_sort_rec",
"bitonic_merge"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 9fb24ed2788255e640f8fb0ac579f401b75b4a29 | 876e636b5cc170b4991e47f80ae1617f0557f1e2 | |||
v1.0 | complete | Data_Structure | Data_Structure_37784_C | from typing import List
def hybrid_sort(arr: List[int], threshold: int) -> List[int]:
"""
Sort a list of integers using a hybrid of merge sort and insertion sort.
If the sub-array size is less than or equal to the threshold, use insertion sort.
Args:
arr (List[int]): A list of integers to be... | from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def merge(left: List[int], right: List[int]... | import pytest
from solution import hybrid_sort
def test_hybrid_sort_small_array():
assert hybrid_sort([4, 1, 7, 0, 3], 2) == [0, 1, 3, 4, 7]
assert hybrid_sort([10, 3, 5, 1, 9], 1) == [1, 3, 5, 9, 10]
def test_hybrid_sort_large_array():
assert hybrid_sort([38, 27, 43, 3, 9, 82, 10], 4) == [3, 9, 10, 27, 3... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[int]) -> List[int]:\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n ... | trial_gpt4o_2 | {
"original_instruction": "You are tasked to sort a list of integers using the merge sort algorithm. But in this challenge, you will enhance the standard implementation by handling arrays with fewer than a threshold length using insertion sort. This hybrid sorting approach can lead to improved performance for certain... | 0.648586 | Data_Structure_37784 | C | [
"insertion_sort",
"merge",
"hybrid_sort"
] | 3 | [
[
"hybrid_sort",
"insertion_sort"
],
[
"hybrid_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fa12001c801dbced03ad3e0c2c38bd75c6d3d923 | 70c4ff2c228982e656563b2cbc7f44eb70c5cd26 | |||
v1.0 | complete | Data_Structure | Data_Structure_37126_C | def extended_bitonic_sort(arr, reverse=False):
"""
Sorts the array using bitonic sort with iterative merge.
:param arr: List[int] - the array of integers to be sorted.
:param reverse: bool - dictates sorting order. True for ascending, False for descending.
:return: List[int] - sorted array (asc... | def is_power_of_two(n):
"""
Check if a number is a power of two.
"""
return (n & (n - 1) == 0) and n != 0
def bitonic_compare_and_swap(arr, i, j, direction):
"""
Compares and swaps elements according to the bitonic sort rule.
"""
if (direction == (arr[i] > arr[j])):
arr[i], arr[... | from solution import extended_bitonic_sort
def test_power_of_two_length_ascending():
arr = [3, 7, 2, 8, 1, 5, 4, 6]
assert extended_bitonic_sort(arr) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_power_of_two_length_descending():
arr = [3, 7, 2, 8, 1, 5, 4, 6]
assert extended_bitonic_sort(arr, reverse=True) ==... | [
{
"docstring": "Check if a number is a power of two.",
"function_declaration": "def is_power_of_two(n):",
"function_name": "is_power_of_two",
"parameter_list": "(n)"
},
{
"docstring": "Compares and swaps elements according to the bitonic sort rule.",
"function_declaration": "def bitonic_... | [
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_bitonic_sort(arr, reverse=False):\n \"\"\"\n Sorts the array using bitonic sort with iterative merge.\n\n :param arr: List[int] - the ar... | trial_gpt4o_1 | {
"original_instruction": "### Question: Implement an Extended Bitonic Sort with Error Handling and Iterative Approach\n\n#### Context:\nYou have been given the task of sorting a dataset that needs to be frequently updated and sorted on a parallel processing system. For initial sorting, an efficient algorithm like Bi... | 0.654483 | Data_Structure_37126 | C | [
"is_power_of_two",
"bitonic_compare_and_swap",
"bitonic_merge",
"bitonic_sort_recursive",
"extended_bitonic_sort"
] | 5 | [
[
"bitonic_merge",
"bitonic_compare_and_swap"
],
[
"bitonic_sort_recursive",
"bitonic_merge"
],
[
"extended_bitonic_sort",
"bitonic_sort_recursive"
],
[
"extended_bitonic_sort",
"is_power_of_two"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 297d5ccbf0a41b2a1a6f95009e797e5e8728ee8c | be8ea8af15a60bbc98f0b1a946858fc68b9f9507 | |||
v1.0 | complete | Data_Structure | Data_Structure_37611_C | import math
def _l2_distance(vec):
"""
Calculate L2 distance (norm) of a vector.
:type vec: list
:rtype: float
"""
norm = 0.0
for element in vec:
norm += element * element
return math.sqrt(norm)
def cosine_similarity(vec1, vec2):
"""
Calculate cosine similarity between... | import math
def _l2_distance(vec):
"""
Calculate L2 distance (norm) of a vector.
:type vec: list
:rtype: float
"""
norm = 0.0
for element in vec:
norm += element * element
return math.sqrt(norm)
def cosine_similarity(vec1, vec2):
"""
Calculate cosine similarity bet... | from solution import cosine_similarity
def test_cosine_similarity_basic():
assert math.isclose(cosine_similarity([1, 0], [0, 1]), 0.0)
def test_cosine_similarity_same_vector():
assert math.isclose(cosine_similarity([1, 2, 3], [1, 2, 3]), 1.0)
def test_cosine_similarity_different_lengths():
try:
... | [
{
"docstring": "Calculate L2 distance (norm) of a vector.\n\n:type vec: list\n:rtype: float",
"function_declaration": "def _l2_distance(vec):",
"function_name": "_l2_distance",
"parameter_list": "(vec)"
},
{
"docstring": "Calculate cosine similarity between two vectors.\n\n:type vec1: list o... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef _l2_distance(vec):\n \"\"\"\n Calculate L2 distance (norm) of a vector.\n \n :type vec: list\n :rtype: float\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "Cosine Similarity Calculation\n\n#### Description:\nYou are required to implement a function `cosine_similarity` that calculates the cosine similarity between two given 1D lists (vectors) of floating-point numbers. The vectors must have the same length, and each vector represents coordinate... | 0.584573 | Data_Structure_37611 | C | [
"_l2_distance",
"cosine_similarity"
] | 2 | [
[
"cosine_similarity",
"_l2_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 004579827a58d556b8d931ed3ce7c96f0373e4ba | 61c7c310cdad5b954a80fbd58326b6ea24c45e73 | |||
v1.0 | complete | Data_Structure | Data_Structure_37115_C | def rsa_encrypt(data: int, e: int, n: int) -> int:
"""
Encrypts the given data using RSA encryption algorithm.
:param data: The integer data to encrypt.
:param e: The public exponent.
:param n: The modulus.
:return: The encrypted integer.
"""
def rsa_decrypt(data: int, d: int, n: int) -> i... | def rsa_encrypt(data: int, e: int, n: int) -> int:
"""
Encrypts the given data using RSA encryption algorithm.
:param data: The integer data to encrypt.
:param e: The public exponent.
:param n: The modulus.
:return: The encrypted integer.
"""
if data < 0 or data >= n:
raise Valu... | import pytest
from solution import rsa_encrypt, rsa_decrypt, secure_message
def test_rsa_encrypt_decrypt_single_value():
n, e, d = 3233, 17, 2753
original_value = 65
encrypted_value = rsa_encrypt(original_value, e, n)
decrypted_value = rsa_decrypt(encrypted_value, d, n)
assert encrypted_value == 27... | [
{
"docstring": "Encrypts the given data using RSA encryption algorithm.\n\n:param data: The integer data to encrypt.\n:param e: The public exponent.\n:param n: The modulus.\n:return: The encrypted integer.",
"function_declaration": "def rsa_encrypt(data, e, n):",
"function_name": "rsa_encrypt",
"par... | [
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 rsa_encrypt(data: int, e: int, n: int) -> int:\n \"\"\"\n Encrypts data using RSA encryption.\n\n :param data: int, the data to be encrypted\n ... | trial_gpt4o_2 | {
"original_instruction": "### RSA Encryption and Decryption\n\nGiven the implementation of the RSA key generation algorithm in the provided code snippet, your task is to implement a secure messaging system using RSA encryption and decryption.\n\n**Context**: You are developing a basic encryption service where users ... | 0.674425 | Data_Structure_37115 | C | [
"rsa_encrypt",
"rsa_decrypt",
"secure_message"
] | 3 | [
[
"secure_message",
"rsa_decrypt"
],
[
"secure_message",
"rsa_encrypt"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9cd0c14d5a41c8eff70e12c3b8c075d733e8269c | ae2df2d93c1a1e4e0a73cd820aac14393d8de913 | |||
v1.0 | complete | Data_Structure | Data_Structure_38455_C | def multiply(matA: list, matB: list) -> list:
""" Multiplies two square matrices matA and matB.
>>> matA = [
... [1, 2],
... [3, 4]
... ]
>>> matB = [
... [2, 0],
... [1, 2]
... ]
>>> multiply(matA, matB)
[[4, 4], [10, 8]]
"""
...
def identity(n: int)... | def multiply(matA, matB):
"""
Multiplies two square matrices matA and matB.
"""
n = len(matA)
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
result[i][j] = sum(matA[i][k] * matB[k][j] for k in range(n))
return result
def identity(n):
"""
... | import pytest
from solution import multiply, identity, matrix_power
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():
expe... | [
{
"docstring": "Multiplies two square matrices matA and matB.",
"function_declaration": "def multiply(matA, matB):",
"function_name": "multiply",
"parameter_list": "(matA, matB)"
},
{
"docstring": "Returns the identity matrix of size n.",
"function_declaration": "def identity(n):",
"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply(matA: list, matB: list) -> list:\n \"\"\"\n Multiplies two matrices matA and matB.\n \"\"\"\n n = len(matA)\n result = [[0] * n fo... | trial_gpt4o_1 | {
"original_instruction": "### Description\nYou have been tasked with implementing a mathematical algorithm to facilitate certain operations on square matrices. Specifically, you must implement a function that performs matrix exponentiation using the method of repeated squaring, leveraging matrix multiplication and i... | 0.537745 | Data_Structure_38455 | C | [
"multiply",
"identity",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity"
],
[
"matrix_power",
"multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c3118dcd2bebc008daa7287e4632c90e8dae819d | b775f9c6dd9f9a56862797e44c19bab0b35a1e85 | |||
v1.0 | complete | Data_Structure | Data_Structure_37819_C | def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points.
Arguments:
point1 : tuple -- A tuple representing the first point.
point2 : tuple -- A tuple representing the second point.
Returns:
float -- The Euclidean distance betw... | import math
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points.
Arguments:
point1 : tuple -- A tuple representing the first point.
point2 : tuple -- A tuple representing the second point.
Returns:
float -- The Euclidean ... | from solution import classify_query_points, euclidean_distance
def test_euclidean_distance():
assert math.isclose(euclidean_distance((0, 0), (3, 4)), 5.0)
assert math.isclose(euclidean_distance((1, 2), (4, 6)), 5.0)
assert math.isclose(euclidean_distance((1, 1), (1, 1)), 0.0)
def test_classify_single_quer... | [
{
"docstring": "Calculate the Euclidean distance between two points.\n\nArguments:\n point1 : tuple -- A tuple representing the first point.\n point2 : tuple -- A tuple representing the second point.\n \nReturns:\n float -- The Euclidean distance between the two points.",
"function_declaration":... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculates the Euclidean distance between two points.\n \n Arguments:\n p... | trial_gpt4o_2 | {
"original_instruction": "## Coding Assessment Question\n\n### Context\nYou're working on a pattern recognition system and need to classify a set of query points based on a labeled training set using the nearest neighbor algorithm. The task involves implementing the key parts of this algorithm to correctly classify ... | 0.669646 | Data_Structure_37819 | C | [
"euclidean_distance",
"classify_query_points"
] | 2 | [
[
"classify_query_points",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 961d28d6fb66bd5da114541c0b8ee89b91ab799f | b16a02f53b13f8c4d7bf07a53068c6ded9abab7b | |||
v1.0 | complete | Data_Structure | Data_Structure_38068_C | from typing import List
import math
def enhanced_interpolation_search(arr: List[int], key: int) -> int:
""" Implement an enhanced interpolation search for a target key in a sorted array.
If the interpolation search fails within a threshold number of guesses,
fallback to binary search.
Args:
arr: ... | import math
from typing import List
def enhanced_interpolation_search(arr: List[int], key: int) -> int:
if len(arr) == 0:
return -1
low = 0
high = len(arr) - 1
threshold = int(math.log2(len(arr)))
guesses = 0
while low <= high and key >= arr[low] and key <= arr[high]:
if low =... | from solution import enhanced_interpolation_search
def test_enhanced_interpolation_search():
# Basic tests
assert enhanced_interpolation_search([5, 10, 12, 14, 17, 20, 21], 14) == 3
assert enhanced_interpolation_search([5, 10, 12, 14, 17, 20, 21], 55) == -1
assert enhanced_interpolation_search([], 5) =... | [
{
"docstring": null,
"function_declaration": "def enhanced_interpolation_search(arr, key):",
"function_name": "enhanced_interpolation_search",
"parameter_list": "(arr, key)"
},
{
"docstring": null,
"function_declaration": "def binary_search(arr, low, high, key):",
"function_name": "b... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import List\n\ndef interpolation_search(arr: List[int], key: int, low: int, high: int) -> int:\n attempts = 0\n max_attempts = ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement an Enhanced Interpolation Search\n\nYou are given a sorted array of integers and a target search key. Implement a function `enhanced_interpolation_search` that searches for the target key in the array. The search should be efficient and robust, even for arrays that a... | 0.576492 | Data_Structure_38068 | C | [
"enhanced_interpolation_search",
"binary_search"
] | 2 | [
[
"enhanced_interpolation_search",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ad83be93e60fbc091f3d761e381430ca9b30c3d5 | 426c1fde5d5294073fa075aa0d3a927e3c2cff3a | |||
v1.0 | complete | Data_Structure | Data_Structure_38435_C | def compute_gcd(a: int, b: int) -> int:
""" Compute the greatest common divisor (GCD) of two integers using the traditional Euclidean method.
>>> compute_gcd(15, 20)
5
>>> compute_gcd(-15, -20)
5
>>> compute_gcd(-15, 20)
5
"""
pass
def compute_gcd_bitwise(a: int, b: int) -> int:
... | def compute_gcd(a: int, b: int) -> int:
"""
Returns the greatest common divisor (GCD) of a and b using the traditional Euclidean method.
"""
if a == 0 or b == 0:
raise ValueError("Input values cannot be zero")
a, b = abs(a), abs(b)
while b:
a, b = b, a % b
... | from solution import compute_gcd, compute_gcd_bitwise, compute_lcm
import pytest
def test_compute_gcd_positive_numbers():
assert compute_gcd(15, 20) == 5
def test_compute_gcd_negative_numbers():
assert compute_gcd(-15, -20) == 5
def test_compute_gcd_mixed_sign_numbers():
assert compute_gcd(-15, 20) == 5
... | [
{
"docstring": "Returns the greatest common divisor (GCD) of a and b using the traditional Euclidean method.",
"function_declaration": "def compute_gcd(a, b):",
"function_name": "compute_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the greatest common divisor (GCD) of a and b ... | [
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 compute_gcd(a: int, b: int) -> int:\n \"\"\"\n Returns the greatest common divisor (GCD) of a and b using the traditional Euclidean method.\n \"\... | trial_gpt4o_0 | {
"original_instruction": "You are tasked with implementing a function to compute the least common multiple (LCM) and greatest common divisor (GCD) of two integers using both traditional and bitwise methods. This task will test your understanding of the Euclidean algorithm, bitwise operations, and handling edge cases... | 0.727433 | Data_Structure_38435 | C | [
"compute_gcd",
"compute_gcd_bitwise",
"compute_lcm"
] | 3 | [
[
"compute_lcm",
"compute_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4377c47843c23725651df4be119f063378defc67 | 16c33ae41a33cc1e083f08d8d9fe898b3784aac3 | |||
v1.0 | complete | Data_Structure | Data_Structure_38651_C | import random
def generate_private_key(p: int) -> int:
"""
Generates a private key in the range [1, p-1].
"""
def generate_public_key(private_key: int, a: int, p: int) -> int:
"""
Computes the public key using the private key, primitive root, and prime number.
"""
def calculate_shared_key(pub... | import random
def generate_private_key(p: int) -> int:
"""
Generates a private key in the range [1, p-1].
"""
return random.randint(1, p - 1)
def generate_public_key(private_key: int, a: int, p: int) -> int:
"""
Computes the public key using the private key, primitive root, and prime number.
... | from solution import generate_private_key, generate_public_key, calculate_shared_key, validate_parameters
def test_generate_private_key():
p = 23
for _ in range(100):
key = generate_private_key(p)
assert 1 <= key < p
def test_generate_public_key():
p = 23
a = 5
private_key = 6
... | [
{
"docstring": "Generates a private key in the range [1, p-1].",
"function_declaration": "def generate_private_key(p):",
"function_name": "generate_private_key",
"parameter_list": "(p)"
},
{
"docstring": "Computes the public key using the private key, primitive root, and prime number.",
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_private_key(p: int) -> int:\n \"\"\"\n Generate a private key, which is a random number in the range [1, p-1].\n \"\"\"... | trial_gpt4o_1 | {
"original_instruction": "You are part of a team developing secure communication protocols and have been assigned to implement a Diffie-Hellman key exchange mechanism. To verify the robustness of the implementation, you need to stretch beyond just performing the key exchange. You must ensure that the keys exchanged ... | 0.554749 | Data_Structure_38651 | C | [
"generate_private_key",
"generate_public_key",
"calculate_shared_key",
"validate_parameters",
"is_prime",
"gcd"
] | 6 | [
[
"validate_parameters",
"gcd"
],
[
"validate_parameters",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a6e8d0b08cb9fc1dc785d07eeeef260a8bdf5c99 | a94f051121456f9497dfa8d975dfae954b7a839b | |||
v1.0 | complete | Data_Structure | Data_Structure_38610_C | from typing import List, Tuple
def enhanced_ternary_search(arr: List[int], key: int) -> Tuple[int, bool]:
"""
Enhanced Ternary Search
Given a sorted array of integers `arr` and an integer `key`,
returns a tuple with:
* The index of the `key` in `arr` (or -1 if key is not found).
* A boolean ind... | from typing import List, Tuple
def binary_search(arr: List[int], key: int) -> Tuple[int, int]:
"""
Binary search, returning the index of the key in the array and the number of comparisons made.
"""
left, right = 0, len(arr) - 1
comparisons = 0
while left <= right:
comparisons += 1
... | from solution import enhanced_ternary_search
def test_enhanced_ternary_search_found():
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
key = 5
assert enhanced_ternary_search(arr, key) == (4, False)
def test_enhanced_ternary_search_not_found():
arr = [1, 2, 3, 4, 6, 7, 8, 9, 10]
key = 5
assert enhanc... | [
{
"docstring": "Binary search, returning the index of the key in the array and the number of comparisons made.",
"function_declaration": "def binary_search(arr, key):",
"function_name": "binary_search",
"parameter_list": "(arr, key)"
},
{
"docstring": "Ternary search, returning the index of ... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef enhanced_ternary_search(arr: List[int], key: int) -> Tuple[int, bool]:\n def ternary_search(arr, key):\n left,... | trial_gpt4o_3 | {
"original_instruction": "### Question: Implement Enhanced Ternary Search\n\n#### Problem Statement:\nYou are tasked with implementing an enhanced version of the ternary search algorithm. Write a Python function `enhanced_ternary_search` that not only finds the index of a given key in a sorted array but also returns... | 0.561359 | Data_Structure_38610 | C | [
"binary_search",
"ternary_search",
"enhanced_ternary_search"
] | 3 | [
[
"enhanced_ternary_search",
"binary_search"
],
[
"enhanced_ternary_search",
"ternary_search"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 858b0bdaf8c1ecf26e927a090b14da3f26657887 | 5faa941b323889c3cb61aa1490729f3976d577c0 | |||
v1.0 | complete | Data_Structure | Data_Structure_38079_C | from typing import List, Dict
from collections import deque
def prime_check(n):
""" Check if a number is a prime number.
>>> prime_check(2)
True
>>> prime_check(4)
False
"""
pass
def prime_shortest_path(graph: Dict[int, List[int]], start: int, end: int) -> int:
""" Find the shortest pa... | from collections import deque
def prime_check(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def prime_sh... | import pytest
from solution import prime_shortest_path
def test_prime_shortest_path_found():
graph = {
2: [3, 5],
3: [2, 5, 11],
5: [2, 3, 7, 11],
7: [5, 11],
11: [3, 5, 7],
4: [6], # Non-prime nodes
6: [4] # Non-prime nodes
}
assert prime_shortest_p... | [
{
"docstring": null,
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def prime_shortest_path(graph, start, end):",
"function_name": "prime_shortest_path",
"parameter_list": "(g... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef is_prime(n):\n \"\"\"\n Check if a number is prime\n \"\"\"\n if n <= 1:\n return False\n if n <= 3... | trial_gpt4o_2 | {
"original_instruction": "Prime Path Finder\n\nGiven an undirected graph where each node corresponds to an integer, design a function to find the shortest path between two nodes where all the nodes in the path are prime numbers.\n\n#### Task\nWrite a function `prime_shortest_path(graph, start, end)` that:\n1. Takes ... | 0.624107 | Data_Structure_38079 | C | [
"prime_check",
"prime_shortest_path"
] | 2 | [
[
"prime_shortest_path",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0b43f8e2d9df5341ca8d19d6daa151bcfd640254 | 3448ede52f5caa258fe62fa64f60740ec1bba8ef | |||
v1.0 | complete | Data_Structure | Data_Structure_38321_C | from typing import List
def lcm_array(arr: List[int]) -> int:
"""Compute the Least Common Multiple (LCM) of an array of integers.
Args:
arr (List[int]): A list of non-negative integers.
Returns:
int: The LCM of all integers in the list.
Examples:
>>> lcm_array([2, 7, 3])
... | from typing import List
from math import gcd
def lcm(x, y):
return x * y // gcd(x, y)
def lcm_array(arr: List[int]) -> int:
result = 1
for num in arr:
if num == 0:
continue
result = lcm(result, num)
return result
# Example usage
# print(lcm_array([2, 7, 3])) # Should retu... | from solution import lcm_array
def test_lcm_array_basic():
assert lcm_array([2, 7, 3]) == 42
assert lcm_array([6, 8]) == 24
assert lcm_array([3, 5, 7]) == 105
def test_lcm_array_with_zero():
assert lcm_array([0, 6, 9]) == 18
assert lcm_array([0, 0, 0, 9]) == 9
assert lcm_array([0]) == 1 # Onl... | [
{
"docstring": null,
"function_declaration": "def lcm(x, y):",
"function_name": "lcm",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def lcm_array(arr):",
"function_name": "lcm_array",
"parameter_list": "(arr)"
}
] | [
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\nfrom math import gcd\n\ndef lcm(x: int, y: int) -> int:\n return x * y // gcd(x, y)\n\ndef lcm_array(arr: List[int]) -> int:\n ... | trial_gpt4o_1 | {
"original_instruction": "Given the fundamental numerical concepts demonstrated in the provided code snippets, you are required to implement a function that computes the LCM of an array of integers efficiently.\n\n### Problem Statement\nImplement a function `lcm_array(arr: List[int]) -> int` that takes a list of non... | 0.628731 | Data_Structure_38321 | C | [
"lcm",
"lcm_array"
] | 2 | [
[
"lcm_array",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c6fa6ae9e17483a8a6582773891c6cd9b33f9a09 | 968b1b223bd63893efb715e8395183f732f7f349 | |||
v1.0 | complete | Data_Structure | Data_Structure_38161_C | def bucket_sort(arr):
"""Implement the Bucket Sort algorithm.
Args:
arr (list): List of non-negative integers.
Returns:
list: Sorted list of integers.
Examples:
>>> bucket_sort([64, 25, 12, 22, 11])
[11, 12, 22, 25, 64]
>>> bucket_sort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
"""
... | def bucket_sort(arr):
''' Bucket Sort
'''
if not arr:
return arr
max_value = max(arr)
bucket_count = len(arr)
size = (max_value / bucket_count) + 1
# Create buckets
buckets = [[] for _ in range(bucket_count)]
# Assign elements to the bucket
for v in arr:
... | from solution import bucket_sort, next_sort
def test_empty_array():
assert bucket_sort([]) == []
def test_single_element():
assert bucket_sort([1]) == [1]
def test_sorted_array():
assert bucket_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert bucket_sort([5, 4, 3, 2, ... | [
{
"docstring": "Bucket Sort\n ",
"function_declaration": "def bucket_sort(arr):",
"function_name": "bucket_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Insertion Sort\n ",
"function_declaration": "def next_sort(arr):",
"function_name": "next_sort",
"parameter_list": ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bucket_sort(arr):\n ''' Bucket Sort\n '''\n if not arr:\n return arr\n \n max_value = max(arr)\n size = max_value // len(arr) + 1... | trial_gpt4o_2 | {
"original_instruction": "You are required to implement the Bucket Sort algorithm with the following specifications and constraints.\n\n### Input:\n* An array `arr` of `n` non-negative integers where \\(1 \\leq n \\leq 10^5\\).\n* The integers in `arr` range from `0` to `10000`.\n\n### Output:\n* A sorted array cont... | 0.577274 | Data_Structure_38161 | C | [
"bucket_sort",
"next_sort"
] | 2 | [
[
"bucket_sort",
"next_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7819e73811a730cf713b1b5e298e56615d3ba25b | 52148b9a5ecda40348dce4c31b88b59157bd1ef9 | |||
v1.0 | complete | Data_Structure | Data_Structure_38312_C | def construct_tree(prices: List[int]) -> List[int]:
"""
Construct the Fenwick Tree (Binary Indexed Tree) from the given stock prices.
>>> construct_tree([3, 2, -1, 6, 5, 4, -3])
[0, 3, 5, -1, 10, 5, 9, -3]
"""
def get_sum(bit_tree: List[int], i: int) -> int:
"""
Compute the prefix sum... | def construct_tree(prices):
"""
Construct the Fenwick Tree (Binary Indexed Tree) from the given stock prices.
"""
n = len(prices)
bit_tree = [0] * (n + 1)
for i in range(n):
update(bit_tree, i, prices[i])
return bit_tree
def get_sum(bit_tree, i):
"""
Compute the pr... | from solution import construct_tree, get_sum, update
def test_construct_tree():
prices = [3, 2, -1, 6, 5, 4, -3]
bit_tree = construct_tree(prices)
expected_bit_tree = [0, 3, 5, -1, 10, 5, 9, -3]
assert bit_tree == expected_bit_tree
def test_get_sum():
prices = [3, 2, -1, 6, 5, 4, -3]
bit_tree ... | [
{
"docstring": "Construct the Fenwick Tree (Binary Indexed Tree) from the given stock prices.",
"function_declaration": "def construct_tree(prices):",
"function_name": "construct_tree",
"parameter_list": "(prices)"
},
{
"docstring": "Compute the prefix sum from day 1 to day i (0-based index)... | [
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 construct_tree(prices):\n \"\"\"\n Construct the Fenwick Tree (Binary Indexed Tree) from the given stock prices.\n \"\"\"\n n = len(prices)\n ... | trial_gpt4o_0 | {
"original_instruction": "#### Context\nYou are working for a financial data analytics company, and one common task is to quickly compute the sum of daily stock prices over a specific range of days, as well as update the price for a specific day when new data comes in. Given that these operations need to be highly e... | 0.495959 | Data_Structure_38312 | C | [
"construct_tree",
"get_sum",
"update"
] | 3 | [
[
"construct_tree",
"update"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ec5a8ee2be57b622f21fff2f8cea53b48432f93f | b9f3f30a567552be45908a35aed8cf3abebe98c6 | |||
v1.0 | complete | Data_Structure | Data_Structure_38549_C | def merge_sort(arr):
"""
Sorts the array `arr` using the merge sort algorithm.
>>> merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
>>> merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
>>> merge_sort([]) == []
>>> merge_sort([1]) == [1]
"""
def merge(left, righ... | def merge_sort(arr):
"""
Sorts the array `arr` using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left, right):
"""
... | from solution import merge_sort, merge
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_list():
asse... | [
{
"docstring": "Sorts the array `arr` using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists `left` and `right` into a single sorted list.",
"function_declaratio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array of integers using the Merge Sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n \... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Implementation Challenge\n\n**Scenario**: \n\nYou are tasked with optimizing a large dataset processing system. Given that stable, consistent sorting is crucial to preserve the integrity of records, you decide to implement the Merge Sort algorithm. The primary requirement is ... | 0.626298 | Data_Structure_38549 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2db133fd37d63be1b7f4478070066b084ed9a0b2 | 1d30d54eda1dae6eae1e41c355ae1fadd7e878c8 | |||
v1.0 | complete | Data_Structure | Data_Structure_38451_C | from typing import List
def radix_sort(arr: List[int]) -> List[int]:
"""
Sort a list of integers in ascending order using the Radix Sort algorithm.
The implementation must handle edge cases and remain robust with various inputs.
>>> radix_sort([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66... | def counting_sort(arr, exp):
"""
A function to help with the counting sort of the digits, based on the exponent.
"""
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]... | from solution import radix_sort
def test_radix_sort_single_element():
assert radix_sort([10]) == [10]
def test_radix_sort_sorted_list():
assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_radix_sort_reverse_sorted():
assert radix_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_radix_sort_d... | [
{
"docstring": "A function to help with the counting sort of the digits, based on the exponent. ",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "The main function to sort an array of non-negative in... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n for i in range(n):\n index = (arr[i] // exp) % 10\n ... | trial_gpt4o_2 | {
"original_instruction": "### Scenario and Context\nSuppose you are tasked with a system where sorting numbers efficiently from a large list is a frequent requirement. Your team has decided to use Radix Sort due to its efficiency in cases where comparisons between numbers are computationally expensive. The integers ... | 0.716038 | Data_Structure_38451 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 42cd37b3e40a5a62b755f4f2a01fddd86e897e47 | 336f3f7730120d73fc3ae0c596dae5c2098dcdd1 | |||
v1.0 | complete | Data_Structure | Data_Structure_38493_C | def euler_totient(n: int) -> int:
"""
Computes the Euler's totient function value of an integer n.
>>> euler_totient(10)
4
>>> euler_totient(12)
4
>>> euler_totient(15)
8
"""
def sum_of_totients(arr: list[int]) -> int:
"""
Given an array of integers, returns the... | def euler_totient(n: int) -> int:
"""
Euler's Totient function, also known as ϕ(n), computes the count of integers
up to n that are relatively prime to n.
"""
if n == 1:
return 1
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
... | from solution import euler_totient, sum_of_totients
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(10) == 4
assert euler_totient(12) == 4
asse... | [
{
"docstring": "Euler's Totient function, also known as ϕ(n), computes the count of integers\nup to n that are relatively prime to n.",
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": "Given an array of integers, co... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def euler_totient(n):\n \"\"\"\n Computes the Euler's totient function for an integer n.\n \"\"\"\n result = n\n p = 2\n while p * p <= n:\n... | trial_gpt4o_1 | {
"original_instruction": "### Euler's Totient Function Implementation and Usage\n\nEuler's totient function, also known as ϕ(n), is extremely useful in number theory and cryptographic algorithms. Given the significance of this function, your task is to implement the Euler's totient function and use it to solve a spe... | 0.711659 | Data_Structure_38493 | C | [
"euler_totient",
"sum_of_totients"
] | 2 | [
[
"sum_of_totients",
"euler_totient"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0d6bf21eeae9a6001098c18eb7da1535f3ee8e9f | d5f18a3ae84ff9e8a7a8f9a7718c07cfcc8f7d59 | |||
v1.0 | complete | Data_Structure | Data_Structure_38283_C | from typing import List
def bucket_sort_floats(arr: List[float]) -> List[float]:
"""
Sorts a list of floating-point numbers using bucket sort.
The input array contains floating-point numbers uniformly distributed in the range [0, 1).
The function returns the sorted array.
>>> bucket_sort... | from typing import List
def insertion_sort(arr: List[float]) -> List[float]:
"""
Helper function to perform insertion sort on a list.
"""
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 bucket_sort_floats
def test_bucket_sort_floats_basic():
assert bucket_sort_floats([0.22, 0.45, 0.12, 0.36, 0.80, 0.72]) == [0.12, 0.22, 0.36, 0.45, 0.72, 0.80]
def test_bucket_sort_floats_with_duplicates():
assert bucket_sort_floats([0.50, 0.50, 0.50]) == [0.50, 0.50, 0.50]
def test_buck... | [
{
"docstring": "Helper function to perform insertion sort on a list.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts a list of floating-point numbers using bucket sort.",
"function_declaration": "... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bucket_sort_floats(arr: List[float]) -> List[float]:\n def insertion_sort(bucket: List[float]) -> List[float]:\n for ... | trial_gpt4o_2 | {
"original_instruction": "**Context**:\nYou are given the task of sorting a list of floating-point numbers, ensuring that the algorithm performs efficiently for values uniformly distributed between [0, 1). The implementation should use the bucket sort algorithm, followed by insertion sort for sorting individual buck... | 0.661653 | Data_Structure_38283 | C | [
"insertion_sort",
"bucket_sort_floats"
] | 2 | [
[
"bucket_sort_floats",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 29220047dd0a623ccc725cf3c1d009aa005f84e1 | dca78548a0901b037621aecbc106b707ea302dd0 | |||
v1.0 | complete | Data_Structure | Data_Structure_37717_C | def generate_word_squares(words: List[str]) -> List[List[str]]:
""" Generate all possible word squares from a given list of words.
Each word square is an arrangement of words in a square grid such that each row and column reads the same word.
Args:
words (List[str]): A list of strings containing words ... | from typing import List, Dict, DefaultDict
from collections import defaultdict
def build_prefix_dict(words: List[str]) -> Dict[str, List[str]]:
prefix_dict = defaultdict(list)
for word in words:
for i in range(len(word) + 1):
prefix = word[:i]
prefix_dict[prefix].append(word)
... | from solution import generate_word_squares
def test_generate_word_squares_example():
words = ["area", "lead", "wall", "lady", "ball"]
expected_output = [
["wall", "area", "lead", "lady"],
["ball", "area", "lead", "lady"]
]
assert generate_word_squares(words) == expected_output
def test... | [
{
"docstring": null,
"function_declaration": "def build_prefix_dict(words):",
"function_name": "build_prefix_dict",
"parameter_list": "(words)"
},
{
"docstring": null,
"function_declaration": "def backtrack(step, word_square, length, prefix_dict, results):",
"function_name": "backtra... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict\nfrom typing import List\n\ndef generate_word_squares(words: List[str]) -> List[List[str]]:\n def build_prefix_dict(wor... | trial_gpt4o_1 | {
"original_instruction": "### Word Square Generator\n\n**Scenario**:\nImagine you are working on a popular word puzzle game where players need to form word squares. A word square is an arrangement of words in a square grid such that each row and column reads the same word. You are tasked with implementing a function... | 0.582273 | Data_Structure_37717 | C | [
"build_prefix_dict",
"backtrack",
"generate_word_squares"
] | 3 | [
[
"generate_word_squares",
"backtrack"
],
[
"generate_word_squares",
"build_prefix_dict"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e9dd50bf4a076be2a5d635518f84c31d8b15f510 | 3ad1bedc912ed3efd29c47a241069a93c3e0c41c | |||
v1.0 | complete | Data_Structure | Data_Structure_38364_C | from typing import List
def hybrid_quick_sort(arr: List[int], low: int, high: int) -> None:
"""Implement a Hybrid Quick Sort that switches to Insertion Sort for small subarrays.
Args:
arr (List[int]): The array of integers to be sorted.
low (int): The starting index of the subarray to be sorted.
... | from typing import List
def insertion_sort(arr: List[int], left: int, right: int) -> None:
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def partition(arr: List[int],... | def test_sort_array_standard_case():
assert sort_array([3, 6, 2, 8, 7, 1]) == [1, 2, 3, 6, 7, 8]
def test_sort_array_already_sorted():
assert sort_array([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_sort_array_reverse_sorted():
assert sort_array([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_sort_array_sing... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"paramet... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr, low, high):\n \"\"\"\n Sorts the array from index low to high using insertion sort.\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement a Hybrid Quick Sort\n\nYour task is to implement a Hybrid Quick Sort algorithm that uses the standard quick sort algorithm but switches to insertion sort when the size of the subarray is below a certain threshold. This hybrid approach helps to optimize the sorting of... | 0.651604 | Data_Structure_38364 | C | [
"insertion_sort",
"partition",
"hybrid_quick_sort",
"sort_array"
] | 4 | [
[
"hybrid_quick_sort",
"insertion_sort"
],
[
"hybrid_quick_sort",
"partition"
],
[
"sort_array",
"hybrid_quick_sort"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 3e2e00857ab3da089c22f5a4f55a4fa41000b235 | c742096526aeed4c066815763cc8f6f51caf0c13 | |||
v1.0 | complete | Data_Structure | Data_Structure_38838_C | def sum_of_primes(numbers):
"""
Given a list of integers, return the sum of all prime numbers in the list.
:param numbers: List of integers
:return: Sum of prime numbers
"""
pass
def is_prime(n):
"""
Check if a number is prime.
:param n: Integer
:return: Boolean, True if n... | def is_prime(n):
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def sum_of_primes(numbers):
"""
... | from solution import sum_of_primes
def test_sum_of_primes_basic():
assert sum_of_primes([2, 3, 4, 5, 6, 7, 8, 9, 10]) == 17
def test_sum_of_primes_no_primes():
assert sum_of_primes([1, 4, 6, 8, 10, 12, 14, 16]) == 0
def test_sum_of_primes_mixed_numbers():
assert sum_of_primes([11, 14, 17, 18, 19, 20]) ==... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given a list of integers, return the sum of all prime numbers in the list.\n\n:param numbers: List of integers\n:return: Sum of pr... | [
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 Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Prime Sum Problem\n\n#### Scenario:\nYou are hired to optimize the performance of a cryptographic system which relies on checking the sum of prime numbers from a list. Given a list of integers, you need to implement a function that returns the sum of all prime numbers within the list. \... | 0.725031 | Data_Structure_38838 | C | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ddf91e8711627b6747e0f59df705f7d4b0ffc945 | 9e8d3b1beea499bdac9201143b43d4f015efab9e | |||
v1.0 | complete | Data_Structure | Data_Structure_38787_C | def max_heap_sort_optimized(arr):
"""Sort a list of integers in ascending order using max heap sort.
>>> max_heap_sort_optimized([4, 10, 3, 5, 1])
[1, 3, 4, 5, 10]
>>> max_heap_sort_optimized([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>> max_heap_sort_optimized([])
[]
"""
pass
def min_h... | def max_heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[largest] < arr[left]:
largest = left
if right < n and arr[largest] < arr[right]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
max_heap... | def test_max_heap_sort_optimized():
arr = [4, 10, 3, 5, 1]
sorted_arr = max_heap_sort_optimized(arr.copy())
assert sorted_arr == [1, 3, 4, 5, 10], f"Unexpected result {sorted_arr}"
def test_min_heap_sort_optimized():
arr = [4, 10, 3, 5, 1]
sorted_arr = min_heap_sort_optimized(arr.copy())
assert... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": null,
"function_declaration": "def max_heap_sort_optimized(arr):",
"function_name": "max_heap_sort_optimized",
"parameter_... | [
0,
0,
0,
1,
1,
1,
0,
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": "def max_heapify(arr, n, i):\n largest = i # Initialize largest as root\n l = 2 * i + 1 # left = 2*i + 1\n r = 2 * i + 2 # right = 2*i + 2\n\n # ... | trial_gpt4o_9 | {
"original_instruction": "### Heap Sort Algorithm Implementation\n\n**Scenario**: A logistics company needs to sort a list of delivery times to optimize their delivery sequence. To ensure the process is efficient, they have chosen to use heap sort. As part of their software development team, you are tasked with impl... | 0.637859 | Data_Structure_38787 | C | [
"max_heapify",
"max_heap_sort_optimized",
"min_heapify",
"min_heap_sort_optimized"
] | 4 | [
[
"max_heap_sort_optimized",
"max_heapify"
],
[
"min_heap_sort_optimized",
"min_heapify"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 8761e0e4ca74d5e069baddd600a876566849d37f | 3b2a0d9944d7c2a7c3f323078d2305ed23a74a6d | |||
v1.0 | complete | Data_Structure | Data_Structure_38910_C | import random
def optimized_bogo_sort(arr: list) -> tuple:
"""
Sorts an array using the Bogo Sort algorithm.
Parameters:
arr (list): The list of integers to be sorted.
Returns:
tuple: A tuple containing the sorted list and the number of iterations.
Example usage:
>>> opti... | import random
def is_sorted(arr):
"""Helper function to check if a list is sorted."""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def optimized_bogo_sort(arr: list) -> tuple:
"""
Sorts an array using the Bogo Sort algorithm.
Parameter... | from solution import optimized_bogo_sort
def test_optimized_bogo_sort_empty():
sorted_arr, iterations = optimized_bogo_sort([])
assert sorted_arr == []
assert iterations == 0
def test_optimized_bogo_sort_single_element():
sorted_arr, iterations = optimized_bogo_sort([42])
assert sorted_arr == [42]... | [
{
"docstring": "Helper function to check if a list is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts an array using the Bogo Sort algorithm.\n\nParameters:\narr (list): The list of integers to be sorte... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if the array is sorted\n \n Parameters:\n arr (list): The list of inte... | trial_gpt4o_2 | {
"original_instruction": "### Context\nYou have learned various sorting algorithms and their efficiency. Now, your task is to understand the limitations of certain inefficient algorithms by implementing one of the least efficient algorithms known: **Bogo Sort**.\n\n### Task\nWrite a Python function `optimized_bogo_s... | 0.617677 | Data_Structure_38910 | C | [
"is_sorted",
"optimized_bogo_sort"
] | 2 | [
[
"optimized_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2802091888bdcd3830a09bab204c6e2bebb537d7 | 619af140a539e58e710ea2168953d055d1c58e1a | |||
v1.0 | complete | Data_Structure | Data_Structure_37976_C | def heapify_max(arr, n, i):
"""
Creates a max heap from a given subtree.
"""
pass
def heap_sort_max(arr):
"""
Sorts an array in ascending order using max heap.
>>> heap_sort_max([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
>>> heap_sort_max([9, 8, 7... | def heapify_max(arr, n, i):
"""
Creates a max heap from a given subtree.
"""
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_max, heap_sort_min
def test_heap_sort_max():
assert heap_sort_max([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
assert heap_sort_max([9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
assert heap_sort_max([-1, 2, 0, -2, 1, 3]) == [-2, -1, 0,... | [
{
"docstring": "Creates a max heap from a given subtree.",
"function_declaration": "def heapify_max(arr, n, i):",
"function_name": "heapify_max",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Sorts an array in ascending order using max heap.",
"function_declaration": "def heap_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": "def heapify_max(arr, n, i):\n \"\"\"\n Creates a max heap from a given subtree.\n \"\"\"\n largest = i\n left = 2 * i + 1\n right = 2 * i + ... | trial_gpt4o_0 | {
"original_instruction": "### Problem: Implementing Heap Sort\nYou are required to implement the Heap Sort algorithm. You must provide two implementations: one using a Max Heap and another using a Min Heap. Both implementations should sort an array of integers in ascending order. Your task is to define two functions... | 0.61256 | Data_Structure_37976 | C | [
"heapify_max",
"heap_sort_max",
"heapify_min",
"heap_sort_min"
] | 4 | [
[
"heap_sort_max",
"heapify_max"
],
[
"heap_sort_min",
"heapify_min"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ac36c39f89c85effe9da83673b6531746d1fb318 | 9bbeafadf454626d1b3c374de10997a5407845ec | |||
v1.0 | complete | Data_Structure | Data_Structure_38406_C | def gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor of two integers using Euclid's algorithm.
>>> gcd(48, 18)
6
>>> gcd(100, 25)
25
>>> gcd(7, 3)
1
>>> gcd(12, 15)
3
>>> gcd(1, 1)
1
"""
pass
def gcd_bit(a: int, b: int) -> int:
"""
Com... | def gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor of two integers using Euclid's algorithm.
"""
while b:
a, b = b, a % b
return a
def gcd_bit(a: int, b: int) -> int:
"""
Computes the greatest common divisor of two non-negative integers using bitwise operations... | from solution import gcd, gcd_bit, lcm, trailing_zero
def test_gcd():
assert gcd(48, 18) == 6
assert gcd(100, 25) == 25
assert gcd(7, 3) == 1
assert gcd(12, 15) == 3
assert gcd(1, 1) == 1
def test_gcd_bit():
assert gcd_bit(48, 18) == 6
assert gcd_bit(100, 25) == 25
assert gcd_bit(7, 3)... | [
{
"docstring": "Computes the greatest common divisor of two integers using Euclid's algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the greatest common divisor of two non-negative integers using bitwise ope... | [
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 gcd(a: int, b: int) -> int:\n \"\"\"\n Computes the greatest common divisor of two integers using Euclid's algorithm.\n \"\"\"\n while b:\n ... | trial_gpt4o_1 | {
"original_instruction": "#### Problem Statement\n\nYou are required to design a system that can handle arithmetic operations involving the greatest common divisor (GCD) and least common multiple (LCM). Additionally, you must devise a utility to count the trailing zeros in a binary representation of a number. This a... | 0.764016 | Data_Structure_38406 | C | [
"gcd",
"gcd_bit",
"lcm",
"trailing_zero"
] | 4 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 79febaa81ea516b55a92ad4c49085f072fe32987 | 7395d0c8d337d42bd706aa5df3f99338c93c0a8c | |||
v1.0 | complete | Data_Structure | Data_Structure_37748_C | from typing import List
def invert_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
Inverts a given square matrix.
Returns an inverted matrix if possible; otherwise, returns an error code:
- [[-1]] if the input is not a matrix.
- [[-2]] if the matrix is not square.
- [[-3]] if the matri... | from typing import List
def determinant(matrix: List[List[float]]) -> float:
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for col in range(n):
submatrix = [row[:col] + row[col+1:]... | def test_invert_valid_matrix_2x2():
matrix = [
[4, 7],
[2, 6]
]
expected = [
[0.6, -0.7],
[-0.2, 0.4]
]
result = invert_matrix(matrix)
assert result == expected
def test_invert_valid_matrix_3x3():
matrix = [
[1, 2, 3],
[0, 1, 4],
[5, 6... | [
{
"docstring": null,
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def adjugate(matrix):",
"function_name": "adjugate",
"parameter_list": "(matrix)"
},
{
"d... | [
0,
0,
0,
0,
1,
1,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Union\n\ndef invert_matrix(matrix: List[List[Union[int, float]]]) -> List[List[float]]:\n # Check if input is a matrix\n if not... | trial_gpt4o_6 | {
"original_instruction": "You are required to implement a function `invert_matrix(matrix: List[List[int]]) -> List[List[int]]` that inverts a given square matrix. Follow these steps and constraints carefully to complete the task. \n\n### Input:\n- A 2D list, `matrix`, containing integers with dimensions n x n (1 ≤ n... | 0.60016 | Data_Structure_37748 | C | [
"determinant",
"adjugate",
"invert_matrix"
] | 3 | [
[
"adjugate",
"determinant"
],
[
"invert_matrix",
"adjugate"
],
[
"invert_matrix",
"determinant"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 6b2c13daa33dd6bd21667e8d47ad319c0f648a5a | 1b912261a8f51c58e0f9e97cf9c09c786a0f21bb | |||
v1.0 | complete | Data_Structure | Data_Structure_39078_C | from typing import List
def enhanced_radix_sort(arr: List[int]) -> List[int]:
"""Enhanced Radix Sort to handle both positive and negative numbers efficiently.
Args:
arr (List[int]): The input list of integers, which can include both negative and positive values.
Returns:
List[int]: Th... | def enhanced_radix_sort(arr):
"""
Enhanced Radix Sort to handle both positive and negative numbers.
"""
if not arr:
return arr
# Separate positive and negative values
pos_arr = [num for num in arr if num >= 0]
neg_arr = [-num for num in arr if num < 0]
# Perform radix sort on ... | from solution import enhanced_radix_sort
def test_basic_sort():
assert enhanced_radix_sort([170, 45, 75, -90, -802, 24, 2, 66]) == [-802, -90, 2, 24, 45, 66, 75, 170]
def test_empty_list():
assert enhanced_radix_sort([]) == []
def test_all_negative():
assert enhanced_radix_sort([-5, -100, -6, -1, -99... | [
{
"docstring": "Enhanced Radix Sort to handle both positive and negative numbers.",
"function_declaration": "def enhanced_radix_sort(arr):",
"function_name": "enhanced_radix_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Performs radix sort on a list of non-negative integers.",
"fun... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef enhanced_radix_sort(arr: List[int]) -> List[int]:\n # Radix sort helper\n def counting_sort(exp, base=10):\n n = l... | trial_gpt4o_2 | {
"original_instruction": "### Problem: Advanced Radix Sort Implementation\n\n#### Context:\nGiven that radix sort is powerful for sorting large lists of non-negative integers, we need to enhance its functionality to handle integers with leading negative values efficiently.\n\n#### Task:\n\nWrite a function `enhanced... | 0.673728 | Data_Structure_39078 | C | [
"enhanced_radix_sort",
"radix_sort",
"counting_sort"
] | 3 | [
[
"enhanced_radix_sort",
"radix_sort"
],
[
"radix_sort",
"counting_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7d1af5f50c51b2e3d3897bfdd9d233781a66076a | 66a97fd400db9c2366b825b1fba59216fa663a99 | |||
v1.0 | complete | Data_Structure | Data_Structure_38918_C | from typing import List
def bucket_sort(arr: List[float]) -> List[float]:
"""
Perform Bucket Sort on a list of floats in the range [0, 1).
Parameters:
arr (List[float]): A list of real numbers where 0 <= arr[i] <= 1 for all i.
Returns:
List[float]: A sorted list of real numbers in non-decreas... | from typing import List
def insertion_sort(arr: List[float]) -> List[float]:
"""
Helper function to perform Insertion Sort on a list of floats.
"""
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 -=... | from solution import bucket_sort
def test_bucket_sort_example_1():
arr = [0.897, 0.565, 0.656, 0.123, 0.665, 0.343]
expected = [0.123, 0.343, 0.565, 0.656, 0.665, 0.897]
assert bucket_sort(arr) == expected
def test_bucket_sort_example_2():
arr = [0.5, 0.25, 0.75, 0.1, 0.9]
expected = [0.1, 0.25, 0... | [
{
"docstring": "Helper function to perform Insertion Sort on a list of floats.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Perform Bucket Sort on a list of floats in the range [0, 1).",
"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 insertion_sort(arr: List[float]) -> List[float]:\n \"\"\"\n Performs insertion sort on the given list and returns the sor... | trial_gpt4o_2 | {
"original_instruction": "You are given an array of `n` real numbers. Your task is to implement a function `bucket_sort(arr: List[float]) -> List[float]`, that takes this array and returns a sorted array using the Bucket Sort algorithm. Here's what you need to consider:\n\n1. **Input**: The function receives a list ... | 0.631622 | Data_Structure_38918 | C | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6fbdbc228f9d4c7d484bff7791aa7f3eb16501b6 | fe0afeeb73f28da054a7dea0f57ac8c9cf209ac7 | |||
v1.0 | complete | Data_Structure | Data_Structure_39138_C | class Node:
def __init__(self, val:int=0, left:'Node'=None, right:'Node'=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big: Node, small: Node) -> bool:
"""Determine if one tree is a subtree of another.
Args:
big (Node): The root of the larger tree... | class Node:
def __init__(self, val:int=0, left:'Node'=None, right:'Node'=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big: Node, small: Node) -> bool:
if not small:
return True
if not big:
return False
if are_identical(big, s... | from solution import Node, is_subtree
def test_identical_subtree():
big = Node(3, Node(4, Node(1), Node(2)), Node(5))
small = Node(4, Node(1), Node(2))
assert is_subtree(big, small) == True
def test_not_subtree():
big = Node(3, Node(4, Node(1), Node(2, Node(0))), Node(5))
small = Node(4, Node(1), ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, val:int=0, left:'Node'=None, right:'Node'=None):\n self.val = val\n self.left = left\n self.right = r... | trial_gpt4o_2 | {
"original_instruction": "### Subtree Check for Binary Trees\n\n**Context:**\nYou are given two binary trees and need to determine if one tree is a subtree of another. A subtree of a tree `t` is a tree consisting of a node in `t` and all of its descendants in `t`.\n\n**Problem:**\nWrite a function `is_subtree(big, s... | 0.578914 | Data_Structure_39138 | C | [
"is_subtree",
"are_identical"
] | 2 | [
[
"is_subtree",
"are_identical"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | f5c770644670ed0eaa2d2a23ce1ebf43f3b2441c | 1872aef81a8e39d2958a4ebddfdaea67416773f2 | |||
v1.0 | complete | Data_Structure | Data_Structure_39050_C | import math
from typing import Dict, Tuple, Any
def distance(x: Tuple[float], y: Tuple[float]) -> float:
"""Calculate the Euclidean distance between vectors x and y."""
assert len(x) == len(y), "The vectors must have the same length"
sum_of_squares = 0
for i in range(len(x)):
sum_of_squares += ... | import math
def distance(x, y):
"""Calculate the Euclidean distance between vectors x and y."""
assert len(x) == len(y), "The vectors must have the same length"
sum_of_squares = 0
for i in range(len(x)):
sum_of_squares += (x[i] - y[i]) ** 2
return math.sqrt(sum_of_squares)
def nearest_neig... | from solution import nearest_neighbor
def test_basic_case():
tSet = {
(1.0, 2.0): 'A',
(3.0, 4.0): 'B',
(1.5, 1.8): 'A',
(-1.0, -2.0): 'C'
}
x = (0.0, 0.0)
assert nearest_neighbor(x, tSet) == 'A'
def test_single_point_case():
tSet = {
(1.0, 1.0): 'A'
}
... | [
{
"docstring": "Calculate the Euclidean distance between vectors x and y.",
"function_declaration": "def distance(x, y):",
"function_name": "distance",
"parameter_list": "(x, y)"
},
{
"docstring": "Find the nearest neighbor of x in the training set tSet.",
"function_declaration": "def ne... | [
0,
0,
0,
1,
1,
0,
1,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(x, y):\n \"\"\"\n Calculate the Euclidean distance between vectors x and y.\n \"\"\"\n assert len(x) == len(y), \"The ... | trial_gpt4o_9 | {
"original_instruction": "### Nearest Neighbor Classification Algorithm Implementation\n\nYou are given a dataset of multi-dimensional points, where each point has an associated label. The Nearest Neighbor algorithm aims to classify a new point based on its proximity to points in the dataset. Your task is to impleme... | 0.697407 | Data_Structure_39050 | C | [
"distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6402302824fa4e0e7a0cb2c8865da3b2a969e7c6 | 34c6dd9f446939289276159b065940a4bb025298 | |||
v1.0 | complete | Data_Structure | Data_Structure_38823_C | from typing import List, Tuple
def prime_check(num: int) -> bool:
"""
Determines if num is a prime number.
Args:
num (int): The number to check for primality.
Returns:
bool: True if num is prime, False otherwise.
>>> prime_check(7) == True
>>> prime_check(4) == False
... | from sympy import isprime, totient, primitive_root
def prime_check(num):
"""
Determines if num is a prime number.
Args:
num (int): The number to check for primality.
Returns:
bool: True if num is prime, False otherwise.
"""
return isprime(num)
def euler_totient(n):
"""
... | from solution import prime_check, euler_totient, find_order, find_primitive_root, exec_diffie_hellman
def test_prime_check():
assert prime_check(7) == True
assert prime_check(4) == False
assert prime_check(11) == True
assert prime_check(1) == False
def test_euler_totient():
assert euler_totient(1)... | [
{
"docstring": "Determines if num is a prime number.\n\nArgs:\nnum (int): The number to check for primality.\n\nReturns:\nbool: True if num is prime, False otherwise.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring"... | [
0,
0,
1,
0,
0,
1,
0,
0,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "def prime_check(num):\n \"\"\"\n Determines if num is a prime number.\n \"\"\"\n if num <= 1:\n return False\n ... | trial_gpt4o_9 | {
"original_instruction": "Implementation and Extension of Diffie-Hellman Key Exchange\n\n#### Context:\nAlice and Bob need to securely exchange keys over a public channel. You are tasked with implementing the Diffie-Hellman key exchange protocol. To ensure a robust solution, you will also implement auxiliary functio... | 0.648529 | Data_Structure_38823 | C | [
"prime_check",
"euler_totient",
"find_order",
"find_primitive_root",
"exec_diffie_hellman"
] | 5 | [
[
"exec_diffie_hellman",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | c1aea3bb8e5419248dfae5bd8d01c3c263992d8f | 6140eafb4c64f0605901dab5ca022aa5507bda0e | |||
v1.0 | complete | Data_Structure | Data_Structure_39000_C | def matrix_power(mat: list, n: int) -> list:
""" Compute the matrix raised to the power `n` efficiently.
>>> matrix_power([[1, 2], [3, 4]], 0)
[[1, 0], [0, 1]]
>>> matrix_power([[1, 2], [3, 4]], 1)
[[1, 2], [3, 4]]
>>> matrix_power([[1, 2], [3, 4]], 2)
[[7, 10], [15, 22]]
>>> matrix... | def matrix_multiply(A, B):
"""
Multiplies two matrices A and B
"""
d = len(A)
result = [[0] * d for _ in range(d)]
for i in range(d):
for j in range(d):
for k in range(d):
result[i][j] += A[i][k] * B[k][j]
return result
def identity_matrix(d):
"""
... | from solution import matrix_power
def test_matrix_power_identity():
mat = [
[1, 2],
[3, 4]
]
n = 0
expected = [
[1, 0],
[0, 1]
]
assert matrix_power(mat, n) == expected
def test_matrix_power_one():
mat = [
[1, 2],
[3, 4]
]
n = 1
e... | [
{
"docstring": "Multiplies two matrices A and B",
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": "Returns an identity matrix of size d x d",
"function_declaration": "def identity_matrix(d):",
"fun... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_multiply(mat1, mat2):\n \"\"\"\n Helper function to multiply two matrices mat1 and mat2.\n \"\"\"\n d = len(mat1)\n result = [[0] * ... | trial_gpt4o_2 | {
"original_instruction": "### Problem: Optimized Matrix Power Calculation\n\nYou are given a square matrix `mat` of size `d x d` and an integer `n`. Your task is to compute the matrix raised to the power `n` efficiently.\n\n### Input\n- `mat`: A list of lists representing a `d x d` matrix, where `d` is an integer (1... | 0.526687 | Data_Structure_39000 | C | [
"matrix_multiply",
"identity_matrix",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity_matrix"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 98d0c7bb7b6f0647a12f3ec171269635854e630e | 12af1242f17fa90099d7273687913b610c80c6be | |||
v1.0 | complete | Data_Structure | Data_Structure_39240_C | from typing import List, Union
def radix_sort_enhanced(arr: List[Union[int, float]], precision: int) -> List[Union[int, float]]:
""" Perform an enhanced Radix Sort that handles negative integers and floating-point numbers,
based on digit precision.
:param arr: A list of integers and floating-point nu... | from typing import List, Union
def get_digit(number, digit_index, base=10):
"""
Extracts the digit at the specified index from the right.
"""
return (abs(number) // base ** digit_index) % base
def counting_sort(arr, digit_index, base=10):
"""
Performs a counting sort on the given digit index.
... | from solution import radix_sort_enhanced
def test_empty_list():
assert radix_sort_enhanced([], 2) == []
def test_single_element_list():
assert radix_sort_enhanced([5], 2) == [5]
assert radix_sort_enhanced([5.5], 2) == [5.5]
def test_positive_integers():
assert radix_sort_enhanced([170, 45, 75, 90], 2... | [
{
"docstring": "Extracts the digit at the specified index from the right.",
"function_declaration": "def get_digit(number, digit_index, base=10):",
"function_name": "get_digit",
"parameter_list": "(number, digit_index, base=10)"
},
{
"docstring": "Performs a counting sort on the given digit ... | [
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, Union\n\ndef counting_sort(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n \n output = [0] * n\n count = [0] * 1... | trial_gpt4o_9 | {
"original_instruction": "### Context\n\nRadix Sort is an efficient non-comparative integer sorting algorithm that sorts numbers by processing individual digits. This algorithm sorts the elements by iteratively processing digits from the least significant to the most significant digit using a bucket-based approach.\... | 0.637921 | Data_Structure_39240 | C | [
"get_digit",
"counting_sort",
"radix_sort",
"handle_negative_numbers",
"handle_floats",
"radix_sort_enhanced"
] | 6 | [
[
"counting_sort",
"get_digit"
],
[
"handle_floats",
"radix_sort"
],
[
"handle_negative_numbers",
"radix_sort"
],
[
"radix_sort",
"counting_sort"
],
[
"radix_sort_enhanced",
"handle_floats"
],
[
"radix_sort_enhanced",
"handle_negative_numbers"
]
... | 6 | [] | false | [] | false | pytest | true | [] | true | 7db765bda953ea92885d2324e3f903031170a4f5 | ec07db607c04edc77ec54cc98bd74b0e80be2e78 | |||
v1.0 | complete | Data_Structure | Data_Structure_39408_C | from typing import List
def bucket_sort(arr: List[int]) -> List[int]:
"""
Implement an optimized bucket sort algorithm. Given an array of non-negative integers, distribute
the elements into a fixed number of buckets, sort each bucket using insertion sort, and then
concatenate the buckets to get the ... | from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def bucket_sort(arr: List[int]) -> List[int... | from solution import bucket_sort
def test_bucket_sort_basic():
assert bucket_sort([4, 2, 2, 8, 3, 3, 1]) == [1, 2, 2, 3, 3, 4, 8]
assert bucket_sort([5, 1, 4, 2]) == [1, 2, 4, 5]
def test_bucket_sort_empty():
assert bucket_sort([]) == []
def test_bucket_sort_single_element():
assert bucket_sort([5]) ... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def bucket_sort(arr):",
"function_name": "bucket_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insertion_sort(bucket):\n for i in range(1, len(bucket)):\n key = bucket[i]\n j = i - 1\n while j >= 0 and bucket[j] > key:\n ... | trial_gpt4o_1 | {
"original_instruction": "You are tasked with implementing an optimized bucket sort algorithm. Given an array of non-negative integers, distribute the elements into a fixed number of buckets, sort each bucket using insertion sort, and then concatenate the buckets to get the final sorted list.\n\n### Function Signatu... | 0.613396 | Data_Structure_39408 | C | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 41f188ac84e6c72a3f26ec011d8f57850c11f18d | 8a99ef95637f06f3f24847520003ad1dc85e70de | |||
v1.0 | complete | Data_Structure | Data_Structure_39037_C | from typing import List
def search_insert(array, val):
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def insertion_sort(array: List[int]) -> List[int]:
... | from typing import List
def search_insert(array, val):
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def insertion_sort(array: List[int]) -> List[int]:
... | from solution import insertion_sort
def test_empty_array():
assert insertion_sort([]) == []
def test_single_element_array():
assert insertion_sort([1]) == [1]
def test_sorted_array():
assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert insertion_sort([5,... | [
{
"docstring": null,
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": null,
"function_declaration": "def insertion_sort(array):",
"function_name": "insertion_sort",
"parameter_list": "(a... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n Helper function to find the appropriate position for a given... | trial_gpt4o_2 | {
"original_instruction": "### Coding Problem: Enhanced Insertion Sort\n\nYou are given an unsorted list of integers. Your task is to implement an insertion sort algorithm using the given helper function `search_insert`. The helper function can be used to find the index where an element belongs in the sorted portion ... | 0.673019 | Data_Structure_39037 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2c9957e60573e3cc9c641d01e6c8c2a04bc2784c | 5ffa80f69675f7a8330cc23e552e585d14c00c7d | |||
v1.0 | complete | Data_Structure | Data_Structure_38957_C | from typing import List, Union
def get_determinant(matrix: List[List[float]]) -> float:
"""
Computes the determinant of a matrix recursively.
"""
pass
def get_minor(matrix: List[List[float]], i: int, j: int) -> List[List[float]]:
"""
Returns the minor matrix after removing the i-th row and j-t... | from typing import List, Union
def get_determinant(matrix: List[List[float]]) -> float:
"""
Computes the determinant of a matrix recursively.
"""
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]
determ... | from solution import invert_matrix
def test_invert_matrix_3x3():
matrix = [
[2, -1, 0],
[-1, 2, -1],
[0, -1, 2]
]
expected = [
[0.75, 0.5, 0.25],
[0.5, 1.0, 0.5],
[0.25, 0.5, 0.75]
]
assert invert_matrix(matrix) == expected
def test_invert_matrix_non... | [
{
"docstring": "Computes the determinant of a matrix recursively.",
"function_declaration": "def get_determinant(matrix):",
"function_name": "get_determinant",
"parameter_list": "(matrix)"
},
{
"docstring": "Returns the minor matrix after removing the i-th row and j-th column.",
"functio... | [
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 numpy as np\n\ndef invert_matrix(matrix):\n if not array_is_matrix(matrix):\n return -1 # Non-square matrix\n \n n = len(matrix)\n ... | trial_gpt4o_9 | {
"original_instruction": "### Matrix Inversion Challenge\n\n#### Problem Description\nYou are given an n x n matrix and are tasked with computing its inverse, if it exists. Matrix inversion is a fundamental operation in linear algebra with applications ranging from solving linear systems to computer graphics.\n\n###... | 0.557718 | Data_Structure_38957 | C | [
"get_determinant",
"get_minor",
"transpose",
"invert_matrix"
] | 4 | [
[
"get_determinant",
"get_minor"
],
[
"invert_matrix",
"get_determinant"
],
[
"invert_matrix",
"get_minor"
],
[
"invert_matrix",
"transpose"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 3830802ab9c03956be0e67434d97307836af7303 | c500479c6f26067b492b6b272f00f171d7c16597 | |||
v1.0 | complete | Data_Structure | Data_Structure_39227_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
""" Determine if tree t is a subtree of tree s.
Args:
s (TreeNode): The root of the main binary tree.
... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
if not s:
return False
if is_same_tree(s, t):
return True
return is_subtree(s.left, t) or is_sub... | import pytest
from solution import TreeNode, is_subtree
def test_example_1():
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.left.right = TreeNode(2)
t = TreeNode(4)
t.left = TreeNode(1)
t.right = TreeNode(2)
assert is_subtree(s, t) ... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_1 | {
"original_instruction": "### Subtree Check in Binary Trees\n\nGiven two binary trees `s` and `t`, determine if `t` is a subtree of `s`. A subtree of a binary tree `s` is any node `n` of `s` and all of its descendants.\n\n#### Input:\n- `s`: The root node of a binary tree.\n- `t`: The root node of another binary tre... | 0.619732 | Data_Structure_39227 | C | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 39c5a44623170392d8800f8e5a341f9cc5a34b8d | acccb16902bd8097caa48def2dd1f03a34486f1d | |||
v1.0 | complete | Data_Structure | Data_Structure_39454_C | def enhanced_is_prime(n: int, k: int = 10) -> bool:
"""
Determine if a given integer is prime using an enhanced Rabin-Miller primality test.
:param n: Integer to test for primality.
:param k: Number of iterations for accuracy, default is 10.
:return: True if n is probably prime, False if n is compo... | import random
def is_prime_trial_division(n):
""" Check for small primes using trial division up to 20. """
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 enhanced_is_prime
def test_small_primes():
assert enhanced_is_prime(2) == True
assert enhanced_is_prime(3) == True
assert enhanced_is_prime(5) == True
def test_small_composites():
assert enhanced_is_prime(1) == False
assert enhanced_is_prime(4) == False
assert enhanced_is_... | [
{
"docstring": "Check for small primes using trial division up to 20. ",
"function_declaration": "def is_prime_trial_division(n):",
"function_name": "is_prime_trial_division",
"parameter_list": "(n)"
},
{
"docstring": "Efficiently compute (a^d) % n ",
"function_declaration": "def power_m... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime_trial_division(n):\n \"\"\" Check for small primes using trial division up to 20. \"\"\"\n if n <= 1:\n return Fals... | trial_gpt4o_0 | {
"original_instruction": "### Question: Enhanced Prime Detection for Cryptographic Applications\n\n#### Background:\nIn cryptographic systems, it is vital to use large prime numbers for creating secure keys. While the traditional Rabin-Miller primality test provides good results, there are scenarios where higher con... | 0.741024 | Data_Structure_39454 | C | [
"is_prime_trial_division",
"power_mod",
"rabin_miller",
"enhanced_is_prime"
] | 4 | [
[
"enhanced_is_prime",
"is_prime_trial_division"
],
[
"enhanced_is_prime",
"rabin_miller"
],
[
"rabin_miller",
"power_mod"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 2e090f659dfae752e14127f9e2f65478f8e98874 | 5446fd305464a800ab8971f669fd097eef18b7d8 | |||
v1.0 | complete | Data_Structure | Data_Structure_39042_C | def generate_key(k: int) -> Tuple[int, int, int]:
"""
Generate RSA key pair.
Args:
- k: The bit length for the modulus n.
Returns:
- Tuple containing (n, e, d).
"""
pass
def encrypt(data: int, e: int, n: int) -> int:
"""
Encrypt data using the public key (n, e).
Args:
-... | import random
from sympy import isprime, mod_inverse
from typing import Tuple
def generate_prime_candidate(bit_length: int) -> int:
# Use the random library to generate a random odd integer of bit_length bits
p = random.getrandbits(bit_length)
# Ensure that it is odd by setting the last bit to 1
p |= (... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16)
assert isinstance(n, int) and n > 0
assert isinstance(e, int) and e > 0
assert isinstance(d, int) and d > 0
def test_encrypt_decrypt():
n, e, d = generate_key(16)
message = 42
encrypted_... | [
{
"docstring": null,
"function_declaration": "def generate_prime_candidate(bit_length):",
"function_name": "generate_prime_candidate",
"parameter_list": "(bit_length)"
},
{
"docstring": null,
"function_declaration": "def generate_large_prime(bit_length):",
"function_name": "generate_... | [
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 typing import Tuple\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime_candidate(length):\n \"\"\" Generate an odd integer r... | trial_gpt4o_2 | {
"original_instruction": "### RSA Key Generation and Encryption/Decryption\n\nYou are asked to implement the RSA encryption algorithm including key generation, encryption, and decryption functions. For this task, you need to demonstrate your understanding of the RSA algorithm by implementing an optimized key generat... | 0.696953 | Data_Structure_39042 | C | [
"generate_prime_candidate",
"generate_large_prime",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_large_prime"
],
[
"generate_large_prime",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 962519c9ebafac7155d35836a1bd0b33cb0f28af | afaf3440d04973c2f614bfc4983056227a2fa05e | |||
v1.0 | complete | Data_Structure | Data_Structure_38972_C | from typing import List
def search_insert(arr: List[int], val: int) -> int:
"""
Uses binary search to find the index at which val should be inserted.
Assumes arr is sorted.
"""
low, high = 0, len(arr)
while low < high:
mid = (low + high) // 2
if arr[mid] < val:
low =... | from typing import List
def search_insert(arr: List[int], val: int) -> int:
"""
Uses binary search to find the index at which val should be inserted.
Assumes arr is sorted.
"""
low, high = 0, len(arr)
while low < high:
mid = (low + high) // 2
if arr[mid] < val:
low =... | from solution import insertion_sort
def test_insertion_sort_empty():
assert insertion_sort([]) == []
def test_insertion_sort_single_element():
assert insertion_sort([1]) == [1]
def test_insertion_sort_sorted_array():
assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_insertion_sort_rever... | [
{
"docstring": "Uses binary search to find the index at which val should be inserted.\nAssumes arr is sorted.",
"function_declaration": "def search_insert(arr, val):",
"function_name": "search_insert",
"parameter_list": "(arr, val)"
},
{
"docstring": "Sorts a list of integers in non-decreasi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(sorted_list: List[int], target: int) -> int:\n \"\"\"\n Use binary search to find the index at which target... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement an Efficient Insertion Sort\n\nYou are to implement the `insertion_sort` function that sorts a list of integers in non-decreasing order using the binary search method provided.\n\n#### Function Signature\n```python\ndef insertion_sort(arr: List[int]) -> List[int]:\n`... | 0.638247 | Data_Structure_38972 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 76b64bed491f1df5c8469ec30ed1b8a9f2fba0b8 | 19d014b883325431fa60aee5f1ff4a71f70f117e | |||
v1.0 | complete | Data_Structure | Data_Structure_39084_C | def iterating_markov_chain(chain: dict, initial_state: str, steps: int) -> list:
"""
Simulates a Markov chain for a given number of steps starting from an initial state.
Args:
chain (dict): A dictionary representing the Markov chain where key is the current state
and value is ano... | import random
def iterating_markov_chain(chain: dict, initial_state: str, steps: int) -> list:
"""
Simulates a Markov chain for a given number of steps starting from an initial state.
Args:
chain (dict): A dictionary representing the Markov chain where key is the current state
a... | from solution import iterating_markov_chain
def test_iterating_single_step():
chain = {'A': {'A': 1.0}}
assert iterating_markov_chain(chain, 'A', 1) == ['A', 'A']
def test_iterating_multiple_steps():
chain = {
'A': {'A': 0.6, 'E': 0.4},
'E': {'A': 0.7, 'E': 0.3}
}
steps = 5
res... | [
{
"docstring": "Simulates a Markov chain for a given number of steps starting from an initial state.\n\nArgs:\nchain (dict): A dictionary representing the Markov chain where key is the current state \n and value is another dictionary representing the next state along with their \n tran... | [
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 iterating_markov_chain(chain: dict, initial_state: str, steps: int) -> list:\n \"\"\"\n This function performs transitions in the g... | trial_gpt4o_2 | {
"original_instruction": "### Question\n\nYou are tasked with enhancing a Markov Chain implementation, specifically modifying the `iterating_markov_chain` function to include a stopping criterion. Instead of running indefinitely, this function should now take an additional parameter, `steps`, that dictates the numbe... | 0.506358 | Data_Structure_39084 | C | [
"iterating_markov_chain",
"next_state"
] | 2 | [
[
"iterating_markov_chain",
"next_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1d092eb90a9d3503ccfcb52f8db7ffd1bf42f028 | bdb9b197d11856848269b223c43ecd14e785d1cd | |||
v1.0 | complete | Data_Structure | Data_Structure_39642_C | def optimized_radix_sort(arr):
""" Implements an optimized version of the radix sort algorithm to sort an array of non-negative integers in ascending order.
>>> optimized_radix_sort([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66, 75, 90, 170, 802]
>>> optimized_radix_sort([5, 3, 8, 6, 2, 7])
[2, ... | def counting_sort(arr, exp):
"""
A helper function to perform counting sort based on the digit represented by exp.
"""
n = len(arr)
output = [0] * n # output array that will have sorted arr
count = [0] * 10 # since digits are from 0-9
# Store count of occurrences in count[]
for i in r... | from solution import optimized_radix_sort
def test_sorted_array():
assert optimized_radix_sort([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_reverse_sorted_array():
assert optimized_radix_sort([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_random_array... | [
{
"docstring": "A helper function to perform 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 do Radix Sort",
"function_declaratio... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n \"\"\"\n A function to do counting sort of arr[] according to the digit represented by exp.\n \"\"\"\n n = len(arr)... | trial_gpt4o_1 | {
"original_instruction": "### Radix Sort with Digits in Array\nGiven an array of non-negative integers, implement an optimized version of the radix sort algorithm. The goal is to sort the array in ascending order based on individual digits, processing from least significant to most significant digits. The given impl... | 0.679984 | Data_Structure_39642 | C | [
"counting_sort",
"optimized_radix_sort"
] | 2 | [
[
"optimized_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 04c23fdcbd19409e2a8f2bfc0558778f7a4f450b | f49ec9d55311d6475e4b4bb649b5fc0fbd87bc5f | |||
v1.0 | complete | Data_Structure | Data_Structure_39601_C | def compute_factorial(n, mod=None):
"""
This function will calculate the factorial of 'n'.
If 'n' > 10,000, use the iterative approach.
If 'mod' is provided, compute n! % mod.
:param n: (int) The non-negative integer for which we want to compute the factorial.
:param mod: (Optional[int]) The mo... | def compute_factorial(n, mod=None):
"""
This function will calculate factorial of 'n'.
If 'n' > 10,000, use the iterative approach.
If 'mod' is provided, compute n! % mod.
:param n: (int) The non-negative integer for which we want to compute the factorial.
:param mod: (Optional[int]) The mo... | from solution import compute_factorial
def test_factorial_simple():
assert compute_factorial(5) == 120
def test_factorial_with_mod():
assert compute_factorial(5, 3) == 0
def test_factorial_zero():
assert compute_factorial(0) == 1
def test_factorial_large_n():
assert compute_factorial(10001) > 0 # w... | [
{
"docstring": "This function will calculate factorial of 'n'.\nIf 'n' > 10,000, use the iterative approach.\nIf 'mod' is provided, compute n! % mod.\n\n:param n: (int) The non-negative integer for which we want to compute the factorial.\n:param mod: (Optional[int]) The modulus value for the factorial computati... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def compute_factorial(n, mod=None):\n \"\"\"\n This function will calculate factorial of 'n'.\n If 'n' > 10,000, use the iterative approach.\n If ... | trial_gpt4o_9 | {
"original_instruction": "## Coding Assessment Question\n\n### Context\n\nYou have been given two functions that calculate the factorial of a given non-negative integer, `n`. One implementation uses an iterative approach while the other uses a recursive approach. Both functions also support calculating the factorial... | 0.714802 | Data_Structure_39601 | C | [
"compute_factorial",
"compute_factorial_iter",
"compute_factorial_recur"
] | 3 | [
[
"compute_factorial",
"compute_factorial_iter"
],
[
"compute_factorial",
"compute_factorial_recur"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | dc2884cf1fff0eb6c6c1ab1a99ed608cb324dd4c | 854d3bf4c2c46b411160598f0f665e15a6ea7d52 | |||
v1.0 | complete | Data_Structure | Data_Structure_38843_C | from typing import List
def find_words(board: List[List[str]], words: List[str]) -> List[str]:
"""
Consider the problem of searching words from a given list in a 2D grid of characters.
This task involves implementing an efficient algorithm using both a Trie data structure
and a backtracking method. ... | class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
def build_trie(words):
root = TrieNode()
for word in words:
node = root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
... | from solution import find_words
def test_example_case():
board = [
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath","pea","eat","rain"]
assert sorted(find_words(board, words)) == ["eat", "oath"]
def test_single_letter_words():... | [] | [
0,
0,
0,
0,
1,
0,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict\n\nclass TrieNode:\n def __init__(self):\n self.children: Dict[str, TrieNode] = {}\n self.end_of_word = False\n... | trial_gpt4o_9 | {
"original_instruction": "Consider the problem of searching words from a given list in a 2D grid of characters. This task involves implementing an efficient algorithm using both a Trie data structure and a backtracking method. You are provided with a grid (board) and a list of words.\n\n### Goals:\n1. Build a Trie d... | 0.573543 | Data_Structure_38843 | C | [
"build_trie",
"find_words"
] | 2 | [
[
"find_words",
"build_trie"
]
] | 1 | [] | false | [
"TrieNode"
] | true | pytest | true | [] | true | 82cb3036ed6df45796bdcbff8b2205d8ac9439e1 | 6c15af19b5f5a8b8eb54a45dacad981374d5a7c8 | |||
v1.0 | complete | Data_Structure | Data_Structure_39496_C | def multiply_bitwise_operator(a: int, b: int) -> int:
""" Multiply two positive integers using bitwise operations without using the '*' operator.
>>> multiply_bitwise_operator(3, 4)
12
>>> multiply_bitwise_operator(2, 3)
6
"""
# your code here
pass
from solution import multiply_bitwise... | def multiply_bitwise_operator(a: int, b: int) -> int:
"""
Multiplies two positive integers using bitwise operations.
"""
result = 0
while b > 0:
# If the lowest bit of b is set, add current value of a to result
if b & 1:
result = add_bitwise(result, a)
# Double t... | from solution import multiply_bitwise_operator
def test_multiply_small_numbers():
assert multiply_bitwise_operator(3, 4) == 12
assert multiply_bitwise_operator(2, 3) == 6
def test_multiply_with_one():
assert multiply_bitwise_operator(1, 5) == 5
assert multiply_bitwise_operator(5, 1) == 5
def test_mul... | [
{
"docstring": "Multiplies two positive integers using bitwise operations.",
"function_declaration": "def multiply_bitwise_operator(a, b):",
"function_name": "multiply_bitwise_operator",
"parameter_list": "(a, b)"
},
{
"docstring": "Adds two positive integers using bitwise operations.",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply_bitwise_operator(a, b):\n \"\"\"\n Multiply two positive integers using bitwise operations.\n \n Args:\n a (int): The first positi... | trial_gpt4o_2 | {
"original_instruction": "## Problem Statement\n\nYou are tasked with implementing an algorithm that multiplies two positive integers without using the '*' operator. The function should utilize only bitwise operations (e.g., AND, OR, XOR, NOT, SHIFT).\n\n### Input\nTwo positive integers `a` and `b`.\n\n### Output\nA... | 0.630466 | Data_Structure_39496 | C | [
"multiply_bitwise_operator",
"add_bitwise"
] | 2 | [
[
"multiply_bitwise_operator",
"add_bitwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f617d225278259f5cd2b8ebc0845aecf2977df13 | 25c8c5c459f3051d0e49560371a36978e21a4268 | |||
v1.0 | complete | Data_Structure | Data_Structure_38755_C | from typing import List
def maximum_flow_bfs(adjacency_matrix: List[List[int]]) -> int:
""" Computes the maximum flow from the source (node 0) to the sink (last node)
using the BFS method.
>>> graph = [[0, 16, 13, 0, 0, 0],
... [0, 0, 10, 12, 0, 0],
... [0, 4, 0, 0, 14, 0],
.... | from typing import List
from collections import deque
def bfs(residual_graph, source, sink, parent):
visited = [False] * len(residual_graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(residual_graph[u]):
... | from solution import maximum_flow_bfs
def test_maximum_flow_example_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow_bfs(graph) == 23
def test... | [
{
"docstring": null,
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(adjacency_matrix):",
"function_name"... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bfs(rGraph: List[List[int]], s: int, t: int, parent: List[int]) -> bool:\n visited = [False] * len(rGraph)\n queue = []\n... | trial_gpt4o_2 | {
"original_instruction": "### Maximum Network Flow: Deep River Crossing\n\nYou're working on a network flow problem where you must determine the maximum flow of materials from the upstream source (node 0) to the downstream sink (the last node) over a series of pathways represented in matrix form.\n\nWrite a function... | 0.652987 | Data_Structure_38755 | C | [
"bfs",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 96e82f5500869123675f53d63a490cab945eccfe | 7a2839821aa4145ca0e0fb16b0d7cc9bde8fc48c | |||
v1.0 | complete | Data_Structure | Data_Structure_39636_C | from typing import List
def radix_sort_with_optimization(arr: List[int]) -> List[int]:
""" Sorts a list of mixed integers in non-decreasing order using an optimized Radix Sort algorithm.
Args:
arr (List[int]): A list of integers where -10^9 <= arr[i] <= 10^9.
Returns:
List[int]: A sorted list... | from typing import List
def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = abs(arr[i]) // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
for i in range(n - 1, -1, -1):
... | from solution import radix_sort_with_optimization
def test_radix_sort_with_mixed_integers():
assert radix_sort_with_optimization([170, -12, 45, 75, -90, 802, 24, 2, 66]) == [-90, -12, 2, 24, 45, 66, 75, 170, 802]
def test_radix_sort_with_only_negatives():
assert radix_sort_with_optimization([-5, -10, -3, -1])... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
},
{
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, base: int = 10) -> List[int]:\n \"\"\"\n A function to do counting sort of arr[] ... | trial_gpt4o_1 | {
"original_instruction": "**Scenario**: You are developing a software module for a database system that needs to efficiently sort large datasets of non-negative integers. To achieve this, you decide to implement Radix Sort due to its efficient handling of integer data.\n\n### Task\nImplement the function `radix_sort... | 0.666295 | Data_Structure_39636 | C | [
"counting_sort",
"radix_sort",
"radix_sort_with_optimization"
] | 3 | [
[
"radix_sort",
"counting_sort"
],
[
"radix_sort_with_optimization",
"radix_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3673f7ffaebf8801e5c44bbfc62d1b46efd69633 | 46c9d84a7969bf3694794ab3d105997b85fe983a | |||
v1.0 | complete | Data_Structure | Data_Structure_39579_C | def secure_diffie_hellman_key_exchange(a: int, p: int) -> bool:
"""Perform a validated variation of the Diffie-Hellman Key Exchange algorithm.
Parameters:
a (int): A candidate primitive root.
p (int): A large candidate prime number.
Returns:
bool: True if the Diffie-Hellman Key Exchange is suc... | from math import isqrt
def is_prime(p):
"""
Check if a number p is a prime number.
"""
if p <= 1:
return False
if p <= 3:
return True
if p % 2 == 0 or p % 3 == 0:
return False
i = 5
while i * i <= p:
if p % i == 0 or p % (i + 2) == 0:
return F... | from solution import secure_diffie_hellman_key_exchange
def test_prime_and_primitive_root_success():
# 3 is a primitive root of prime number 7
assert secure_diffie_hellman_key_exchange(3, 7) == True
def test_prime_and_invalid_primitive_root():
# 4 is not a primitive root of prime number 7
assert secur... | [
{
"docstring": "Check if a number p is a prime number.",
"function_declaration": "def is_prime(p):",
"function_name": "is_prime",
"parameter_list": "(p)"
},
{
"docstring": "Compute the greatest common divisor of a and b.",
"function_declaration": "def gcd(a, b):",
"function_name": "g... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def prime_check(n):\n if n <= 1:\n return False\n if n in (2, 3):\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n ... | trial_gpt4o_4 | {
"original_instruction": "on Diffie-Hellman Key Exchange\n\n### Objective\nYour task is to implement a validated variation of the Diffie-Hellman Key Exchange algorithm. You need to ensure that the inputs, particularly the prime number and its primitive root, are valid and lead to a successful key exchange.\n\n### Fu... | 0.538106 | Data_Structure_39579 | C | [
"is_prime",
"gcd",
"power_mod",
"find_primitive_root",
"secure_diffie_hellman_key_exchange"
] | 5 | [
[
"find_primitive_root",
"is_prime"
],
[
"find_primitive_root",
"power_mod"
],
[
"secure_diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"secure_diffie_hellman_key_exchange",
"is_prime"
],
[
"secure_diffie_hellman_key_exchange",
"power_mod"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 4c084ba5527d231f8e4797a8a93f5dd74d535376 | f92ee518dfa547cc3e6aa8f650c7c2929d926946 | |||
v1.0 | complete | Data_Structure | Data_Structure_39614_C | from typing import List
from math import gcd
def euler_totient(n: int) -> int:
""" Compute the Euler's Totient function of '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... | from math import gcd
from typing import List
def euler_totient(n: int) -> int:
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1
if n > 1:
result -= result // n
return result
def ... | from solution import find_order, find_primitive_root
def test_find_order():
assert find_order(3, 10) == 4
assert find_order(7, 10) == 4
assert find_order(2, 8) == -1
assert find_order(2, 9) == 6
assert find_order(1, 7) == 1
def test_find_primitive_root():
assert find_primitive_root(10) == [3, ... | [
{
"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,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef find_order(a, n):\n \"\"\"\n Returns the smallest positive integer k such tha... | trial_gpt4o_9 | {
"original_instruction": "### Primitive Root Finder\n\nYou are given a number `n`, and your task is to find all primitive roots of this number. In modular arithmetic, a primitive root of a prime `n` is an integer `g` such that every number between 1 and `n-1` can be expressed as `g^k` mod `n` for some integer `k`.\n... | 0.576809 | Data_Structure_39614 | C | [
"euler_totient",
"find_order",
"find_primitive_root"
] | 3 | [
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"find_order"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2be05ecc2e91cf2d6d6e62e643d68d7634d258b0 | 692286bfeb3389b04b896af8870f590085023f00 | |||
v1.0 | complete | Data_Structure | Data_Structure_39417_C | import random
from typing import List
def optimized_shuffle_sort(arr: List[int], simulation: bool = False) -> List[int]:
""" Sort an array using a combination of shuffling and partial sorting.
The sorting is done by breaking the array into chunks, sorting each chunk,
shuffling these sorted chunks, and fina... | import random
from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def merge_sorted_chunks(chunk... | from solution import optimized_shuffle_sort
def test_sorted_array():
assert optimized_shuffle_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert optimized_shuffle_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_unsorted_array():
assert optimized_shuffle_sort([3, 1, 4, 1, 5... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge_sorted_chunks(chunks):",
"function_name": "merge_sorted_chunks",
"parameter_list": "(ch... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef insertion_sort(arr: List[int]) -> List[int]:\n for i in range(1, len(arr)):\n key = arr[i]\n j ... | trial_gpt4o_0 | {
"original_instruction": "Optimized Shuffle Sort Challenge\n\nGiven the highly inefficient nature of bogo sort, it's paramount to leverage randomness efficiently. Design and implement a new sorting algorithm that uses randomness but ensures better performance than bogo sort while maintaining simplicity. \n\n#### Que... | 0.651154 | Data_Structure_39417 | C | [
"insertion_sort",
"merge_sorted_chunks",
"optimized_shuffle_sort"
] | 3 | [
[
"optimized_shuffle_sort",
"insertion_sort"
],
[
"optimized_shuffle_sort",
"merge_sorted_chunks"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1d1947ffdf91b9c2e4de8eb26c5cf662a8927e79 | bfcb673bfb2f13b59c11fd9602287f6153b350a9 | |||
v1.0 | complete | Data_Structure | Data_Structure_39694_C | import math
from typing import List
def _l2_distance(vec: List[float]) -> float:
"""
Helper function to calculate the L2 norm of a vector.
"""
pass
def cosine_similarity(vec1: List[float], vec2: List[float]) -> float:
"""
Calculate cosine similarity between two vectors.
Args:
vec1... | import math
def _l2_distance(vec):
"""
Helper function to calculate the L2 norm of a vector.
"""
return math.sqrt(sum(x ** 2 for x in vec))
def cosine_similarity(vec1, vec2):
"""
Calculate cosine similarity between two vectors.
"""
if len(vec1) != len(vec2):
raise ValueError("V... | def test_cosine_similarity_same_vector():
assert math.isclose(cosine_similarity([1, 2, 3], [1, 2, 3]), 1.0)
def test_cosine_similarity_orthogonal_vectors():
assert math.isclose(cosine_similarity([1, 0, 0], [0, 1, 0]), 0.0)
def test_cosine_similarity_example_1():
assert math.isclose(cosine_similarity([1, 1... | [
{
"docstring": "Helper function to calculate the L2 norm of a vector.",
"function_declaration": "def _l2_distance(vec):",
"function_name": "_l2_distance",
"parameter_list": "(vec)"
},
{
"docstring": "Calculate cosine similarity between two vectors.",
"function_declaration": "def cosine_s... | [
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 _l2_norm_squared(vec):\n \"\"\"\n Helper function to calculate the L2 norm squared of a vector.\n \"\"\"\n return sum(x ** 2 fo... | trial_gpt4o_1 | {
"original_instruction": "### Cosine Similarity Function Implementation\n\n**Context**: Cosine similarity is a measure often used in machine learning and information retrieval to determine the similarity between two vectors. This is particularly useful in scenarios such as document comparison, recommendation systems... | 0.598653 | Data_Structure_39694 | C | [
"_l2_distance",
"cosine_similarity"
] | 2 | [
[
"cosine_similarity",
"_l2_distance"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 9c8df6d199ba146699c6dc9be8e533125f0a8e67 | efb4a0545691792fe999692b5a4ce7c407cbaf20 | |||
v1.0 | complete | Data_Structure | Data_Structure_39719_C | def gcd_optimized(a: int, b: int) -> int:
"""
Returns the greatest common divisor of a and b using Euclid's algorithm.
Raises ValueError for non-integer or zero inputs.
>>> gcd_optimized(48, 18) == 6
>>> gcd_optimized(-48, -18) == 6
>>> gcd_optimized(0, 18) # Raises ValueError
"""
def l... | def gcd_optimized(a, b):
"""
Returns the greatest common divisor of a and b using Euclid's algorithm.
Raises ValueError for non-integer or zero inputs.
"""
if not isinstance(a, int) or not isinstance(b, int):
raise ValueError("Inputs must be integers.")
a, b = abs(a), abs(b)
... | from solution import gcd_optimized, lcm_optimized, gcd_bitwise
import pytest
def test_gcd_optimized_positive_integers():
assert gcd_optimized(48, 18) == 6
def test_gcd_optimized_negative_integers():
assert gcd_optimized(-48, -18) == 6
def test_gcd_optimized_non_integers():
with pytest.raises(ValueError):... | [
{
"docstring": "Returns the greatest common divisor of a and b using Euclid's algorithm.\nRaises ValueError for non-integer or zero inputs.",
"function_declaration": "def gcd_optimized(a, b):",
"function_name": "gcd_optimized",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the least ... | [
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 gcd_optimized(a, b):\n \"\"\"\n Calculate the Greatest Common Divisor (GCD) of a and b using Euclid's algorithm.\n \"\"\"\n if not isinstance(... | trial_gpt4o_1 | {
"original_instruction": "### Question:\n\n**Problem Statement: Greatest Common Divisor Using Advanced Methods**\n\nYour task is to implement the following functions using the described algorithms and constraints:\n\n1. **gcd_optimized(a: int, b: int) -> int**:\n - Calculate the greatest common divisor of `a` and ... | 0.726514 | Data_Structure_39719 | C | [
"gcd_optimized",
"lcm_optimized",
"gcd_bitwise"
] | 3 | [
[
"lcm_optimized",
"gcd_optimized"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3e3c344aa19473cbb5060d7574904c030a97d3e9 | de83b15368e6714dbe6f19acf328cfd2622d23da | |||
v1.0 | complete | Data_Structure | Data_Structure_39711_C | from typing import List
def prime_check(n: int) -> bool:
""" Check if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return Fals... | def prime_check(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def prime_sum(limit):
"""
Returns t... | from solution import prime_sum, prime_subsequence_sum
def test_prime_sum():
assert prime_sum(10) == 17
assert prime_sum(1) == 0
assert prime_sum(2) == 2
assert prime_sum(100) == 1060
assert prime_sum(17) == 58
def test_prime_subsequence_sum():
assert prime_subsequence_sum([3, 4, 7, 10, 11]) ==... | [
{
"docstring": null,
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers less than or equal to limit.",
"function_declaration": "def prime_sum(limit):",
"function_name": "prime_... | [
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 prime_check(n):\n \"\"\"\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n... | trial_gpt4o_2 | {
"original_instruction": "### Prime Number Verification and Sum Calculations\n\n#### Problem Statement\n\nGiven the provided `prime_check(n)` function, implement a new function `prime_sum(limit)` that calculates the sum of all prime numbers less than or equal to a given integer `limit`. You will then extend `prime_s... | 0.743566 | Data_Structure_39711 | C | [
"prime_check",
"prime_sum",
"prime_subsequence_sum"
] | 3 | [
[
"prime_subsequence_sum",
"prime_check"
],
[
"prime_sum",
"prime_check"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 214b310fabbf58b7481cc50ad12e69240d5186c7 | 0dc1064d0629317204d7cfc8a2d40cd3fcb5ae1a | |||
v1.0 | complete | Data_Structure | Data_Structure_39566_C | def iterative_matrix_exponentiation(mat: list, n: int) -> list:
"""
Calculates mat^n by repeated squaring using an iterative approach.
:param mat: A square matrix represented as a list of lists.
:param n: A non-negative integer representing the power to which the matrix will be raised.
:return:... | def matrix_multiply(A, B):
d = len(A)
result = [[0] * d for _ in range(d)]
for i in range(d):
for j in range(d):
for k in range(d):
result[i][j] += A[i][k] * B[k][j]
return result
def identity_matrix(size):
I = [[0 if i != j else 1 for j in range(size)] for i in ... | from solution import iterative_matrix_exponentiation
def test_example_1():
mat = [[1, 1], [1, 0]]
n = 5
expected = [[8, 5], [5, 3]]
assert iterative_matrix_exponentiation(mat, n) == expected
def test_example_2():
mat = [[2, 0], [0, 2]]
n = 3
expected = [[8, 0], [0, 8]]
assert iterative... | [
{
"docstring": null,
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def identity_matrix(size):",
"function_name": "identity_matrix",
"parameter_list": "(size)"
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_multiply(mat1, mat2):\n \"\"\"Multiplies two matrices mat1 and mat2.\"\"\"\n size = len(mat1)\n result = [[0] * size for _ in range(size)]... | trial_gpt4o_2 | {
"original_instruction": "### Matrix Exponentiation in an Optimized Iterative Approach\n\nYou are provided with functions for matrix multiplication, identity matrix creation, and matrix exponentiation using recursion. Your task is to re-implement the `matrix_exponentiation` function iteratively to avoid potential st... | 0.524913 | Data_Structure_39566 | C | [
"matrix_multiply",
"identity_matrix",
"iterative_matrix_exponentiation"
] | 3 | [
[
"iterative_matrix_exponentiation",
"identity_matrix"
],
[
"iterative_matrix_exponentiation",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5e903226cf7b07361baf50dda8cc3e0f2fe4b797 | 1c9f75593d4ecdd0edb79c9a9934b1d9fb9700be | |||
v1.0 | complete | Data_Structure | Data_Structure_39852_C | from typing import List, Tuple
from math import factorial
def prime_factors(n: int) -> List[int]:
i = 2
factors = []
while i * i <= n:
while (n % i) == 0:
factors.append(i)
n //= i
i += 1
if n > 1:
factors.append(n)
return factors
def factorial_prime... | from typing import List, Tuple
from math import factorial
from sympy import primerange
def prime_factors(n: int) -> List[int]:
i = 2
factors = []
while i * i <= n:
while (n % i) == 0:
factors.append(i)
n //= i
i += 1
if n > 1:
factors.append(n)
return... | import pytest
from solution import factorial_prime_factors
def test_factorial_prime_factors_no_mod():
result, factors = factorial_prime_factors(5)
assert result == 120
assert sorted(factors) == [2, 2, 2, 3, 5]
def test_factorial_prime_factors_with_mod():
result, factors = factorial_prime_factors(5, mo... | [
{
"docstring": null,
"function_declaration": "def prime_factors(n):",
"function_name": "prime_factors",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def factorial_prime_factors(n, mod=None):",
"function_name": "factorial_prime_factors",
"parameter_list... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nfrom math import factorial\nfrom sympy import primerange\n\ndef prime_factors(n: int) -> List[int]:\n i = 2\n factors = ... | trial_gpt4o_0 | {
"original_instruction": "### Factorial Calculation with Additional Functionalities\n\n#### Objective\nImplement a function called `factorial_prime_factors` that computes the factorial of a given non-negative integer `n` and also returns the list of prime factors of the factorial result. The function should optional... | 0.827935 | Data_Structure_39852 | C | [
"prime_factors",
"factorial_prime_factors"
] | 2 | [
[
"factorial_prime_factors",
"prime_factors"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 091155986364d9a5aa107f74a8f80b7e9dafef0e | 3090cb042b43af23a2be28aa6797a4fb2a94e1c2 | |||
v1.0 | complete | Data_Structure | Data_Structure_39877_C | def generate_key(k):
"""
Generate RSA keys with a modulus of bit length k.
Parameters:
k (int): Bit length for the modulus n.
Returns:
tuple: A tuple containing (n, e, d)
"""
pass
def encrypt(data, e, n):
"""
Encrypt the given data using the public key (e, n).
... | import random
from sympy import isprime, mod_inverse
def generate_large_prime(bits):
while True:
p = random.getrandbits(bits)
if isprime(p):
return p
def generate_key(k):
"""
Generate RSA keys with a modulus of bit length k.
Parameters:
k (int): Bit length for ... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(512)
assert type(n) == int and type(e) == int and type(d) == int
assert n.bit_length() >= 512
def test_encrypt_decrypt():
n, e, d = generate_key(512)
plaintext = 123456789
encrypted = encry... | [
{
"docstring": null,
"function_declaration": "def generate_large_prime(bits):",
"function_name": "generate_large_prime",
"parameter_list": "(bits)"
},
{
"docstring": "Generate RSA keys with a modulus of bit length k.\n\nParameters:\n k (int): Bit length for the modulus n.\n\nReturns:\n ... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime\nfrom math import gcd\nfrom sympy import mod_inverse\n\ndef generate_large_prime(bits):\n while True:\n num... | trial_gpt4o_2 | {
"original_instruction": "### **Coding Assessment Question: RSA Encryption Implementation**\n\n#### Scenario\nImagine you are tasked with securing a communication channel between a client and a server using RSA encryption. Your job is to implement the functions required to generate RSA keys, encrypt, and decrypt mes... | 0.720916 | Data_Structure_39877 | C | [
"generate_large_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_large_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 6406a8500d398088031abf7505bf8a1620c0e53c | e9a103f1477f0b704a38fabb28c77bbddbab6ac4 | |||
v1.0 | complete | Data_Structure | Data_Structure_39860_C | from typing import List
def enhanced_radix_sort(arr: List[int]) -> List[int]:
"""
Modify the basic Radix Sort algorithm to handle arrays with both
negative and non-negative integers and return a sorted list.
Example:
>>> enhanced_radix_sort([170, -45, 90, 802, 24, 2, 66, -3])
[-45, -3, 2, 24... | from typing import List
def counting_sort_for_radix(arr: List[int], exp: int) -> None:
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 ... | from solution import enhanced_radix_sort
def test_enhanced_radix_sort_typical_case():
assert enhanced_radix_sort([170, -45, 90, 802, 24, 2, 66, -3]) == [-45, -3, 2, 24, 66, 90, 170, 802]
def test_enhanced_radix_sort_mixed_signs():
assert enhanced_radix_sort([5, -3, 0, -1, -2, 3, 2, 1, -4]) == [-4, -3, -2, -1,... | [
{
"docstring": null,
"function_declaration": "def counting_sort_for_radix(arr, exp):",
"function_name": "counting_sort_for_radix",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort_for_radix(arr: List[int], exp: int) -> None:\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n ... | trial_gpt4o_0 | {
"original_instruction": "## Question: Implement Enhanced Radix Sort\n\nRadix Sort can efficiently sort arrays of non-negative integers. However, the basic implementation doesn’t handle arrays containing negative numbers. \n\nYour task is to modify the existing Radix Sort algorithm to correctly sort arrays that can ... | 0.65532 | Data_Structure_39860 | C | [
"counting_sort_for_radix",
"radix_sort",
"enhanced_radix_sort"
] | 3 | [
[
"enhanced_radix_sort",
"radix_sort"
],
[
"radix_sort",
"counting_sort_for_radix"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 605de6c1ce129c1720fb4b9a4f770d41f6d7d509 | d90d3149583141898562d94312b8f9879f9fc9d2 | |||
v1.0 | complete | Data_Structure | Data_Structure_39592_C | from typing import List
def min_heap_sort(arr: List[int], simulation: bool=False) -> List[int]:
""" Sorts an array using the Min Heap Sort algorithm.
Args:
arr: A list of unsorted integers.
simulation: If set to True, prints iterative states of array sorting.
Returns:
... | from typing import List
def min_heapify(arr: List[int], n: int, i: int):
smallest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] < arr[smallest]:
smallest = left
if right < n and arr[right] < arr[smallest]:
smallest = right
if smallest != i:
arr[... | from solution import min_heap_sort
def test_empty_array():
assert min_heap_sort([]) == []
def test_single_element_array():
assert min_heap_sort([1]) == [1]
def test_sorted_array():
assert min_heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_unsorted_array():
assert min_heap_sort([3, 1, 5, 2, 4... | [
{
"docstring": null,
"function_declaration": "def min_heapify(arr, n, i):",
"function_name": "min_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": null,
"function_declaration": "def min_heap_sort(arr, simulation=False):",
"function_name": "min_heap_sort",
"parameter_li... | [
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 min_heapify(arr, n, i):\n \"\"\"\n Helper function to maintain the min-heap property.\n \"\"\"\n smallest = i\n left = 2 * i + 1\n right... | trial_gpt4o_1 | {
"original_instruction": "You are given two variants of Heap Sort algorithms, one using a Max Heap and the other using a Min Heap. A **Heap Sort algorithm** sorts an array by leveraging the properties of heap data structures.\n\nYour task is to implement the variant of the Heap Sort that uses a **Min Heap** data str... | 0.675938 | Data_Structure_39592 | C | [
"min_heapify",
"min_heap_sort"
] | 2 | [
[
"min_heap_sort",
"min_heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c4adb5f14be63148f13f542b37addf32b3857aef | 7c443b99fc64aa51b175b3a8923d30e08bfd1660 | |||
v1.0 | complete | Data_Structure | Data_Structure_39477_C | from typing import List
def bucket_sort(arr: List[int]) -> List[int]:
""" Implement an optimized version of Bucket Sort that accounts for non-uniformly distributed data using QuickSort for sorting the contents of each bucket.
>>> bucket_sort([4, 1, 2, 3, 5, 7, 6, 8])
[1, 2, 3, 4, 5, 6, 7, 8]
>>> bucket... | from typing import List
def quicksort(arr):
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(left) + middle + quicksor... | from solution import bucket_sort
def test_bucket_sort_empty():
assert bucket_sort([]) == []
def test_bucket_sort_single_element():
assert bucket_sort([1]) == [1]
def test_bucket_sort_small_array():
assert bucket_sort([4, 1, 2, 3, 5, 7, 6, 8]) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_bucket_sort_with_zero():... | [
{
"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,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def quicksort(arr):\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < pivot]\n middle = [x for ... | trial_gpt4o_1 | {
"original_instruction": "**Problem Statement**:\nImplement an optimized version of Bucket Sort that accounts for non-uniformly distributed data using a more efficient sorting algorithm for the buckets. Specifically, replace Insertion Sort with QuickSort for sorting the contents of each bucket to enhance performance... | 0.538365 | Data_Structure_39477 | C | [
"quicksort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a943863f4698ab6d229665b929f5c5d500a8ea81 | 4ac0ed1be0cf35f1075706f18709511833eb496f | |||
v1.0 | complete | Data_Structure | Data_Structure_39824_C | def bitonic_sort(arr: list, reverse: bool = False) -> list:
""" Implement Bitonic Sort without size limitation.
Sort an array of integers in the specified order using the Bitonic Sort
algorithm. The array can be of any size, and the algorithm leverages
parallel processing capabilities for performance ... | from concurrent.futures import ThreadPoolExecutor
def merge_bitonic(arr, low, cnt, direction):
if cnt > 1:
k = cnt // 2
for i in range(low, low + k):
if (direction == (arr[i] > arr[i + k])):
arr[i], arr[i + k] = arr[i + k], arr[i]
merge_bitonic(arr, low, k, direc... | from solution import bitonic_sort
def test_bitonic_sort_with_multiple_elements():
arr = [34, 7, 23, 32, 5, 62]
assert bitonic_sort(arr, reverse=False) == [5, 7, 23, 32, 34, 62]
assert bitonic_sort(arr, reverse=True) == [62, 34, 32, 23, 7, 5]
def test_bitonic_sort_with_power_of_two_length():
arr = [4, ... | [
{
"docstring": null,
"function_declaration": "def merge_bitonic(arr, low, cnt, direction):",
"function_name": "merge_bitonic",
"parameter_list": "(arr, low, cnt, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_sort_recursive(arr, low, cnt, direction):",
"func... | [
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 concurrent.futures import ThreadPoolExecutor\n\ndef merge_bitonic(arr, low, cnt, direction):\n if cnt > 1:\n k = cnt // 2\n for i in ran... | trial_gpt4o_0 | {
"original_instruction": "### Coding Task: Implement Bitonic Sort Without Size Limitation\n\n#### Scenario\nYou work for a software company that deals with large amounts of streaming data. You need an efficient sorting algorithm capable of leveraging parallel processing capabilities. As part of this requirement, you... | 0.583694 | Data_Structure_39824 | C | [
"merge_bitonic",
"bitonic_sort_recursive",
"bitonic_sort"
] | 3 | [
[
"bitonic_sort",
"bitonic_sort_recursive"
],
[
"bitonic_sort_recursive",
"merge_bitonic"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 63e5f933880e4e37b8bb67c6b8fff3ac35e6b29c | 369f64113c478b1dd89e401de42d52d03ab0fbc1 | |||
v1.0 | complete | Data_Structure | Data_Structure_39685_C | def maximum_flow_dinic(vertex_count, capacity_matrix, source, sink):
"""
Dinic's algorithm to find the maximum flow from source to sink in a flow network.
:param vertex_count: int - Number of vertices in the graph.
:param capacity_matrix: List[List[int]] - Matrix where capacity_matrix[i][j] represents c... | from collections import deque
def bfs(level_graph, source, sink, level):
"""
Perform BFS to construct level graph and update level of vertices.
"""
q = deque([source])
level[source] = 0
while q:
u = q.popleft()
for v in range(len(level_graph)):
if level[v] < 0 and l... | def test_basic_flow():
vertex_count = 4
capacity_matrix = [
[0, 10, 10, 0],
[0, 0, 5, 10],
[0, 0, 0, 10],
[0, 0, 0, 0]
]
source = 0
sink = 3
assert maximum_flow_dinic(vertex_count, capacity_matrix, source, sink) == 20
def test_no_path():
vertex_count = 4... | [
{
"docstring": "Perform BFS to construct level graph and update level of vertices.",
"function_declaration": "def bfs(level_graph, source, sink, level):",
"function_name": "bfs",
"parameter_list": "(level_graph, source, sink, level)"
},
{
"docstring": "Perform DFS to find the blocking flow i... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs_level_graph(vertex_count, capacity_graph, source, sink, level):\n for i in range(vertex_count):\n level[i] ... | trial_gpt4o_9 | {
"original_instruction": "### Maximum Flow Evaluation\n\n#### Context:\nYou are managing a water distribution network for a city, represented as a directed graph. Each vertex in the graph represents a junction point, and each directed edge represents a water pipeline with a specific capacity indicating the maximum v... | 0.486207 | Data_Structure_39685 | C | [
"bfs",
"dfs",
"maximum_flow_dinic"
] | 3 | [
[
"maximum_flow_dinic",
"bfs"
],
[
"maximum_flow_dinic",
"dfs"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | c206e83bff6bdee61cc6438b081ec7b8336b741b | ace051b1074dd87c1ca4b4f1d13b6d9744f939c3 | |||
v1.0 | complete | Data_Structure | Data_Structure_40014_C | def efficient_gcd(x: int, y: int) -> int:
"""
Returns the greatest common divisor (GCD) of x and y using the binary GCD algorithm.
>>> efficient_gcd(40, 100)
20
>>> efficient_gcd(18, 24)
6
>>> efficient_gcd(13, 29)
1
"""
pass
def smallest_lcm(x: int, y: int) -> int:
"""
... | def efficient_gcd(x, y):
"""
Returns the greatest common divisor (GCD) of x and y using the binary GCD algorithm.
"""
if x == 0:
return y
if y == 0:
return x
# From here on, x and y are guaranteed to be non-zero
shift = 0
while ((x | y) & 1) == 0:
x >>= 1
... | from solution import efficient_gcd, smallest_lcm
def test_efficient_gcd_both_non_zero():
assert efficient_gcd(40, 100) == 20
assert efficient_gcd(18, 24) == 6
assert efficient_gcd(13, 29) == 1
assert efficient_gcd(270, 192) == 6
def test_efficient_gcd_one_zero():
assert efficient_gcd(0, 5) == 5
... | [
{
"docstring": "Returns the greatest common divisor (GCD) of x and y using the binary GCD algorithm.",
"function_declaration": "def efficient_gcd(x, y):",
"function_name": "efficient_gcd",
"parameter_list": "(x, y)"
},
{
"docstring": "Returns the least common multiple (LCM) of x and y using ... | [
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 efficient_gcd(x, y):\n \"\"\"\n Compute the greatest common divisor (GCD) of two non-negative integers x and y using bitwise operations.\n \"\"\"... | trial_gpt4o_2 | {
"original_instruction": "### Question: Efficient GCD and LCM Computations\n\n#### Problem Statement\nYou are given two non-negative integers, `x` and `y`. Your task is to implement two functions:\n\n1. `efficient_gcd(x, y)` which computes the greatest common divisor (GCD) using:\n - Bitwise operations for perform... | 0.753094 | Data_Structure_40014 | C | [
"efficient_gcd",
"smallest_lcm"
] | 2 | [
[
"smallest_lcm",
"efficient_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 27cf1d4a2034d67c5d878cbbe16565c82ce58222 | 3a1a111ef033e390329efa50d5bd7e409269c11b | |||
v1.0 | complete | Data_Structure | Data_Structure_39645_C | import random
from typing import Tuple
def alice_private_key(p: int) -> int:
""" Returns Alice's private key as a random integer within the range [1, p-1].
>>> p = 23
>>> 1 <= alice_private_key(p) < p
True
"""
pass
def alice_public_key(a_pr_k: int, a: int, p: int) -> int:
""" Returns Alice... | import random
def alice_private_key(p):
"""
Returns Alice's private key as a random integer within the range [1, p-1].
"""
return random.randint(1, p-1)
def alice_public_key(a_pr_k, a, p):
"""
Returns Alice's public key.
"""
return pow(a, a_pr_k, p)
def bob_private_key(p):
"""
... | from solution import (
alice_private_key, alice_public_key, bob_private_key, bob_public_key,
alice_shared_key, bob_shared_key, diffie_hellman_key_exchange
)
import pytest
def test_alice_private_key():
p = 23
key = alice_private_key(p)
assert 1 <= key < p
def test_alice_public_key():
p = 23
... | [
{
"docstring": "Returns Alice's private key as a random integer within the range [1, p-1].",
"function_declaration": "def alice_private_key(p):",
"function_name": "alice_private_key",
"parameter_list": "(p)"
},
{
"docstring": "Returns Alice's public key.",
"function_declaration": "def al... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef alice_private_key(p):\n \"\"\"\n Returns Alice's private key as a random integer within the range [1, p-1].\n \"\"\"\n return... | trial_gpt4o_2 | {
"original_instruction": "### Assignment: Implement a Secure Diffie-Hellman Key Exchange\n\n**Problem Statement**: \n\nAlice and Bob want to securely share a secret key over an insecure network using the Diffie-Hellman Key Exchange method. You need to implement the key components of this protocol to ensure they exch... | 0.51619 | Data_Structure_39645 | C | [
"alice_private_key",
"alice_public_key",
"bob_private_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"diffie_hellman_key_exchange"
] | 7 | [
[
"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... | 6 | [] | false | [] | false | pytest | true | [] | true | 92b351700977e4a4507ac787545b4573244bc0d8 | 9cef9d08dd78d97d33b32dd74592273f18d6f0ff | |||
v1.0 | complete | Data_Structure | Data_Structure_39609_C | from typing import List
def pancake_sort(arr: List[int]) -> List[int]:
"""
Sorts the array using the Pancake Sort algorithm.
The function sorts the input list in-place and returns the sorted list.
The Pancake Sort algorithm uses a series of prefix reversals to sort the array.
>>> pancake_sort([3,... | from typing import List
def flip(arr: List[int], k: int) -> None:
"""
Reverses the order of the first k elements in the array.
"""
arr[:k] = arr[:k][::-1]
def find_max_index(arr: List[int], n: int) -> int:
"""
Finds the index of the maximum element in the first n elements of the array.
"""... | from solution import pancake_sort
def test_pancake_sort_normal_case():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
def test_pancake_sort_with_negative_and_zero():
assert pancake_sort([10, -1, 0, 5, 3]) == [-1, 0, 3, 5, 10]
def test_pancake_sort_single_element():
assert pancake_sort([1]) == [1]
def... | [
{
"docstring": "Reverses the order of the first k elements in the array.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Finds the index of the maximum element in the first n elements of the array.",
"function_declar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def pancake_sort(arr):\n def flip(arr, k):\n \"\"\"Helper function to flip the array up to index k.\"\"\"\n start = 0\n while start < ... | trial_gpt4o_2 | {
"original_instruction": "### Pancake Sort Implementation and Analysis\n\nYou are required to implement the Pancake Sort algorithm without referencing any code examples. Pancake Sort is inspired by the process of sorting a stack of pancakes using a spatula to flip the stack. The goal is to sort the given array by pe... | 0.767401 | Data_Structure_39609 | C | [
"flip",
"find_max_index",
"pancake_sort"
] | 3 | [
[
"pancake_sort",
"find_max_index"
],
[
"pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3db92ce834043bf3168d3c413b6a8cfe1c919c33 | 4fb9762405f69f0abb6dc223814d4d56b7d02851 | |||
v1.0 | complete | Data_Structure | Data_Structure_40093_C | def optimized_gcd(a: int, b: int) -> int:
"""
Compute the greatest common divisor (GCD) of two non-negative integers a and b
using a combination of the Euclidean algorithm and bitwise operations.
>>> optimized_gcd(48, 18) == 6
>>> optimized_gcd(0, 34) == 34
"""
pass
def optimized_lcm(a: in... | def optimized_gcd(a: int, b: int) -> int:
"""
Compute the greatest common divisor (GCD) of two non-negative integers a and b
using a combination of the Euclidean algorithm and bitwise operations.
"""
if a == 0:
return b
if b == 0:
return a
# Finding the largest power of ... | from solution import optimized_gcd, optimized_lcm
def test_optimized_gcd_basic():
assert optimized_gcd(48, 18) == 6
def test_optimized_gcd_zero():
assert optimized_gcd(0, 34) == 34
assert optimized_gcd(34, 0) == 34
assert optimized_gcd(0, 0) == 0
def test_optimized_gcd_prime():
assert optimized_g... | [
{
"docstring": "Compute the greatest common divisor (GCD) of two non-negative integers a and b\nusing a combination of the Euclidean algorithm and bitwise operations.",
"function_declaration": "def optimized_gcd(a, b):",
"function_name": "optimized_gcd",
"parameter_list": "(a, b)"
},
{
"docs... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_gcd(a: int, b: int) -> int:\n \"\"\"\n Optimized GCD function using bitwise operations and the Euclidean algorithm.\n \"\"\"\n if a ... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with implementing a function that computes the GCD of two non-negative integers a and b using an optimized algorithm that combines both the traditional Euclidean algorithm and bitwise operations. Your function should handle common edge cases and potential pitfalls.\n\nYou are... | 0.766438 | Data_Structure_40093 | C | [
"optimized_gcd",
"optimized_lcm"
] | 2 | [
[
"optimized_lcm",
"optimized_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e7d040ed776c6e585780b976b1d1f9fa450e0be3 | d5bfea9c5e836fbf8ffb547903cfbf9574be7844 | |||
v1.0 | complete | Data_Structure | Data_Structure_39687_C | def bucket_sort(arr: List[int]) -> List[int]:
""" Performs bucket sort on a given list of non-negative integers.
>>> bucket_sort([9, 4, 1, 7, 9, 1])
[1, 1, 4, 7, 9, 9]
>>> bucket_sort([])
[]
>>> bucket_sort([2])
[2]
"""
pass
# Sample Unit Tests
def test_bucket_sort_ra... | from typing import List
def insertion_sort(bucket: List[int]) -> List[int]:
"""
Performs insertion sort on a given list (bucket).
"""
for i in range(1, len(bucket)):
key = bucket[i]
j = i - 1
while j >= 0 and key < bucket[j]:
bucket[j + 1] = bucket[j]
j -... | from solution import bucket_sort
def test_bucket_sort_random():
assert bucket_sort([9, 4, 1, 7, 9, 1]) == [1, 1, 4, 7, 9, 9]
def test_bucket_sort_empty():
assert bucket_sort([]) == []
def test_bucket_sort_single_element():
assert bucket_sort([2]) == [2]
def test_bucket_sort_sorted():
assert bucket_s... | [
{
"docstring": "Performs insertion sort on a given list (bucket).",
"function_declaration": "def insertion_sort(bucket):",
"function_name": "insertion_sort",
"parameter_list": "(bucket)"
},
{
"docstring": "Performs bucket sort on a given list.",
"function_declaration": "def bucket_sort(a... | [
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 bucket_sort(arr: List[int]) -> List[int]:\n if len(arr) == 0:\n return []\n\n # Find maximum value to determine bu... | trial_gpt4o_2 | {
"original_instruction": "You are given an array of non-negative numbers. Your task is to implement a sorting function using the Bucket Sort algorithm. The inner sorting of each bucket will be handled using a specific function that you may choose to implement. \n\n### Function Signature\n```python\ndef bucket_sort(a... | 0.552577 | Data_Structure_39687 | C | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aae96ee68c490237aed60f798600b080a602c077 | 573ac0b7d6e361fda18867f1dbf73651c46d57f2 | |||
v1.0 | complete | Data_Structure | Data_Structure_40042_C | def combine_stutter_operations(stack: list) -> list:
"""
This function applies second_stutter first and then first_stutter on the stack.
Args:
stack (list): A list representing a stack (where the element at index 0 is the bottom and the element at the last index is the top).
Returns:
... | def first_stutter(stack):
"""
This function takes a stack and duplicates each element in the stack.
"""
aux = []
while stack:
value = stack.pop()
aux.append(value)
aux.append(value)
while aux:
stack.append(aux.pop())
def second_stutter(stack):
"""
... | from solution import combine_stutter_operations
def test_empty_stack():
assert combine_stutter_operations([]) == []
def test_single_element_stack():
assert combine_stutter_operations([10]) == [10, 10, 10, 10]
def test_multiple_elements_stack():
assert combine_stutter_operations([3, 7, 1, 14, 9]) == [3, 3... | [
{
"docstring": "This function takes a stack and duplicates each element in the stack.",
"function_declaration": "def first_stutter(stack):",
"function_name": "first_stutter",
"parameter_list": "(stack)"
},
{
"docstring": "This function takes a stack and duplicates each element in the stack."... | [
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 first_stutter(stack):\n \"\"\"\n Given a stack (represented as a list), replace each element with two copies of itself, maintaining the original ord... | trial_gpt4o_2 | {
"original_instruction": "#### Context:\nYou have been provided with functions to duplicate each element in a stack using auxiliary storage structures. Your task is to further manipulate a stack with combinations of these duplication operations and apply additional constraints.\n\n#### Problem Statement:\nYou need t... | 0.506087 | Data_Structure_40042 | C | [
"first_stutter",
"second_stutter",
"combine_stutter_operations"
] | 3 | [
[
"combine_stutter_operations",
"first_stutter"
],
[
"combine_stutter_operations",
"second_stutter"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7898254d78a252657478f54583e998d2c0259754 | 124221cd9046c92fd9d6af096096340ebbb56986 | |||
v1.0 | complete | Data_Structure | Data_Structure_39872_C | import time
from typing import List
def gnome_sort(arr: List[int]) -> List[int]:
"""
Gnome Sort Algorithm.
>>> gnome_sort([5, 3, 1, 6, 4, 2])
[1, 2, 3, 4, 5, 6]
>>> gnome_sort([])
[]
"""
index = 0
while index < len(arr):
if index == 0 or arr[index] >= arr[index - 1]:
... | import time
def gnome_sort(arr):
"""
Gnome Sort Algorithm.
"""
index = 0
while index < len(arr):
if index == 0 or arr[index] >= arr[index - 1]:
index += 1
else:
arr[index], arr[index - 1] = arr[index - 1], arr[index]
index -= 1
return arr
def... | from solution import gnome_sort, optimized_sort, compare_sorting_performance
def test_gnome_sort_empty():
assert gnome_sort([]) == []
def test_gnome_sort_single_element():
assert gnome_sort([1]) == [1]
def test_gnome_sort_sorted():
assert gnome_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_gnome_sor... | [
{
"docstring": "Gnome Sort Algorithm.",
"function_declaration": "def gnome_sort(arr):",
"function_name": "gnome_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merge Sort Algorithm.",
"function_declaration": "def optimized_sort(arr):",
"function_name": "optimized_sort",
"para... | [
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 time\n\ndef gnome_sort(arr):\n \"\"\"\n Gnome Sort Algorithm.\n \"\"\"\n index = 0\n while index < len(arr):\n if index == 0 or a... | trial_gpt4o_0 | {
"original_instruction": "### Question: Implement and Analyze an Optimized Sorting Algorithm\n\n#### Context:\nYou are given a list of integers that need to be sorted in ascending order. Gnome Sort is one approach to accomplish this, but its inefficiency on larger, unsorted datasets can be a hindrance. To remedy thi... | 0.551789 | Data_Structure_39872 | C | [
"gnome_sort",
"optimized_sort",
"merge",
"compare_sorting_performance"
] | 4 | [
[
"compare_sorting_performance",
"gnome_sort"
],
[
"compare_sorting_performance",
"optimized_sort"
],
[
"optimized_sort",
"merge"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 066ab2d79a551bfaae75cd89223fa6b23a1dca88 | 781dd8a1abae33c00f01eed5e8f854206fe70eb6 | |||
v1.0 | complete | Data_Structure | Data_Structure_39963_C | def nearest_neighbor_classifier(x: Tuple[float, ...], training_set: Dict[Tuple[float, ...], int]) -> int:
"""
Given an input vector `x`, and a training set represented as a dictionary with vectors as keys and their corresponding
classification labels as values, return the label of the nearest neighbor.
... | from typing import Tuple, Dict
import math
def euclidean_distance(v1: Tuple[float, ...], v2: Tuple[float, ...]) -> float:
"""
Calculate the Euclidean distance between two vectors.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def nearest_neighbor_classifier(x: Tuple[float, ...], trai... | from solution import nearest_neighbor_classifier
def test_nearest_neighbor_basic_functionality():
x = (1.0, 2.0)
training_set = {
(0.0, 0.0): 0,
(1.0, 2.5): 1,
(2.0, 2.0): 2
}
assert nearest_neighbor_classifier(x, training_set) == 1
def test_nearest_neighbor_single_element():
... | [
{
"docstring": "Calculate the Euclidean distance between two vectors.",
"function_declaration": "def euclidean_distance(v1, v2):",
"function_name": "euclidean_distance",
"parameter_list": "(v1, v2)"
},
{
"docstring": null,
"function_declaration": "def nearest_neighbor_classifier(x, train... | [
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 Tuple, Dict\nimport math\n\ndef euclidean_distance(a: Tuple[float, ...], b: Tuple[float, ...]) -> float:\n return math.sqrt(sum((x - y) ... | trial_gpt4o_2 | {
"original_instruction": "### Nearest Neighbor Classifier Implementation\n\nYou are tasked with implementing a nearest neighbor classifier. The classifier should be capable of determining the nearest neighbor from a training dataset based on the Euclidean distance metric and returning the label associated with the n... | 0.64691 | Data_Structure_39963 | C | [
"euclidean_distance",
"nearest_neighbor_classifier"
] | 2 | [
[
"nearest_neighbor_classifier",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 932a5f932735b7466173818a7437cc87cf662540 | e906a9b112171b4aaa057e4d8ae576ec62ed6dde | |||
v1.0 | complete | Data_Structure | Data_Structure_39373_C | def optimized_bucket_sort(scores: List[float]) -> List[float]:
"""Implement a function optimized_bucket_sort using bucket sort. The elements in each bucket
should be sorted using an algorithm of your choice, different from insertion sort. This function should handle scores
uniformly distributed between 0 an... | from typing import List
def quicksort(arr):
"""
Quicksort algorithm to sort elements within each bucket.
"""
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 ... | from solution import optimized_bucket_sort
def test_optimized_bucket_sort_sample_input():
scores = [52.5, 49.3, 66.8, 30.1, 90.4, 89.9, 45.3, 22.2]
expected = [22.2, 30.1, 45.3, 49.3, 52.5, 66.8, 89.9, 90.4]
assert optimized_bucket_sort(scores) == expected
def test_optimized_bucket_sort_empty_list():
... | [
{
"docstring": "Quicksort algorithm to sort elements within each bucket.",
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def optimized_bucket_sort(scores):",
"function_name": "op... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef optimized_bucket_sort(scores: List[float]) -> List[float]:\n \"\"\"\n Sorts a list of scores using bucket sort algorithm.... | trial_gpt4o_2 | {
"original_instruction": "### Problem Context:\nYou have been tasked to help optimize the score processing system for a sports competition platform. The system receives numerous athlete scores which need to be sorted efficiently to generate ranking and statistical analyses. The scores range uniformly between 0 and 1... | 0.589725 | Data_Structure_39373 | C | [
"quicksort",
"optimized_bucket_sort"
] | 2 | [
[
"optimized_bucket_sort",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 57ab5ec4a339b2b243799c66528b73a38f1ab8da | a9159a1295f82b9e1d18187b6d93a26e437c9ed6 | |||
v1.0 | complete | Data_Structure | Data_Structure_39970_C | def optimized_matrix_exponentiation(mat: list, n: int, memo: dict = None) -> list:
""" Raises the matrix 'mat' to the power 'n' using optimized repeated squaring.
Parameters:
mat (list): A 2D list representing the matrix.
n (int): The exponent to which the matrix is raised.
memo (dict): A dicti... | def multiply(mat1, mat2):
"""
Multiplies two matrices mat1 and mat2.
"""
size = len(mat1)
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] += mat1[i][k] * mat2[k][j]
return ... | from solution import optimized_matrix_exponentiation
def test_simple_case():
mat = [
[1, 2],
[3, 4]
]
n = 3
assert optimized_matrix_exponentiation(mat, n) == [
[37, 54],
[81, 118]
]
def test_identity_case():
mat = [
[2, 0],
[0, 2]
]
n = 0... | [
{
"docstring": "Multiplies two matrices mat1 and mat2.",
"function_declaration": "def multiply(mat1, mat2):",
"function_name": "multiply",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": "Returns an identity matrix of given size.",
"function_declaration": "def identity(size):",
"f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply(mat1, mat2):\n \"\"\"\n Multiplies two matrices mat1 and mat2.\n \"\"\"\n size = len(mat1)\n result = [[0] * size for _ in range(s... | trial_gpt4o_0 | {
"original_instruction": "### Question: Implement an Optimized Matrix Exponentiation Function\n\nYou are given a function `matrix_exponentiation` that raises a square matrix to an integer power using repeated squaring, but it suffers in performance for very high powers due to redundant multiplications. Your task is ... | 0.53385 | Data_Structure_39970 | C | [
"multiply",
"identity",
"optimized_matrix_exponentiation"
] | 3 | [
[
"optimized_matrix_exponentiation",
"identity"
],
[
"optimized_matrix_exponentiation",
"multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d96b99a49105d35d9e1d7cdf06d6537ecef71629 | 3a1218f7de2da14e4339f00a09660deb3370dba0 | |||
v1.0 | complete | Data_Structure | Data_Structure_39226_C | from typing import Tuple, Dict
import math
def euclidean_distance(point1: Tuple[float, ...], point2: Tuple[float, ...]) -> float:
"""
Computes the Euclidean distance between two points in k-dimensional space.
"""
pass
def nearest_neighbor(x: Tuple[float, ...], tSet: Dict[Tuple[float, ...], str]) -> st... | from typing import Tuple, Dict
import math
def euclidean_distance(point1: Tuple[float, ...], point2: Tuple[float, ...]) -> float:
"""
Computes the Euclidean distance between two points in k-dimensional space.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(point1, point2)))
def nearest_neighbor(... | from solution import nearest_neighbor, euclidean_distance
def test_nearest_neighbor_standard_case():
x = (1.0, 2.0, 3.0)
tSet = {
(2.0, 3.0, 4.0): 'A',
(1.0, 2.1, 2.9): 'B',
(0.0, 0.0, 0.0): 'C'
}
assert nearest_neighbor(x, tSet) == 'B'
def test_nearest_neighbor_multiple_neares... | [
{
"docstring": "Computes the Euclidean distance between two points in k-dimensional space.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Finds the nearest neighbor of the inp... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom scipy.spatial import cKDTree\nfrom typing import Tuple, Dict\n\ndef nearest_neighbor(x: Tuple[float], tSet: Dict[Tuple[float], str]) -> str:... | trial_gpt4o_2 | {
"original_instruction": "### Assessing Nearest Neighbor Classification in Higher-Dimensional Space\n\n#### Problem Description:\nYou are given an implementation of a nearest neighbor algorithm that classifies an input vector `x` based on the closest match from a training set `tSet`. Your task is to improve this imp... | 0.675001 | Data_Structure_39226 | C | [
"euclidean_distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e8fb700fa351ca84a6bc26d6892a1adc76f98147 | e1a17f60cae2e1a4c757264025b8555c4fce0d69 | |||
v1.0 | complete | Data_Structure | Data_Structure_39587_C | import math
from collections import Counter
from typing import Any, Dict, Tuple
def euclidean_distance(v1: Tuple[float], v2: Tuple[float]) -> float:
"""
Calculate the Euclidean distance between two vectors.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def k_nearest_neighbors(x: Tupl... | import math
from collections import Counter
from typing import Any, Dict, Tuple
def euclidean_distance(v1: Tuple[float], v2: Tuple[float]) -> float:
"""
Calculate the Euclidean distance between two vectors.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def k_nearest_neighbors(x: Tupl... | from solution import k_nearest_neighbors
def test_knn_basic():
training_set = {
(1, 2): 'ClassA',
(3, 4): 'ClassB',
(1, 1): 'ClassA',
(2, 2): 'ClassC',
(6, 6): 'ClassB'
}
assert k_nearest_neighbors((1, 3), training_set, 3) == 'ClassA'
def test_k_equals_1():
trai... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom collections import Counter\n\ndef euclidean_distance(v1, v2):\n return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))\n\ndef k_near... | trial_gpt4o_2 | {
"original_instruction": "You are provided with a simplified nearest neighbor algorithm that finds the vector in a training set closest to a given input vector. The specific task is to extend the functionality of this basic implementation to handle a k-nearest neighbors (k-NN) algorithm, taking the k nearest neighbo... | 0.631716 | Data_Structure_39587 | C | [
"euclidean_distance",
"k_nearest_neighbors"
] | 2 | [
[
"k_nearest_neighbors",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8942c6afdc344155e93c190b7fb472b9f2315f4f | c25d96aa4f0c955279697a78dd5d131e0102973a | |||
v1.0 | complete | Data_Structure | Data_Structure_40303_C | import random
def prime_check(num: int) -> bool:
"""
Returns True if `num` is a prime number.
Else returns False.
"""
pass
def find_primitive_root(n: int) -> list[int]:
"""
Returns all primitive roots of n.
"""
pass
def diffie_hellman_key_exchange(a: int, p: int) -> bool:
"""
... | import random
def prime_check(num: int) -> bool:
"""
Returns True if `num` is a prime number.
Else returns 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... | import pytest
from solution import prime_check, find_primitive_root, diffie_hellman_key_exchange
def test_prime_check():
assert prime_check(2) == True
assert prime_check(3) == True
assert prime_check(4) == False
assert prime_check(29) == True
def test_find_primitive_root():
assert 2 in find_primit... | [
{
"docstring": "Returns True if `num` is a prime number.\nElse returns False.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"pa... | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef prime_check(num):\n if num < 2:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n ... | trial_gpt4o_7 | {
"original_instruction": "### Diffie-Hellman Key Exchange Implementation Challenge\n\nYou are tasked with implementing a simplified version of the Diffie-Hellman key exchange algorithm. This exercise will help assess your understanding of modular arithmetic and cryptographic protocols.\n\n#### Problem Statement\n\nI... | 0.542448 | Data_Structure_40303 | C | [
"prime_check",
"gcd",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 4 | [
[
"diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"diffie_hellman_key_exchange",
"prime_check"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b5ee1aec0f458b778d084864211cf9a79276e324 | a9ad4c5df95657ab9c13db1c3e13f48f907e9a3a | |||
v1.0 | complete | Data_Structure | Data_Structure_40070_C | def merge_in_place(arr, start, mid, end):
"""
Merge two sorted subarrays in place.
:param arr: List of integers
:param start: Starting index of the first subarray
:param mid: Ending index of the first subarray
:param end: Ending index of the second subarray
"""
start2 = mid + 1
if a... | def merge_in_place(arr, start, mid, end):
start2 = mid + 1
if arr[mid] <= arr[start2]:
return
while start <= mid and start2 <= end:
if arr[start] <= arr[start2]:
start += 1
else:
value = arr[start2]
index = start2
while index != star... | def test_merge_sort_in_place_single_element():
arr = [1]
merge_sort_in_place(arr, 0, len(arr) - 1)
assert arr == [1]
def test_merge_sort_in_place_already_sorted():
arr = [1, 2, 3, 4, 5]
merge_sort_in_place(arr, 0, len(arr) - 1)
assert arr == [1, 2, 3, 4, 5]
def test_merge_sort_in_place_reverse... | [
{
"docstring": null,
"function_declaration": "def merge_in_place(arr, start, mid, end):",
"function_name": "merge_in_place",
"parameter_list": "(arr, start, mid, end)"
},
{
"docstring": null,
"function_declaration": "def merge_sort_in_place(arr, start, end):",
"function_name": "merge... | [
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 merge_in_place(arr, start, mid, end):\n start2 = mid + 1\n\n # If the direct merge is already sorted\n if arr[mid] <= arr[start2]:\n retur... | trial_gpt4o_2 | {
"original_instruction": "### Coding Challenge: Implementing Optimized Merge Sort \n\n#### Context:\nYou are tasked with implementing an optimized version of merge sort that reduces the memory overhead usually associated with this algorithm. Traditional merge sort implementations use additional arrays to manage sort... | 0.665567 | Data_Structure_40070 | C | [
"merge_in_place",
"merge_sort_in_place"
] | 2 | [
[
"merge_sort_in_place",
"merge_in_place"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | be7e7cac66cbbe9c5c771319cd1907963c79ae83 | ff5e658a4693c7642ea3069e3c6497e521ceb89e | |||
v1.0 | complete | Data_Structure | Data_Structure_40160_C | def radix_sort(arr):
""" Perform Radix Sort on a given list of non-negative integers.
Args:
arr (List[int]): A list of non-negative integers
Returns:
List[int]: Sorted list of integers
Example:
>>> radix_sort([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66, 75, 90, 170, 802]
... | 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[in... | from solution import radix_sort
def test_radix_sort_example1():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_example2():
assert radix_sort([3, 3, 3, 3]) == [3, 3, 3, 3]
def test_radix_sort_example3():
assert radix_sort([]) == []
def test_r... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def radix_sort(arr):\n \"\"\"\n Performs radix sort on a given list of non-negative integers.\n \"\"\"\n if not arr:\n return arr\n \n ... | trial_gpt4o_2 | {
"original_instruction": "### Radix Sort Implementation Challenge\n\nYou've just learned about a sorting algorithm called Radix Sort, which sorts a list of non-negative integers efficiently by processing individual digits from the least significant to the most significant. The algorithm uses buckets to collect numbe... | 0.712656 | Data_Structure_40160 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3a14da67bdaa2edefe16197ef48425c998f99e76 | eef6a70730325913d56c4983aa23db384c68f579 | |||
v1.0 | complete | Data_Structure | Data_Structure_39906_C | import random
def is_sorted(arr):
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def enhanced_bogo_sort(arr: list, max_attempts: int) -> tuple:
"""
Implement an enhanced version of Bogo Sort that:
1. Returns immediately with 0 iterations if the array is empty.
2. Checks if all elements... | import random
def is_sorted(arr):
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def enhanced_bogo_sort(arr: list, max_attempts: int) -> tuple:
if not arr:
return (arr, 0)
if all(x == arr[0] for x in arr):
return (arr, 0)
attempts = 0
while not is_sorted(a... | from solution import enhanced_bogo_sort
def test_empty_array():
assert enhanced_bogo_sort([], 10) == ([], 0)
def test_all_identical_elements():
assert enhanced_bogo_sort([1, 1, 1], 10) == ([1, 1, 1], 0)
def test_already_sorted_array():
result = enhanced_bogo_sort([1, 2, 3], 100)
assert result[0] == [... | [
{
"docstring": null,
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def enhanced_bogo_sort(arr, max_attempts):",
"function_name": "enhanced_bogo_sort",
"parameter_list": "(arr... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef enhanced_bogo_sort(arr, max_attempts):\n \"\"\"\n Enhanced Bogo Sort algorithm that sorts a list and returns the number of iteratio... | trial_gpt4o_2 | {
"original_instruction": "### Bogo Sort Variation Challenge\n\n**Background**: While Bogo Sort is a highly inefficient sorting algorithm, it serves as an interesting case study in understanding the limitations and behavior of brute-force algorithms. In this task, you will extend the Bogo Sort algorithm to handle add... | 0.609127 | Data_Structure_39906 | C | [
"is_sorted",
"enhanced_bogo_sort"
] | 2 | [
[
"enhanced_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ac2c6b5d86e86736f156f1305006966c9fbaccbd | 75711a33bf2f15b17bcd5d39a3c1dd763eefe33a | |||
v1.0 | complete | Data_Structure | Data_Structure_39890_C | from typing import List
def counting_sort(arr: List[int], exp: int) -> List[int]:
""" Helper function to perform counting sort based on exponent value.
"""
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for ... | from typing import List
def counting_sort(arr: List[int], exp: int) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i] += count[i - 1]
for i in range(n - 1, -1,... | from solution import efficient_radix_sort
def test_empty_list():
assert efficient_radix_sort([]) == []
def test_single_element_list():
assert efficient_radix_sort([1]) == [1]
def test_sorted_list():
assert efficient_radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list():
asser... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def efficient_radix_sort(arr):",
"function_name": "efficient_radix_sort",
"parameter_list... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n for ... | trial_gpt4o_2 | {
"original_instruction": "**Scenario:**\nYou are working on a data management system for a large e-commerce platform where product IDs need to be sorted efficiently. The IDs are large integers, and the sorting must be stable to maintain the initial order of products with identical IDs. Your task is to implement an e... | 0.573995 | Data_Structure_39890 | C | [
"counting_sort",
"efficient_radix_sort"
] | 2 | [
[
"efficient_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | db5c4109664f6e21b2d1d0732ac4cf41cd884cce | 38f70c1b60ed171aa4542f202fa4f44c237efcd3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.