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_40067_C | def merge_sort_optimized(book_ids):
"""
Sorts a given list of book IDs in ascending order using an optimized version of Merge Sort that minimizes additional space complexity.
Parameters:
book_ids (List[int]): The list of book IDs to be sorted.
Returns:
List[int]: The sorted list of boo... | def merge_sort_optimized(book_ids):
"""
Sorts a list of book IDs in ascending order using an optimized version of merge sort
that minimizes additional space complexity.
"""
if len(book_ids) <= 1:
return book_ids
temp_array = [0] * len(book_ids)
_merge_sort(book_ids, temp_array, ... | from solution import merge_sort_optimized
def test_merge_sort_optimized_basic():
assert merge_sort_optimized([101, 25, 82, 5, 210, 107]) == [5, 25, 82, 101, 107, 210]
def test_merge_sort_optimized_sorted():
assert merge_sort_optimized([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_optimized_reverse(... | [
{
"docstring": "Sorts a list of book IDs in ascending order using an optimized version of merge sort\nthat minimizes additional space complexity.",
"function_declaration": "def merge_sort_optimized(book_ids):",
"function_name": "merge_sort_optimized",
"parameter_list": "(book_ids)"
},
{
"doc... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort_optimized(book_ids):\n \"\"\"\n Sorts the provided list of book IDs in ascending order using an optimized version of Merge Sort.\n \"\... | trial_gpt4o_2 | {
"original_instruction": "#### Scenario\nA local bookstore needs to sort their inventory of books based on the ascending order of book IDs to streamline the search process. They have implemented a basic version of Merge Sort but realized their inventory size can be quite large, leading to high space usage. Your task... | 0.512365 | Data_Structure_40067 | C | [
"merge_sort_optimized",
"_merge_sort",
"_merge"
] | 3 | [
[
"_merge_sort",
"_merge"
],
[
"merge_sort_optimized",
"_merge_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 620a190c6374763f528c22080cf8408fe3b2cda0 | faa26f2e9ca7dbfa735e2fcf48e27b3290023082 | |||
v1.0 | complete | Data_Structure | Data_Structure_40385_C | from typing import List
def bitonic_sort_parallel(arr: List[int], reverse: bool = False) -> List[int]:
"""
Sorts an array of integers using the Bitonic Sort algorithm optimized for parallel processing.
Leverages Python's concurrent.futures module for parallel processing.
Args:
arr: A list of ... | from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List
def bitonic_merge(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]
... | from solution import bitonic_sort_parallel
def test_bitonic_sort_parallel_ascending():
assert bitonic_sort_parallel([3, 7, 2, 8, 1, 5, 6, 4], False) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_bitonic_sort_parallel_descending():
assert bitonic_sort_parallel([3, 7, 2, 8, 1, 5, 6, 4], True) == [8, 7, 6, 5, 4, 3, 2, 1]... | [
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, low, cnt, direction):",
"function_name": "bitonic_merge",
"parameter_list": "(arr, low, cnt, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_sort_recursive(arr, low, cnt, direction):",
"func... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom concurrent.futures import ThreadPoolExecutor\nimport math\n\ndef bitonic_merge(arr, low, cnt, direction):\n if cnt > 1:\n ... | trial_gpt4o_5 | {
"original_instruction": "### Scenario\nYou have been tasked by a software company to implement an efficient sorting algorithm suitable for parallel processing environments. The company frequently deals with large datasets that require fast and reliable sorting using their high-performance computing clusters.\n\n###... | 0.606368 | Data_Structure_40385 | C | [
"bitonic_merge",
"bitonic_sort_recursive",
"bitonic_sort_parallel"
] | 3 | [
[
"bitonic_sort_parallel",
"bitonic_sort_recursive"
],
[
"bitonic_sort_recursive",
"bitonic_merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 71c4df1531f92a3460f1caa6ccac828e4489b97f | 0dbfc20d6caeb187969e87eec6fa2e7a202dad27 | |||
v1.0 | complete | Data_Structure | Data_Structure_40099_C | def optimized_quick_sort(arr):
"""
Perform an optimized QuickSort on the array with median-of-three pivot selection.
Returns the sorted array.
>>> optimized_quick_sort([3, 6, 8, 10, 1, 2, 1])
[1, 1, 2, 3, 6, 8, 10]
>>> optimized_quick_sort([])
[]
>>> optimized_quick_sort([1])
[1... | def median_of_three(arr, low, high):
mid = (low + high) // 2
a, b, c = arr[low], arr[mid], arr[high]
if a > b:
if a < c:
median = low
elif b > c:
median = mid
else:
median = high
else:
if a > c:
median = low
elif b <... | import pytest
from solution import optimized_quick_sort
def test_empty_array():
assert 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():
... | [
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter... | [
1,
1,
1
] | 3 | easy | 1 | {
"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 This function takes an unsorted list of integers and returns the sorted list\n using an optimized Quick Sor... | trial_gpt4o_2 | {
"original_instruction": "### Quick Sort Implementation with Optimization\n\n#### Problem Statement\nYou are required to implement an optimized version of the Quick Sort algorithm. Your task is to handle large arrays efficiently, minimize the risk of the worst-case performance, and improve the average-case performan... | 0.604368 | Data_Structure_40099 | C | [
"median_of_three",
"partition",
"quick_sort_recursive",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"quick_sort_recursive"
],
[
"partition",
"median_of_three"
],
[
"quick_sort_recursive",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ea7a2f69201187b1b75b50df71ccb2e75fd330b6 | 0af6a843eff6ef06161461539aea316c8537e3bb | |||
v1.0 | complete | Data_Structure | Data_Structure_40179_C | def euler_totient(n: int) -> int:
""" Computes the totient of a given integer n.
>>> euler_totient(5)
4
>>> euler_totient(10)
4
>>> euler_totient(1)
1
>> euler_totient(1000000)
400000
"""
pass
def gcd(a: int, b: int) -> int:
while b:
a, b = b, a % b
retu... | # Optimized Euler's Totient function
def euler_totient(n: int) -> int:
result = n
p = 2
while p ** 2 <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1
if n > 1:
result -= result // n
return result
# Helper fun... | import pytest
from solution import euler_totient, gcd_totient
def test_euler_totient_prime():
assert euler_totient(5) == 4 # 5 is a prime number
def test_euler_totient_non_prime():
assert euler_totient(10) == 4 # totient of 10 is 4
def test_euler_totient_one():
assert euler_totient(1) == 1 # totie... | [
{
"docstring": null,
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def euler_totient(n: int) -> int:\n result = n\n p = 2\n while p * p <= n:\n if n % p == 0:\n while n % p == 0:\n n ... | trial_gpt4o_3 | {
"original_instruction": "### Euler's Totient Function: Optimized Implementation and Applications\n\n#### Context:\nEuler's Totient function, ϕ(n), or the phi function, is an important function in number theory that counts integers up to n that are coprime with n. This function is particularly prominent in fields su... | 0.606646 | Data_Structure_40179 | C | [
"euler_totient",
"gcd",
"gcd_totient"
] | 3 | [
[
"gcd_totient",
"euler_totient"
],
[
"gcd_totient",
"gcd"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fed632d4299d58947dcf51f7ff0e411c039dd2e0 | 6119870eeafb45b858b9d2d817bd92c7a4e7d2fb | |||
v1.0 | complete | Data_Structure | Data_Structure_40284_C | def max_heap_sort(arr, simulation=False):
""" Sort the array using a max-heap and return the sorted array in ascending order.
Args:
arr (List[int]): List of integers to sort.
simulation (bool): If True, print the array at each step of the heapify and sort process. Default is False.
... | def max_heapify(arr, n, i, simulation):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
... | from solution import max_heap_sort, min_heap_sort
def test_max_heap_sort_regular_case():
assert max_heap_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
def test_min_heap_sort_regular_case():
assert min_heap_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6,... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, simulation):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, simulation)"
},
{
"docstring": null,
"function_declaration": "def max_heap_sort(arr, simulation=False):",
"function_name": "max_heap_... | [
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 max_heapify(arr, n, i, simulation):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n and arr[left] > arr[largest]:\n ... | trial_gpt4o_0 | {
"original_instruction": "### Coding Challenge: Implement Max-Heap and Min-Heap Sorts\n\nYou are required to implement two sorting algorithms: one based on the max-heap and the other on the min-heap structure. Both algorithms should sort an array of integers in ascending order and include a simulation mode that prin... | 0.664195 | Data_Structure_40284 | C | [
"max_heapify",
"max_heap_sort",
"min_heapify",
"min_heap_sort"
] | 4 | [
[
"max_heap_sort",
"max_heapify"
],
[
"min_heap_sort",
"min_heapify"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 86a35a2b6983d8a9daa962fffe2b16510e3f90eb | 6fc04eabecd834a6218a51e31cf3d4832403a1f4 | |||
v1.0 | complete | Data_Structure | Data_Structure_40775_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array in non-decreasing order using the Merge Sort algorithm.
>>> merge_sort([38, 27, 43, 3, 9, 82, 10])
[3, 9, 10, 27, 38, 43, 82]
>>> merge_sort([5, 1, 1, 2, 0, 0])
[0, 0, 1, 1, 2, 5]
>>> mer... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array in non-decreasing order using the Merge Sort algorithm.
"""
if len(arr) <= 1:
return arr
# Divide the array into two halves
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_h... | from solution import merge_sort
def test_merge_sort():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
assert merge_sort([5, 1, 1, 2, 0, 0]) == [0, 0, 1, 1, 2, 5]
assert merge_sort([]) == []
assert merge_sort([1]) == [1]
assert merge_sort([2, 1]) == [1, 2]
assert mer... | [
{
"docstring": "Sorts an array in non-decreasing order using the Merge Sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted arrays into one sorted array.",
"function_declaration": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array of integers in non-decreasing order using the Merge So... | trial_gpt4o_2 | {
"original_instruction": "You are given an array of integers that you need to sort using an efficient sorting algorithm. Implement the `merge_sort` function that sorts an array in non-decreasing order using the Merge Sort algorithm. Follow the guidelines and constraints given below.\n\n### Function Signature\n```pyt... | 0.644697 | Data_Structure_40775 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5a8b21f109bc97a2ebd016a56cbfd912ce09da85 | e1a4c52e36f425ab670655ed3ad45950ba4a2dcb | |||
v1.0 | complete | Data_Structure | Data_Structure_40430_C | from typing import Optional
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def min_depth(root: Optional[TreeNode]) -> int:
""" Return the minimum depth (the number of nodes along the sho... | from typing import Optional
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def min_depth(root: Optional[TreeNode]) -> int:
if not root:
return 0
queue = deque([(root, 1)... | from solution import TreeNode, min_depth, min_height, print_tree
def test_min_depth():
tree = TreeNode(10)
tree.left = TreeNode(12)
tree.right = TreeNode(15)
tree.left.left = TreeNode(25)
tree.right.left = TreeNode(36)
assert min_depth(tree) == 3
def test_min_depth_empty():
tree = None
... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Optional\nfrom collections import deque\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n... | trial_gpt4o_1 | {
"original_instruction": "### Question:\nYou are given a binary tree and need to perform certain operations on it concerning the depth and height calculations. Implement the following functions:\n\n1. **min_depth**: This function should take a root node of a binary tree and return the minimum depth (the number of no... | 0.604752 | Data_Structure_40430 | C | [
"min_depth",
"min_height",
"print_tree"
] | 3 | [
[
"min_height",
"min_depth"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 392827752652a4960464d2c71d299d93e31e11de | 1a37f7c04443e06b6fb5fefe3dcdea2fa6a33879 | |||
v1.0 | complete | Data_Structure | Data_Structure_40742_C | def generate_key(k, seed=None):
"""Generate RSA public and private keys with k bits in the modulus n.
Parameters:
k (int): The number of bits in the modulus n.
seed (int, optional): Seed for random number generator.
Returns:
Tuple[int, int, int]: Tuple containing (n, e, d) where n is t... | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(length):
# Generate random bits and ensure the MSB and LSB are 1
p = random.getrandbits(length)
p |= (1 << length - 1) | 1
return p
def generate_prime_number(length):
p = 4
while not isprime(p):
p = gener... | from solution import generate_key, encrypt, decrypt
def test_key_generation():
n, e, d = generate_key(64, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert n.bit_length() == 64
def test_encryption_decryption():
n, e, d = generate_key(64, seed=42)
... | [
{
"docstring": null,
"function_declaration": "def generate_prime_candidate(length):",
"function_name": "generate_prime_candidate",
"parameter_list": "(length)"
},
{
"docstring": null,
"function_declaration": "def generate_prime_number(length):",
"function_name": "generate_prime_numbe... | [
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 mod_inverse, isprime\n\ndef generate_key(k, seed=None):\n if seed:\n random.seed(seed)\n \n while True:\n... | trial_gpt4o_2 | {
"original_instruction": "### RSA Encryption Algorithm Implementation and Enhancement\n\nIn this task, you will implement and enhance an RSA encryption system. \n\n### Context\nFor secure communication, you often need a secure way to encrypt messages so that only the intended recipient can decrypt them. RSA is a wid... | 0.766799 | Data_Structure_40742 | C | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 2bd018fb586cf5d801642848baaf69d782ac9675 | 41756e0782b4254d27713c39f93b2a2de3de16c6 | |||
v1.0 | complete | Data_Structure | Data_Structure_40265_C | def matrix_power(mat: list, k: int) -> list:
""" Implement an efficient solution for matrix exponentiation utilizing the principles of repeated squaring.
Args:
mat (list of list of int): A square matrix `n x n` where `1 <= n <= 100`.
k (int): An integer indicating the power to which the matrix is to be... | def matrix_multiply(mat1, mat2):
"""
Multiplies two matrices mat1 and mat2.
"""
n = len(mat1)
res = [[0]*n for _ in range(n)]
for i in range(n):
for j in range(n):
res[i][j] = sum(mat1[i][k] * mat2[k][j] for k in range(n))
return res
def identity_matrix(n):
"""
R... | from solution import matrix_power
def test_matrix_power_identity():
mat = [
[2, 0],
[0, 2]
]
k = 0
assert matrix_power(mat, k) == [[1, 0], [0, 1]]
def test_matrix_power_basic():
mat = [
[2, 0],
[0, 2]
]
k = 3
assert matrix_power(mat, k) == [[8, 0], [0, 8... | [
{
"docstring": "Multiplies two matrices mat1 and mat2.",
"function_declaration": "def matrix_multiply(mat1, mat2):",
"function_name": "matrix_multiply",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": "Returns the n x n identity matrix.",
"function_declaration": "def identity_matrix(n... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B.\n \"\"\"\n n = len(A)\n result = [[0] * n for _ in range(n)]\n\n for ... | trial_gpt4o_2 | {
"original_instruction": "Implement an efficient solution for matrix exponentiation utilizing the principles of repeated squaring. Given an integer `k` and an `n x n` matrix `mat`, return the matrix raised to the power `k`, i.e., `mat^k`.\n\n### Function Signature\n```python\ndef matrix_power(mat: list, k: int) -> l... | 0.517478 | Data_Structure_40265 | C | [
"matrix_multiply",
"identity_matrix",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity_matrix"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d88458689e60296ac2bfd9211ff0a968bd45d835 | 55e69876f3c156e638bb897dbdc813bdc4cb391e | |||
v1.0 | complete | Data_Structure | Data_Structure_40660_C | def sort_segments(arr, segments, sort_type):
"""
Sorts the segments within array 'arr',
where segments is a list of tuples defining the start and end indices of each segment.
sort_type defines the heap type ('max' or 'min').
Parameters:
arr (List[int]): The array to be sorted.
segments (Li... | def heapify(arr, n, i, sort_type):
"""
Maintain the heap property for a subtree rooted at index i
assuming the whole array 'arr' is a heap, except for possibly i itself.
"""
largest = smallest = i
left = 2 * i + 1
right = 2 * i + 2
if sort_type == "max":
if left < n and arr[i]... | from solution import sort_segments
def test_sort_segments_max_heap_small():
arr = [3, 5, 1, 2, 4, 6, 9, 8, 7]
segments = [(0, 3), (4, 6)]
sort_type = 'max'
result = sort_segments(arr, segments, sort_type)
assert result == [1, 2, 3, 5, 4, 6, 9, 8, 7]
def test_sort_segments_min_heap_small():
arr... | [
{
"docstring": "Maintain the heap property for a subtree rooted at index i \nassuming the whole array 'arr' is a heap, except for possibly i itself.",
"function_declaration": "def heapify(arr, n, i, sort_type):",
"function_name": "heapify",
"parameter_list": "(arr, n, i, sort_type)"
},
{
"do... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def heapify(arr, n, i, sort_type):\n \"\"\"Helper function to maintain the heap property.\"\"\"\n largest_or_smallest = i\n left = 2 * i + 1\n rig... | trial_gpt4o_2 | {
"original_instruction": "## Heap Sort Enhanced: Multiple Array Segments\n\n### Background\nHeap Sort is a powerful sorting algorithm leveraging heaps to order elements. Two forms exist: max-heap sorts in ascending order, and min-heap sorts in descending order. Your task extends upon this foundation, applying heap s... | 0.612199 | Data_Structure_40660 | C | [
"heapify",
"heap_sort_segment",
"sort_segments"
] | 3 | [
[
"heap_sort_segment",
"heapify"
],
[
"sort_segments",
"heap_sort_segment"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a627e52089ba56e8388b4be742b90ea17ce28dc7 | 5959ed575de40b18febbf24ed986fb8151d1354d | |||
v1.0 | complete | Data_Structure | Data_Structure_40978_C | import random
from typing import List, Union
def constrained_bogo_sort(arr: List[int], max_iterations: int) -> Union[List[int], str]:
"""
Attempts to sort the list arr using Constrained Bogo Sort within max_iterations.
If unsuccessful, return "Sort failed".
>>> constrained_bogo_sort([3, 2, 5, 1, 4... | import random
from typing import List, Union
def is_sorted(arr: List[int]) -> bool:
"""Helper function to check if the list is sorted."""
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def constrained_bogo_sort(arr: List[int], max_iterations: int) -> Union[List[int], str]:
"""
Attempts to s... | from solution import constrained_bogo_sort
def test_sorted_array():
assert constrained_bogo_sort([1, 2, 3, 4, 5], 1) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
result = constrained_bogo_sort([5, 4, 3, 2, 1], 1000)
assert result == [1, 2, 3, 4, 5] or result == "Sort failed"
def test_same_elements... | [
{
"docstring": "Helper function to check if the list is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Attempts to sort the list arr using Constrained Bogo Sort within max_iterations.\nIf unsuccessful, retur... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List, Union\n\ndef constrained_bogo_sort(arr: List[int], max_iterations: int) -> Union[List[int], str]:\n def is_sorted(a... | trial_gpt4o_2 | {
"original_instruction": "### Problem Description\n\nYou have been tasked to assess students' understanding of sorting algorithms by having them implement a variation of the Bogo Sort algorithm called **Constrained Bogo Sort**. \n\nThe Constrained Bogo Sort will try to sort the list in a given number of maximum iter... | 0.568816 | Data_Structure_40978 | C | [
"is_sorted",
"constrained_bogo_sort"
] | 2 | [
[
"constrained_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 08fc17573dc1b125d29b753a5649f39ad4b6b561 | 98951a4c5edb8c3a0becb225fbecfa20555ff70a | |||
v1.0 | complete | Data_Structure | Data_Structure_40157_C | class TreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
def insert(root: TreeNode, val: int) -> TreeNode:
"""
Insert a value into the binary search tree.
:param root: TreeNode representing the root of the BST
:param val: integer valu... | class TreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
def insert(root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = inser... | from solution import TreeNode, insert, delete, search
def test_insert_into_empty_tree():
root = None
root = insert(root, 10)
assert root.val == 10
assert root.left is None
assert root.right is None
def test_insert_multiple_values():
values = [20, 10, 30, 5, 15, 25, 35]
root = None
for ... | [] | [
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):\n self.val = val\n self.left = None\n self.right = None\n\ndef insert(root: TreeNode, val... | trial_gpt4o_2 | {
"original_instruction": "### Binary Search Tree Implementation\n\nSuppose you are a software developer tasked with creating a library for a binary search tree (BST). You need to implement the core functionalities: inserting a new value, deleting a value, and searching for a value in the tree.\n\n#### Function Signa... | 0.536413 | Data_Structure_40157 | C | [
"insert",
"delete",
"find_min",
"search"
] | 4 | [
[
"delete",
"find_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 161def7ea997175db0e87391223d336a456e1d96 | 14d5d7ada6f9e78fbaec9b1cda6431cd9b42aa89 | |||
v1.0 | complete | Data_Structure | Data_Structure_41085_C | def search_insert(array, val):
""" Perform binary search to find the insert position of val in array.
>>> search_insert([1, 3, 4, 10], 5) 3
>>> search_insert([1, 3, 4, 10], 1) 0
"""
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[... | def search_insert(array, val):
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def insertion_sort(array):
for i in range(1, len(array)):
key = ar... | def test_insertion_sort_empty():
assert insertion_sort([]) == []
def test_insertion_sort_single_element():
assert insertion_sort([5]) == [5]
def test_insertion_sort_sorted_order():
assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_insertion_sort_reverse_order():
assert insertion_sort... | [
{
"docstring": null,
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": null,
"function_declaration": "def insertion_sort(array):",
"function_name": "insertion_sort",
"parameter_list": "(a... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(array, val):\n low = 0\n high = len(array) - 1\n while low <= high:\n mid = low + (high - low) // 2\n if val > array[... | trial_gpt4o_2 | {
"original_instruction": "### Objective\nYou are required to implement the Insertion Sort algorithm using a helper function that efficiently finds the correct insertion position using binary search.\n\n### Task\nWrite a function `insertion_sort(array)` that sorts an array of integers in ascending order using the Ins... | 0.631298 | Data_Structure_41085 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 000caf21e8eeb3a54f35df7e2cd06b76fdbb640a | 9eb483565e14b366f44a4a76228e23fd566fd557 | |||
v1.0 | complete | Data_Structure | Data_Structure_40870_C | def multiply_bitwise(x: int, y: int) -> int:
"""
Multiplies two positive integers using only bitwise operations.
>>> multiply_bitwise(3, 4)
12
>>> multiply_bitwise(7, 5)
35
>>> multiply_bitwise(0, 9)
0
>>> multiply_bitwise(13, 13)
169
"""
def test_multiply_simple_c... | def multiply_bitwise(x, y):
"""
Multiplies two positive integers using only bitwise operations.
"""
result = 0
while y > 0:
# If the least significant bit of y is set, add x to the result
if y & 1:
result = add_bitwise(result, x)
# Double x and halve y
x <... | from solution import multiply_bitwise
def test_multiply_simple_cases():
assert multiply_bitwise(3, 4) == 12
assert multiply_bitwise(7, 5) == 35
def test_multiply_with_zero():
assert multiply_bitwise(0, 9) == 0
assert multiply_bitwise(9, 0) == 0
def test_multiply_with_one():
assert multiply_bitwis... | [
{
"docstring": "Multiplies two positive integers using only bitwise operations.",
"function_declaration": "def multiply_bitwise(x, y):",
"function_name": "multiply_bitwise",
"parameter_list": "(x, y)"
},
{
"docstring": "Adds two numbers using bitwise operations.",
"function_declaration":... | [
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 multiply_bitwise(x, y):\n \"\"\"\n Multiplies two positive integers using only bitwise operations.\n \"\"\"\n result = 0\n while y > 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "## Objective:\nImplement a function that multiplies two positive integers using only bitwise operations.\n\n## Scenario:\nYou are working on a low-level programming task where you need to perform multiplication of two positive integers without using any of the traditional arithmetic operato... | 0.617658 | Data_Structure_40870 | C | [
"multiply_bitwise",
"add_bitwise"
] | 2 | [
[
"multiply_bitwise",
"add_bitwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a4a6d6551ab9c31e289de395d84491e330c95520 | ff52598147b5996fe838f67e057d1d0c4ae7970f | |||
v1.0 | complete | Data_Structure | Data_Structure_40903_C | from typing import List, Tuple
def find_prime_pairs(n: int) -> List[Tuple[int, int]]:
"""
Given a number n, return all unique pairs of prime numbers (p1, p2) such that p1 + p2 = n.
Parameters:
* n (int): The target sum of the prime pairs.
Returns:
* List[Tuple[int, int]]: A list of unique pai... | from typing import List, Tuple
def is_prime(n: int) -> bool:
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
limit = int(n ** 0.5)
for i in range(3, limit + 1, 2):
if n % i == 0:
r... | from solution import find_prime_pairs
def test_find_prime_pairs_10():
assert find_prime_pairs(10) == [(3, 7), (5, 5)]
def test_find_prime_pairs_26():
assert find_prime_pairs(26) == [(3, 23), (7, 19), (13, 13)]
def test_find_prime_pairs_50():
assert find_prime_pairs(50) == [(3, 47), (7, 43), (13, 37), (19... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given a number n, return all unique pairs of prime numbers (p1, p2) such that p1 + p2 = n.",
"function_declaration": "def find... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False... | trial_gpt4o_0 | {
"original_instruction": "### Prime Pair Finder\n\nYou are working on a cryptography application and need to find pairs of prime numbers that sum up as required pairs.\n\n#### Problem Statement\n\nWrite a function:\n\n```python\ndef find_prime_pairs(n):\n \"\"\"\n Given a number n, return all unique pairs of p... | 0.685969 | Data_Structure_40903 | C | [
"is_prime",
"find_prime_pairs"
] | 2 | [
[
"find_prime_pairs",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3f96e529688797e7dab593d6a2c4fa4e62ce30b3 | dc07d9fdab8fc804e875ef08f8fc240f62056e44 | |||
v1.0 | complete | Data_Structure | Data_Structure_41601_C | def find_primitive_roots(n: int) -> list:
""" Find all primitive roots of a given integer n.
>>> find_primitive_roots(1) == [0]
>>> find_primitive_roots(7) == [3, 5]
>>> find_primitive_roots(9) == [2, 5]
""" | from math import gcd
def euler_totient(n):
"""Calculate Euler's Totient function φ(n)."""
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1
if n > 1:
result -= result // n
retu... | from solution import find_primitive_roots
def test_single_one():
assert find_primitive_roots(1) == [0]
def test_prime_number():
assert find_primitive_roots(7) == [3, 5]
def test_non_prime_coprime():
assert find_primitive_roots(9) == [2, 5]
def test_no_primitive_roots():
assert find_primitive_roots(8... | [
{
"docstring": "Calculate Euler's Totient function φ(n).",
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": "Check if g is a primitive root of n.",
"function_declaration": "def is_primitive_root(n, g):",
"fun... | [
0,
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef euler_totient(n):\n result = n\n p = 2\n while p * p <= n:\n if n %... | trial_gpt4o_7 | {
"original_instruction": "**Scenario**: You are developing a part of a cryptographic library that requires identifying primitive roots of a given number `n`. Understanding this requires knowledge of number theory, particularly Euler's Totient function and modular arithmetic.\n\n**Objective**: Implement a function th... | 0.519123 | Data_Structure_41601 | C | [
"euler_totient",
"is_primitive_root",
"find_primitive_roots"
] | 3 | [
[
"find_primitive_roots",
"is_primitive_root"
],
[
"is_primitive_root",
"euler_totient"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cb91ecf523bf2ecbe496779793d8de34d8337375 | 185f0aca66b330059f87f6bc2c8469d54d85b27c | |||
v1.0 | complete | Data_Structure | Data_Structure_41507_C | def diffie_hellman_key_exchange(a: int, p: int, option: bool = False) -> bool:
""" Perform the Diffie-Hellman Key Exchange algorithm.
Alice and Bob need to securely exchange keys over a network. You are to perform the Diffie-Hellman Key Exchange.
Args:
a: An integer which is a primitive root modul... | import random
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return... | from solution import diffie_hellman_key_exchange
def test_valid_case():
assert diffie_hellman_key_exchange(5, 23, False) == True
def test_invalid_a_not_primitive_root():
assert diffie_hellman_key_exchange(4, 23, False) == False
def test_invalid_p_not_prime():
assert diffie_hellman_key_exchange(5, 22, Fal... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Compute (base ^ exponent) % modulus efficiently.",
"function_declaration": "def power_mod(base, exponent, modulus):",
"fun... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\" Check if a number is prime. \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 ... | trial_gpt4o_1 | {
"original_instruction": "### Question: Implement Diffie-Hellman Key Exchange Algorithm\n\nAlice and Bob need to securely exchange keys over a network. You are to implement the Diffie-Hellman Key Exchange algorithm in Python.\n\n#### Task\nWrite a function `diffie_hellman_key_exchange` which takes the following inpu... | 0.47826 | Data_Structure_41507 | C | [
"is_prime",
"power_mod",
"is_primitive_root",
"diffie_hellman_key_exchange"
] | 4 | [
[
"diffie_hellman_key_exchange",
"is_prime"
],
[
"diffie_hellman_key_exchange",
"is_primitive_root"
],
[
"diffie_hellman_key_exchange",
"power_mod"
],
[
"is_primitive_root",
"is_prime"
],
[
"is_primitive_root",
"power_mod"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 1e3930fc1dcac35d46b5525dd47f0349f33c46e5 | 620e3b62003234509f69928e1f42c8bbbf9c55ac | |||
v1.0 | complete | Data_Structure | Data_Structure_40724_C | def is_prime(num: int) -> bool:
"""
Return True if num is a prime number, otherwise return False.
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(29)
True
>>> is_prime(30)
False
"""
def primitive_root(p: int) -> int:
"""
Return a ... | from math import gcd
def is_prime(num: int) -> bool:
"""
Return True if num is a prime number, otherwise return 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 % ... | from solution import is_prime, primitive_root, diffie_hellman_exchange
def test_is_prime():
assert is_prime(2) is True
assert is_prime(3) is True
assert is_prime(4) is False
assert is_prime(29) is True
assert is_prime(30) is False
def test_primitive_root():
assert primitive_root(11) == 2
a... | [
{
"docstring": "Return True if num is a prime number, otherwise return False.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Return a primitive root of the prime number p. If no \nprimitive root exists, return -1.",
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num: int) -> bool:\n \"\"\"\n Return True if num is a prime number, otherwise return False.\n \"\"\"\n if num <= 1:\n return F... | trial_gpt4o_1 | {
"original_instruction": "You are tasked with implementing parts of the Diffie-Hellman key exchange system. Specifically, you need to create functions that perform the following:\n\n1. Prime check for a given number.\n2. Finding a primitive root for a given prime number `p`.\n3. Completing the Diffie-Hellman key exc... | 0.581922 | Data_Structure_40724 | C | [
"is_prime",
"primitive_root",
"diffie_hellman_exchange"
] | 3 | [
[
"diffie_hellman_exchange",
"is_prime"
],
[
"diffie_hellman_exchange",
"primitive_root"
],
[
"primitive_root",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 7b0751cabde8cf27e0d62cfa5b3c103de2acfd87 | f3fd68f0cc943bc335b82d13f8ec4a6e1b2db01b | |||
v1.0 | complete | Data_Structure | Data_Structure_41237_C | def iterative(s: str) -> str:
"""
Reverses a string using an iterative approach.
"""
reversed_str = ''
for char in s:
reversed_str = char + reversed_str
return reversed_str
def ultra_pythonic(s: str) -> str:
"""
Reverses a string using Python slicing.
"""
return s[::-1]
... | def iterative(s: str) -> str:
"""
Reverses a string using an iterative approach.
"""
reversed_str = ''
for char in s:
reversed_str = char + reversed_str
return reversed_str
def ultra_pythonic(s: str) -> str:
"""
Reverses a string using Python slicing.
"""
return s[::-1]
... | import pytest
from solution import validated_reverse
def test_validated_reverse_empty():
assert validated_reverse("") == ""
def test_validated_reverse_single_char():
assert validated_reverse("a") == "a"
def test_validated_reverse_short_string():
assert validated_reverse("hello") == "hello"
def test_vali... | [
{
"docstring": "Reverses a string using an iterative approach.",
"function_declaration": "def iterative(s):",
"function_name": "iterative",
"parameter_list": "(s)"
},
{
"docstring": "Reverses a string using Python slicing.",
"function_declaration": "def ultra_pythonic(s):",
"function... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def validated_reverse(s: str) -> str:\n \"\"\"\n Validate and reverse a string using a combination of iterative and ultra_pythonic methods.\n \n :... | trial_gpt4o_2 | {
"original_instruction": "#### Reversal Algorithm Function Implementation\n\nYou are given four different implementations of a string reversal algorithm. Each implementation represents a unique approach to the problem. Your objective is to write a new function that combines these methods and performs additional spec... | 0.626814 | Data_Structure_41237 | C | [
"iterative",
"ultra_pythonic",
"validated_reverse"
] | 3 | [
[
"validated_reverse",
"iterative"
],
[
"validated_reverse",
"ultra_pythonic"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2bdfaea42a0a034bb6e4b8ca28108fe2a79d9925 | 9f2a239fb51179d176ba0f2b8b27d341d4619ed4 | |||
v1.0 | complete | Data_Structure | Data_Structure_40576_C | def merge_sort_inplace(arr, left, right):
"""
Sorts the portion of the array from index left to index right (inclusive) using in-place merge sort.
:param arr: List[int] - The list of integers to be sorted.
:param left: int - The starting index of the portion of the array to sort.
:param right: ... | def merge_sort_inplace(arr, left, right):
"""
Sorts the portion of the array from index left to index right (inclusive) using in-place merge sort.
:param arr: List[int] - The list of integers to be sorted.
:param left: int - The starting index of the portion of the array to sort.
:param right: ... | import pytest
from solution import merge_sort_inplace
def test_merge_sort_inplace_sorted_array():
arr = [1, 2, 3, 4, 5]
merge_sort_inplace(arr, 0, len(arr) - 1)
assert arr == [1, 2, 3, 4, 5]
def test_merge_sort_inplace_reverse_sorted_array():
arr = [5, 4, 3, 2, 1]
merge_sort_inplace(arr, 0, len(ar... | [
{
"docstring": "Sorts the portion of the array from index left to index right (inclusive) using in-place merge sort.\n\n:param arr: List[int] - The list of integers to be sorted.\n:param left: int - The starting index of the portion of the array to sort.\n:param right: int - The ending index of the portion of t... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge(arr, left, mid, right):\n start2 = mid + 1\n \n # If the direct merge is already sorted\n if arr[mid] <= arr[start2]:\n return\n \... | trial_gpt4o_1 | {
"original_instruction": "### Merge Sort with In-Place Merge\n\nYou are tasked with implementing an enhanced version of the Merge Sort algorithm. The improvement you need to implement is an in-place merge operation that reduces the auxiliary space usage from O(n) to O(log n), which aligns with the depth of the recur... | 0.637838 | Data_Structure_40576 | C | [
"merge_sort_inplace",
"merge"
] | 2 | [
[
"merge_sort_inplace",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d4d6f68202393e5952243664e66b7a85b0be780b | ed288ba8b5acf3ea942665269fb93cf8adaee7ca | |||
v1.0 | complete | Data_Structure | Data_Structure_40953_C | from typing import List, Tuple
def all_pairs_shortest_path(vertex_count: int, edges: List[Tuple[int, int, int]]) -> List[List[float]]:
"""Find the shortest paths between all pairs of vertices in a weighted, directed graph.
>>> all_pairs_shortest_path(4, [(0, 1, 3), (0, 3, 7), (1, 2, 1), (2, 3, 2), (3, 2, ... | from typing import List, Tuple
import heapq
def dijkstra(vertex_count: int, graph: List[List[Tuple[int, int]]], start: int) -> List[float]:
distances = [float('inf')] * vertex_count
distances[start] = 0
priority_queue = [(0, start)]
while priority_queue:
current_distance, current_vertex = ... | from solution import all_pairs_shortest_path
def test_all_pairs_shortest_path_example():
vertex_count = 4
edges = [
(0, 1, 3),
(0, 3, 7),
(1, 2, 1),
(2, 3, 2),
(3, 2, 3)
]
expected = [
[0, 3, 4, 6],
[float('inf'), 0, 1, 3],
[float('inf... | [
{
"docstring": null,
"function_declaration": "def dijkstra(vertex_count, graph, start):",
"function_name": "dijkstra",
"parameter_list": "(vertex_count, graph, start)"
},
{
"docstring": null,
"function_declaration": "def all_pairs_shortest_path(vertex_count, edges):",
"function_name"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nfrom typing import List, Tuple\n\ndef dijkstra(vertex_count: int, graph: List[List[Tuple[int, int]]], start: int) -> List[float]:\n distances... | trial_gpt4o_2 | {
"original_instruction": "### Problem: Modified Dijkstra's Algorithm for All-Pairs Shortest Path\n\nGiven the implementation of Dijkstra's Single-Source Shortest Path Algorithm, your task is to modify it to find the shortest paths between all pairs of vertices in a weighted, directed graph.\n\n### Input\n1. **vertex... | 0.672778 | Data_Structure_40953 | C | [
"dijkstra",
"all_pairs_shortest_path"
] | 2 | [
[
"all_pairs_shortest_path",
"dijkstra"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c4259e07acdacc8bd7593ff97a3a891b5150644f | 4b873dcee4e0540791a43b7c719b9d62c4466335 | |||
v1.0 | complete | Data_Structure | Data_Structure_41345_C | def secure_communication(sender_keys: tuple, receiver_keys: tuple, msg: str) -> str:
""" Secure communication using RSA encryption and decryption.
The message is encrypted with the receiver's public key and decrypted with the
receiver's private key.
>>> sender_keys = (3233, 17, 413)
>>> receiv... | def encrypt_message(n, e, msg):
"""
Encrypt the message using the receiver's public key (n, e).
"""
encrypted_message = [pow(ord(char), e, n) for char in msg]
return encrypted_message
def decrypt_message(n, d, encrypted_msg):
"""
Decrypt the message using the receiver's private key (n, d).
... | from solution import secure_communication
def test_secure_communication_basic():
sender_keys = (3233, 17, 413) # Example sender keys
receiver_keys = (3233, 17, 413) # Example receiver keys, same for simplicity
message = "HELLO123"
assert secure_communication(sender_keys, receiver_keys, message) ... | [
{
"docstring": "Encrypt the message using the receiver's public key (n, e).",
"function_declaration": "def encrypt_message(n, e, msg):",
"function_name": "encrypt_message",
"parameter_list": "(n, e, msg)"
},
{
"docstring": "Decrypt the message using the receiver's private key (n, d).",
"... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def string_to_int(message: str) -> int:\n \"\"\"Converts a string message to an integer representation.\"\"\"\n return int.from_bytes(message.encode(), ... | trial_gpt4o_2 | {
"original_instruction": "### Question Statement\n\nConsider the RSA algorithm implementation provided. Your task is to extend this system by implementing a secure communication protocol using RSA encryption. You will design a function that takes two sets of RSA keys as input (one for the sender and one for the rece... | 0.568681 | Data_Structure_41345 | C | [
"encrypt_message",
"decrypt_message",
"secure_communication"
] | 3 | [
[
"secure_communication",
"decrypt_message"
],
[
"secure_communication",
"encrypt_message"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2be937f480693f04dfe2f21b5dff1ed9e6ed4694 | 6a487946c22181920c8c7639c8c3ff0489543ea3 | |||
v1.0 | complete | Data_Structure | Data_Structure_41749_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
""" Sorts an array of integers using the merge sort algorithm.
>>> merge_sort([5, 2, 9, 1, 5, 6]) [1, 2, 5, 5, 6, 9]
>>> merge_sort([]) []
>>> merge_sort([1]) [1]
>>> merge_sort([2, 1]) [1, 2]
""" | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(le... | from solution import merge_sort
def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_two_elements():
assert merge_sort([2, 1]) == [1, 2]
def test_merge_sort_multiple_elements():
assert merge_sort([5, 2,... | [
{
"docstring": "Sorts an array of integers using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted arrays into one sorted array.",
"function_declaration": "def merge(le... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array of integers using the merge sort algorithm.\n \n ... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with sorting an array of integers using the merge sort algorithm. Your objective is to implement the `merge_sort` function and handle edge cases properly.\n\n### Function Signature\n```python\ndef merge_sort(arr: List[int]) -> List[int]:\n```\n\n### Input\n* `arr` (List[int])... | 0.661968 | Data_Structure_41749 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0276259f327c1be13d23c31c3eab9fe70c1a5ed5 | 2cb730c6cd3f2805765c309608a57119f9df94e7 | |||
v1.0 | complete | Data_Structure | Data_Structure_40825_C | import random
def choose_next_state(state_map):
"""
Given a dictionary state_map representing possible transitions from the current state with their associated probabilities,
this function returns the chosen next state based on the given probabilities.
"""
pass
def validate_transition_map(transiti... | import random
def choose_next_state(state_map):
"""
Given a dictionary state_map representing possible transitions from the current state with their associated probabilities,
this function returns the chosen next state based on the given probabilities.
"""
states = list(state_map.keys())
probab... | from solution import choose_next_state, validate_transition_map, markov_chain_generator
def test_choose_next_state():
state_map = {'A': 0.5, 'B': 0.5}
next_states = [choose_next_state(state_map) for _ in range(1000)]
assert 'A' in next_states
assert 'B' in next_states
def test_validate_transition_map(... | [
{
"docstring": "Given a dictionary state_map representing possible transitions from the current state with their associated probabilities,\nthis function returns the chosen next state based on the given probabilities.",
"function_declaration": "def choose_next_state(state_map):",
"function_name": "choos... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef choose_next_state(state_map):\n \"\"\"\n Chooses the next state based on the provided transition probabilities.\n \n Args:\n ... | trial_gpt4o_2 | {
"original_instruction": "#### Context\nYou are working on a predictive text model that uses a Markov Chain to suggest the next character in a sequence. The system models transitions between characters based on probabilities derived from historical text data.\n\nYour task is to implement functions to operate this Ma... | 0.500908 | Data_Structure_40825 | C | [
"choose_next_state",
"validate_transition_map",
"markov_chain_generator"
] | 3 | [
[
"markov_chain_generator",
"choose_next_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 442341f0c589ce270e8116c73c0d2d5754ded149 | e2832443e627d02419dda458e9b9e6a7cc39755b | |||
v1.0 | complete | Data_Structure | Data_Structure_40915_C | from typing import List
def pancake_sort(arr: List[int]) -> List[int]:
""" Sort an array of integers in ascending order using the Pancake Sort algorithm.
The function flips the order of elements in the array from position 0 to a given index.
Args:
arr (List[int]): An unsorted list of integers.
... | from typing import List
def flip(arr: List[int], k: int) -> None:
"""
Function to reverse the array from start to k index.
"""
arr[:k+1] = arr[:k+1][::-1]
def find_max_index(arr: List[int], n: int) -> int:
"""
Function to find the index of the maximum element in arr[:n+1]
"""
max_index... | from solution import pancake_sort
def test_pancake_sort_basic():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
def test_pancake_sort_with_duplicates():
assert pancake_sort([3, 1, 4, 2, 2, 4, 1, 1, 3]) == [1, 1, 1, 2, 2, 3, 3, 4, 4]
def test_pancake_sort_sorted():
assert pancake_sort([1, 2, 3]) ==... | [
{
"docstring": "Function to reverse the array from start to k index.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Function to find the index of the maximum element in arr[:n+1]",
"function_declaration": "def find_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def pancake_sort(arr):\n def flip(sub_arr, k):\n \"\"\"\n Flip the sublist from 0 to k.\n \"\"\"\n sub_arr[:k+1] = sub_arr[:k+1... | trial_gpt4o_2 | {
"original_instruction": "You are given an unsorted array consisting of integers. Your goal is to sort this array in ascending order using the **Pancake Sort** algorithm. This sorting algorithm sorts elements by repeatedly using a flip operation — flipping the order of elements in the array from position 0 to a give... | 0.770643 | Data_Structure_40915 | C | [
"flip",
"find_max_index",
"pancake_sort"
] | 3 | [
[
"pancake_sort",
"find_max_index"
],
[
"pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ad1c39af106b25073b995eecc20936ec526b1419 | 4fbf271d206c73b8f908857b9c77f8ad2371e6bf | |||
v1.0 | complete | Data_Structure | Data_Structure_40820_C | from typing import List, Dict, Union
def prime_check(n: int) -> bool:
"""
Check if the number is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i +... | from typing import List, Dict, Union
def prime_check(n: int) -> bool:
"""
Check if the number is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i +... | from solution import validate_prime_numbers
def test_validate_prime_numbers():
# Example test case from the prompt
assert validate_prime_numbers([2, 3, 4, 5, 16]) == {
"primes": [2, 3, 5],
"non_primes": [4, 16],
"prime_count": 3,
"non_prime_count": 2
}
def test_validate_pri... | [
{
"docstring": "Check if the number is a prime number.",
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def validate_prime_numbers(numbers):",
"function_name": "validate_prime_num... | [
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, Dict, Union\n\ndef is_prime(n: int) -> bool:\n \"\"\"Check if a number is a prime number.\"\"\"\n if n <= 1:\n return Fa... | trial_gpt4o_1 | {
"original_instruction": "### Scenario: Prime Validation Service\n\nYour task is to implement a function that leverages the prime-checking algorithm discussed above within a more extensive service that validates multiple numbers and returns a summary report.\n\n### Function Specification\n\nYou must implement `valid... | 0.760221 | Data_Structure_40820 | C | [
"prime_check",
"validate_prime_numbers"
] | 2 | [
[
"validate_prime_numbers",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 883660417ea6419111cf496911a10eb2b959b527 | 8f087da32c596c24d2c6b1d966d0e6e66e3697a5 | |||
v1.0 | complete | Data_Structure | Data_Structure_41181_C | def radix_sort(arr, simulation=False):
"""
Sort a list of non-negative integers using the radix sort technique.
Params:
arr (List[int]): A list of non-negative integers to be sorted.
simulation (bool): A flag to enable or disable printing intermediate steps (default: False).
Returns:
... | def counting_sort(arr, exp, simulation):
n = len(arr)
output = [0] * n
count = [0] * 10
# Store count of occurrences in count[]
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
# Change count[i] so that count[i] contains actual position of this digi... | from solution import radix_sort
def test_radix_sort_example_1():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_example_2():
assert radix_sort([78, 56, 89, 234, 12, 789]) == [12, 56, 78, 89, 234, 789]
def test_radix_sort_empty_list():
assert ... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp, simulation):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n for i in range(n):\n index = (arr[i] // e... | trial_gpt4o_1 | {
"original_instruction": "### Radix Sort Implementation and Analysis\n\n#### Scenario\nYou are tasked with sorting a list of non-negative integers efficiently for a large-scale data processing system. Given the constraints on execution time, you decide to implement the Radix Sort algorithm, which can offer better pe... | 0.696636 | Data_Structure_41181 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 05fb5909b34f9efa35cb24c113597a3afc6b5b8f | 0eb744d9f30f839cf3e5c8d23d52de04db26ec1e | |||
v1.0 | complete | Data_Structure | Data_Structure_41589_C | def lcm(a: int, b: int) -> int:
""" Calculate the least common multiple (LCM) of two non-negative integers.
>>> lcm(15, 20)
60
>>> lcm(0, 5)
0
>>> lcm(7, 0)
0
""" | def gcd(a, b):
"""
Calculate the Greatest Common Divisor of a and b.
"""
while b:
a, b = b, a % b
return a
def lcm(a: int, b: int) -> int:
"""
Calculate the Least Common Multiple of two non-negative integers a and b.
"""
if a == 0 or b == 0:
return 0
return abs(a... | from solution import lcm
def test_lcm_with_zeros():
assert lcm(0, 5) == 0
assert lcm(7, 0) == 0
assert lcm(0, 0) == 0
def test_lcm_positive_numbers():
assert lcm(15, 20) == 60
assert lcm(3, 7) == 21
assert lcm(8, 12) == 24
def test_lcm_with_one():
assert lcm(1, 5) == 5
assert lcm(1, 1... | [
{
"docstring": "Calculate the Greatest Common Divisor of a and b.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate the Least Common Multiple of two non-negative integers a and b.",
"function_declaration": "def lcm... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def lcm(a: int, b: int) -> int:\n \"\"\"\n Calculate the Least Common Multiple of two non-negative integers.\n \"\"\"\n if a < 0 or b < 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question\nYou are required to implement a function for calculating the least common multiple (LCM) of two non-negative integers, taking into consideration proper error handling and integer output.\n\n#### Function Signature\n```python\ndef lcm(a: int, b: int) -> int:\n pass\n```\n\n#... | 0.761781 | Data_Structure_41589 | C | [
"gcd",
"lcm"
] | 2 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a0569d954cbbc341dedc541c7b88a913e7b3b6c4 | 2614b7a309b222a963d27dd4cf63344d5247d53a | |||
v1.0 | complete | Data_Structure | Data_Structure_41422_C | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if the list is sorted in ascending order.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def bogo_sort(arr: List[int]) -> List[int]:
"""
Sorts an array using the highly ... | import random
def is_sorted(arr):
"""
Helper function to check if the list is sorted in ascending order.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def bogo_sort(arr):
"""
Sorts an array using the highly inefficient BogoSort method.
"""
attempts = 0
max_attem... | from solution import bogo_sort
def test_bogo_sort_simple_array():
assert bogo_sort([3, 1, 2]) == [1, 2, 3]
def test_bogo_sort_with_duplicates():
assert bogo_sort([1, 2, 2, 3]) == [1, 2, 2, 3]
def test_bogo_sort_already_sorted():
assert bogo_sort([1, 2, 3]) == [1, 2, 3]
def test_bogo_sort_reverse_order()... | [
{
"docstring": "Helper function to check if the list is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts an array using the highly inefficient BogoSort method.",
"function_declarat... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if the list is sorted in ascending order.\n \"\"\"\n return all(arr[i] <=... | trial_gpt4o_2 | {
"original_instruction": "#### Bogo Sort Analysis and Implementation\n\nBogo Sort is a highly inefficient sorting algorithm based on generating permutations of the input list until the list is sorted. Your task is to write a Bogo Sort function and deeply comprehend its inefficiencies and limitations.\n\n#### Task:\n... | 0.585965 | Data_Structure_41422 | C | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 607ad6ec79af105f5f3d8faa1878a19af0cb7371 | 299f5f2a696a913b6aeda0c334b399d0e3e9a781 | |||
v1.0 | complete | Data_Structure | Data_Structure_40989_C | def median_of_three(arr, first, last):
"""
Reorders the first, middle, and last elements to choose the median as the pivot.
"""
# Your code here
def partition(arr, low, high):
"""
Partitions the array around the pivot selected by the median of three method.
"""
# Your code here
def qui... | def median_of_three(arr, first, last):
"""
Reorders the first, middle, and last elements of the array to choose the median as the pivot.
"""
mid = (first + last) // 2
if arr[first] > arr[mid]:
arr[first], arr[mid] = arr[mid], arr[first]
if arr[first] > arr[last]:
arr[first], arr[... | from solution import quick_sort
def test_quick_sort_with_duplicates():
assert quick_sort([3,1,2,1,4]) == [1,1,2,3,4]
def test_quick_sort_already_sorted():
assert quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_quick_sort_reversed():
assert quick_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_... | [
{
"docstring": "Reorders the first, middle, and last elements of the array to choose the median as the pivot.",
"function_declaration": "def median_of_three(arr, first, last):",
"function_name": "median_of_three",
"parameter_list": "(arr, first, last)"
},
{
"docstring": null,
"function_d... | [
0,
0,
0,
0,
1,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def median_of_three(arr, first, last):\n \"\"\"\n Selects the median of the first, middle, and last elements of the list.\n Reorders so the pivot end... | trial_gpt4o_8 | {
"original_instruction": "### Quick Sort with Pivot Optimization\n\nYou have been provided a quick sort algorithm. The task is to improve this algorithm by implementing a median-of-three pivot selection strategy to enhance the average performance further.\n\n#### Requirements:\n1. Implement the function `median_of_t... | 0.649025 | Data_Structure_40989 | C | [
"median_of_three",
"partition",
"quick_sort_recursive",
"quick_sort"
] | 4 | [
[
"partition",
"median_of_three"
],
[
"quick_sort",
"quick_sort_recursive"
],
[
"quick_sort_recursive",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | c14d688eb664970faa8b268b33a4db87c72e360d | a05acf7a838421b738a3db98925d6e709041ebb6 | |||
v1.0 | complete | Data_Structure | Data_Structure_41228_C | def hailstone(n, memo={}):
"""
Return the 'hailstone sequence' from n to 1 with memoization to improve performance.
n: The starting point of the hailstone sequence
>>> hailstone(10) [10, 5, 16, 8, 4, 2, 1]
>>> hailstone(1) [1]
>>> hailstone(7) [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, ... | def hailstone(n, memo={}):
"""
Return the 'hailstone sequence' from n to 1 with memoization to improve performance.
n: The starting point of the hailstone sequence
memo: A dictionary to store previously computed sequences
"""
if n in memo:
return memo[n]
original_n = n
sequence... | def test_hailstone_sequence():
assert hailstone(10) == [10, 5, 16, 8, 4, 2, 1]
assert hailstone(1) == [1]
assert hailstone(7) == [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
def test_longest_hailstone_sequence():
assert longest_hailstone_sequence(10) == (9, 20)
assert longest_hail... | [
{
"docstring": "Return the 'hailstone sequence' from n to 1 with memoization to improve performance.\nn: The starting point of the hailstone sequence\nmemo: A dictionary to store previously computed sequences",
"function_declaration": "def hailstone(n, memo={}):",
"function_name": "hailstone",
"para... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def hailstone(n, memo={}):\n \"\"\"\n Return the 'hailstone sequence' from n to 1 with memoization to improve performance.\n n: The starting point of... | trial_gpt4o_1 | {
"original_instruction": "You are given a function that generates a hailstone sequence starting from a given number `n`. Your task is to modify the function to handle large inputs more efficiently by leveraging memoization. You also need to implement a secondary function that, given an integer `m`, finds the startin... | 0.568618 | Data_Structure_41228 | C | [
"hailstone",
"longest_hailstone_sequence"
] | 2 | [
[
"longest_hailstone_sequence",
"hailstone"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 1a0ce6d2d1410f607bec4d42fd41ab03c2eaaaa1 | 29d688dba40b4c5bc15a866c850fb5d95f06d1d7 | |||
v1.0 | complete | Data_Structure | Data_Structure_41722_C | def generate_strobogrammatic(n: int) -> List[str]:
""" Generate all strobogrammatic numbers of a given length.
>>> generate_strobogrammatic(1)
["0", "1", "8"]
>>> generate_strobogrammatic(2)
["11", "69", "88", "96"]
"""
def count_strobogrammatic_in_range(low: str, high: str) -> int:
""" Cou... | from typing import List
def generate_strobogrammatic(n: int) -> List[str]:
# pairs of strobogrammatic numbers
pairs = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
def helper(n, length):
if n == 0: return [""]
if n == 1: return ["0", "1", "8"]
middles = helper(n-2, le... | from solution import generate_strobogrammatic, count_strobogrammatic_in_range
def test_generate_strobogrammatic_length_2():
result = generate_strobogrammatic(2)
expected = sorted(["11", "69", "88", "96"])
assert sorted(result) == expected
def test_generate_strobogrammatic_length_3():
result = generate... | [
{
"docstring": null,
"function_declaration": "def generate_strobogrammatic(n):",
"function_name": "generate_strobogrammatic",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def count_strobogrammatic_in_range(low, high):",
"function_name": "count_strobogramma... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_strobogrammatic(n):\n \"\"\"\n Generates all strobogrammatic numbers of length n.\n \"\"\"\n if n == 0:\n return [\"\"]\n e... | trial_gpt4o_4 | {
"original_instruction": "### Question: Optimal Strobogrammatic Number Generation and Counting\n\n#### Context\nA strobogrammatic number is one that looks the same when rotated 180 degrees. Your task is to implement two functions: one that generates all strobogrammatic numbers of a given length and another that coun... | 0.509036 | Data_Structure_41722 | C | [
"generate_strobogrammatic",
"count_strobogrammatic_in_range"
] | 2 | [
[
"count_strobogrammatic_in_range",
"generate_strobogrammatic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 54beda61fbec778c8a47edad32c9ff7b7e05beb4 | f26cdff53261a08b5e2c8fc0f47213fa5ab3da1e | |||
v1.0 | complete | Data_Structure | Data_Structure_41912_C | from typing import List
def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
""" Sort an array of non-negative integers using the Radix Sort algorithm.
Optionally print out the array at each iteration of sorting at each significant digit if simulation is True.
>>> radix_sort([170, 4... | from typing import List
def counting_sort_for_radix(arr: List[int], exp: int) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
w... | from solution import radix_sort
def test_radix_sort_basic():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_single_element():
assert radix_sort([5]) == [5]
def test_radix_sort_empty_list():
assert radix_sort([]) == []
def test_radix_sort_wit... | [
{
"docstring": null,
"function_declaration": "def counting_sort_for_radix(arr, exp):",
"function_name": "counting_sort_for_radix",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort",
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n ... | trial_gpt4o_2 | {
"original_instruction": "### Radix Sort Implementation and Analysis\n\nYou are tasked with implementing an advanced sorting algorithm, Radix Sort. This algorithm is particularly efficient for sorting lists of integers where the number of digits in the largest number is significantly smaller than the size of the lis... | 0.708744 | Data_Structure_41912 | C | [
"counting_sort_for_radix",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort_for_radix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e0e6c63ed9183713661e4087f288411e0fb3e845 | 778f02b094d60d9160b9dd7370c73c1447a9cabf | |||
v1.0 | complete | Data_Structure | Data_Structure_41792_C | import random
def prime_check(num: int) -> bool:
"""
Validate that the given number is a prime number.
>>> prime_check(23)
True
>>> prime_check(29)
True
>>> prime_check(4)
False
>>> prime_check(1)
False
"""
def find_primitive_root(n: int) -> list:
"""
Find the p... | import random
def prime_check(num: int) -> bool:
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
... | def test_prime_check():
assert prime_check(23) == True
assert prime_check(29) == True
assert prime_check(4) == False
assert prime_check(1) == False
def test_find_primitive_root():
assert 5 in find_primitive_root(23)
assert 3 in find_primitive_root(7)
assert find_primitive_root(4) == []
... | [
{
"docstring": null,
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def find_primitive_root(n):",
"function_name": "find_primitive_root",
"parameter_list": "(n)"
},
{
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef prime_check(num: int) -> bool:\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Secure Messaging Using Diffie-Hellman Key Exchange\n\nAlice and Bob want to securely share a secret key over an insecure communication channel, using the Diffie-Hellman Key Exchange algorithm. Given a large prime number \\(p\\) and its primitive root \\(a\\), write Python functions to s... | 0.584825 | Data_Structure_41792 | C | [
"prime_check",
"find_primitive_root",
"alice_private_key",
"alice_public_key",
"bob_private_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"diffie_hellman_key_exchange"
] | 9 | [
[
"diffie_hellman_key_exchange",
"alice_private_key"
],
[
"diffie_hellman_key_exchange",
"alice_public_key"
],
[
"diffie_hellman_key_exchange",
"alice_shared_key"
],
[
"diffie_hellman_key_exchange",
"bob_private_key"
],
[
"diffie_hellman_key_exchange",
"bob_pu... | 7 | [] | false | [] | false | pytest | false | [] | true | 5ed0a97af0695491808158fe5a3d31c17e003b5f | 167105ef0cd7d026fe87e831eb12db599ea45387 | |||
v1.0 | complete | Data_Structure | Data_Structure_41101_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(preorder, postorder):
"""
Constructs a full binary tree given its preorder and postorder traversals.
:param preorder: List[int]
:param postorder... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(preorder, postorder):
"""
Constructs a full binary tree given its preorder and postorder traversals.
:param preorder: List[int]
:param postorder... | import pytest
from solution import getInorderFromPrePost
def test_example_case():
pre = [1, 2, 4, 8, 9, 5, 3, 6, 7]
post = [8, 9, 4, 5, 2, 6, 7, 3, 1]
expected = [8, 4, 9, 2, 5, 1, 6, 3, 7]
assert getInorderFromPrePost(pre, post) == expected
def test_single_node_tree():
pre = [1]
post = [1]
... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left... | trial_gpt4o_2 | {
"original_instruction": "Given two arrays representing the preorder and postorder traversal of a full binary tree, your task is to construct the binary tree and return its inorder traversal.\n\n**Input:**\n- `pre` (list): A list of integers representing the preorder traversal of the full binary tree.\n- `post` (lis... | 0.527744 | Data_Structure_41101 | C | [
"buildTree",
"inorderTraversal",
"getInorderFromPrePost"
] | 3 | [
[
"getInorderFromPrePost",
"buildTree"
],
[
"getInorderFromPrePost",
"inorderTraversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 76e307d47ee363d761760822e7f21be3bfe5cc98 | 5d2507276128088ed1070241d54d53159f68d1ca | |||
v1.0 | complete | Data_Structure | Data_Structure_41251_C | def maximum_flow_bfs(graph: List[List[int]]) -> int:
""" Compute the maximum flow from the source node (node 0) to the sink node (the last node)
using the Edmonds-Karp algorithm (an implementation of the Ford-Fulkerson method using BFS).
Args:
graph (List[List[int]]): The adjacency matrix where eac... | from collections import deque
def bfs(capacity, source, sink, parent):
visited = [False] * len(capacity)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for ind, val in enumerate(capacity[u]):
if visited[ind] == False and val > 0:
... | from solution import maximum_flow_bfs
def test_maximum_flow_example():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow_bfs(graph) == 23
def test_maxi... | [
{
"docstring": null,
"function_declaration": "def bfs(capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(graph):",
"function_name": "maximum_flow_bfs",
... | [
0,
0,
0,
1,
0,
1,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(capacity, residual, source, sink, parent):\n \"\"\"\n Perform BFS to find an augmenting path.\n \"\"\"\n ... | trial_gpt4o_8 | {
"original_instruction": "You are given a directed graph represented by an adjacency matrix where each entry `[i][j]` indicates the capacity of the edge from node `i` to node `j`. Your task is to compute the maximum flow from the source node (node 0) to the sink node (the last node) using the Edmonds-Karp algorithm,... | 0.575364 | Data_Structure_41251 | C | [
"bfs",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a11f26da7f8bfeed4d100f303afad07b0c36e953 | 60203454646e8c0c33d42e8db92031bafb7c649d | |||
v1.0 | complete | Data_Structure | Data_Structure_41789_C | from typing import List
def dual_heap_sort(arr: List[int]) -> List[int]:
"""
Implement a function dual_heap_sort which sorts an array using both max-heap
and min-heap approaches sequentially and returns the final sorted array.
This function should execute max_heap_sort followed by min_heap_sort on t... | import heapq
from typing import List
def max_heap_sort(arr: List[int]) -> List[int]:
"""
Perform a heap sort using a max heap.
"""
# heapify transforms list into a heap, in-place, in linear time.
heap = [-x for x in arr]
heapq.heapify(heap)
sorted_list = []
while heap:
max_... | from solution import dual_heap_sort
def test_dual_heap_sort_with_mixed_numbers():
assert dual_heap_sort([3, 6, 1, 5, 2, 4]) == [1, 2, 3, 4, 5, 6]
def test_dual_heap_sort_with_negative_numbers():
assert dual_heap_sort([-3, -6, -1, -5, -2, -4]) == [-6, -5, -4, -3, -2, -1]
def test_dual_heap_sort_with_zeros_and... | [
{
"docstring": "Perform a heap sort using a max heap.",
"function_declaration": "def max_heap_sort(arr):",
"function_name": "max_heap_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Perform a heap sort using a min heap.",
"function_declaration": "def min_heap_sort(arr):",
"functi... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef max_heapify(arr: List[int], n: int, i: int):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n a... | trial_gpt4o_1 | {
"original_instruction": "#### Context\nHeap Sort is an efficient comparison-based sorting algorithm that can either use a Max-Heap or Min-Heap. This task will help you understand the operational mechanics of both types and their implementations.\n\n#### Task\nImplement a function `dual_heap_sort` which sorts an arr... | 0.637648 | Data_Structure_41789 | C | [
"max_heap_sort",
"min_heap_sort",
"dual_heap_sort"
] | 3 | [
[
"dual_heap_sort",
"max_heap_sort"
],
[
"dual_heap_sort",
"min_heap_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 81940cbd0ec708c0c0df77d48d0bafaf304e038f | 1fa60112366ac1018dcf1808029345d4b79ada5b | |||
v1.0 | complete | Data_Structure | Data_Structure_42236_C | import math
def euclidean_distance(vector1, vector2):
"""
Compute the Euclidean distance between two vectors.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(vector1, vector2)))
def nearest_neighbor(user_vector: tuple, content_set: dict) -> str:
"""
Finds and returns the content identifi... | import math
def euclidean_distance(vector1, vector2):
"""
Compute the Euclidean distance between two vectors.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(vector1, vector2)))
def nearest_neighbor(user_vector: tuple, content_set: dict) -> str:
"""
Finds and returns the content identifi... | from solution import nearest_neighbor
def test_nearest_neighbor_basic():
user_vector = (3, 5, 1)
content_set = {
(1, 4, 2): 'Video A',
(3, 5, 6): 'Video B',
(4, 5, 1): 'Video C'
}
assert nearest_neighbor(user_vector, content_set) == 'Video C'
def test_nearest_neighbor_edge_case... | [
{
"docstring": "Compute the Euclidean distance between two vectors.",
"function_declaration": "def euclidean_distance(vector1, vector2):",
"function_name": "euclidean_distance",
"parameter_list": "(vector1, vector2)"
},
{
"docstring": "Finds and returns the content identifier/name most simil... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(vec1, vec2):\n \"\"\" Calculate the Euclidean distance between two vectors \"\"\"\n return math.sqrt(sum((a - b) *... | trial_gpt4o_2 | {
"original_instruction": "### Scenario:\nYou are implementing a basic recommender system using the Nearest Neighbor algorithm. Your task involves working with high-dimensional user preference vectors and a known set of content vectors to recommend the closest content to a user. Given a user vector and a set of conte... | 0.573017 | Data_Structure_42236 | C | [
"euclidean_distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2bd6e4431aa1013a9ca7d0e7b1046fa99fcf730f | 874fd987af28186e96d865a778836ef48d50beed | |||
v1.0 | complete | Data_Structure | Data_Structure_42036_C | def find_order(a: int, n: int) -> int:
"""
Determine the smallest positive integer `k` such that pow(a, k) % n == 1.
a: int - (must be coprime with n)
n: int - positive integer
Returns:
k: int - the order of a modulo n, or -1 if no such k exists.
>>> find_order(3, 7) == 6
>>> find_o... | def find_order(a, n):
"""
Determine the smallest positive integer `k` such that pow(a, k) % n == 1.
a: int - (must be coprime with n)
n: int - positive integer
Returns:
k: int - the order of a modulo n, or -1 if no such k exists.
"""
k = 1
current = a % n
while current != 1:... | from solution import find_order, euler_totient, find_primitive_root
def test_find_order():
assert find_order(3, 7) == 6
assert find_order(2, 5) == 4
assert find_order(5, 9) == 6
assert find_order(7, 13) == 12
assert find_order(2, 9) == 6
def test_euler_totient():
assert euler_totient(9) == 6
... | [
{
"docstring": "Determine the smallest positive integer `k` such that pow(a, k) % n == 1.\na: int - (must be coprime with n)\nn: int - positive integer\n\nReturns:\nk: int - the order of a modulo n, or -1 if no such k exists.",
"function_declaration": "def find_order(a, n):",
"function_name": "find_orde... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_order(a, n):\n \"\"\"\n Determine the smallest positive integer `k` such that pow(a, k) % n == 1.\n a: int - (must be coprime with n)\n n... | trial_gpt4o_5 | {
"original_instruction": "### Question: Finding Primitive Roots of a Number\n\nYou are required to implement functions related to finding primitive roots of a number. A primitive root of a positive integer `n` is any integer `a` such that all integers coprime with `n` are generated in a sequence modulo `n` by powers... | 0.567464 | Data_Structure_42036 | C | [
"find_order",
"euler_totient",
"find_primitive_root"
] | 3 | [
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"find_order"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6fe0c0d06ae052560c41c9e14834c8883477cc16 | 8e50229818c9c3e9b3aa6fa920cc99c57260b005 | |||
v1.0 | complete | Data_Structure | Data_Structure_42136_C | from typing import List, Sequence
def find_pattern_occurrences(text: Sequence[str], pattern: Sequence[str]) -> List[int]:
"""
Given two sequences, `text` and `pattern`, returns the starting indices of all occurrences of the `pattern` within the `text`.
Uses the Knuth-Morris-Pratt (KMP) algorithm to achieve... | from typing import List, Sequence
def kmp_partial_match_table(pattern: Sequence[str]) -> List[int]:
"""
Generates the partial match table (pi table) using the pattern.
"""
m = len(pattern)
pi = [0] * m
k = 0
for q in range(1, m):
while k > 0 and pattern[k] != pattern[q]:
... | from solution import find_pattern_occurrences
def test_find_pattern_occurrences_single_occurrence():
assert find_pattern_occurrences("hello there hero!", "there") == [6]
def test_find_pattern_occurrences_multiple_occurrences():
assert find_pattern_occurrences("hello there hero!", "he") == [0, 7, 12]
def test... | [
{
"docstring": "Generates the partial match table (pi table) using the pattern.",
"function_declaration": "def kmp_partial_match_table(pattern):",
"function_name": "kmp_partial_match_table",
"parameter_list": "(pattern)"
},
{
"docstring": "Returns the starting indices of all occurrences of `... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Sequence\n\ndef find_pattern_occurrences(text: Sequence[str], pattern: Sequence[str]) -> List[int]:\n \"\"\"\n Implement the Kn... | trial_gpt4o_1 | {
"original_instruction": "### Objective\nDesign a function that implements a string matching algorithm, demonstrating your understanding of the Knuth-Morris-Pratt (KMP) algorithm.\n\n### Problem Statement\nGiven two sequences, `text` and `pattern`, write a function `find_pattern_occurrences(text: Sequence[str], patt... | 0.668088 | Data_Structure_42136 | C | [
"kmp_partial_match_table",
"find_pattern_occurrences"
] | 2 | [
[
"find_pattern_occurrences",
"kmp_partial_match_table"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a7fe2d2000df4211dea741f0da8142f0db92353f | 14958c79ac2ba01788885d003f0c50501ba3186f | |||
v1.0 | complete | Data_Structure | Data_Structure_42325_C | def find_order(a: int, n: int) -> int:
""" Finds the order of `a` modulo `n`.
The order is the smallest positive integer k such that a^k ≡ 1 (mod n).
Returns -1 if no such k exists.
>>> find_order(2, 5)
4
>>> find_order(3, 7)
6
>>> find_order(2, 4)
-1
>>> find_order(1, 1)
... | import math
def gcd(a, b):
while b:
a, b = b, a % b
return a
def find_order(a: int, n: int) -> int:
"""
Finds the smallest positive integer k such that a^k ≡ 1 (mod n).
If no such k exists, returns -1.
"""
# If gcd(a, n) != 1, then no such k exists.
if gcd(a, n) != 1:
r... | from solution import find_order
def test_find_order_basic():
assert find_order(2, 5) == 4
assert find_order(3, 7) == 6
def test_find_order_non_coprime():
assert find_order(2, 4) == -1
assert find_order(12, 15) == -1
def test_find_order_other_cases():
assert find_order(2, 9) == 6
assert find_o... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Finds the smallest positive integer k such that a^k ≡ 1 (mod n).\nIf no such k exists, returns -1.",
"function_declaration": "def find_order(a, n):",
"... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(x, y):\n \"\"\"\n Helper function to compute the greatest common divisor of x and y.\n \"\"\"\n while(y):\n x, y = y, x % y\n re... | trial_gpt4o_7 | {
"original_instruction": "You are given a positive integer `n` and another integer `a` such that \\(\\text{gcd}(a, n) = 1\\). The order of `a` modulo `n` is the smallest positive integer `k` such that \\(a^k \\equiv 1 \\pmod{n}\\). Write a function that computes this order or returns -1 if it does not exist.\n\n### ... | 0.596281 | Data_Structure_42325 | C | [
"gcd",
"find_order"
] | 2 | [
[
"find_order",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7a6548e52e58b11235f68f71bb716582911de594 | 52e347c45e88be11f2ea398cf1b736445374f1d2 | |||
v1.0 | complete | Data_Structure | Data_Structure_41990_C | import random
from typing import Tuple
from sympy import isprime, mod_inverse
def generate_key(k_bits: int) -> Tuple[int, int, int]:
"""
Generate RSA public and private keys.
Args:
- k_bits (int): Number of bits for the primes p and q used to compute n.
Returns:
- Tuple (n, e, d): Pub... | import random
from sympy import isprime, mod_inverse
def generate_prime(bits):
while True:
num = random.getrandbits(bits)
if isprime(num):
return num
def generate_key(k_bits: int) -> (int, int, int):
"""
Generate RSA public and private keys.
Args:
- k_bits (int): N... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16)
assert n > 0
assert e > 0
assert d > 0
assert gcd(e, (n//2 - 1) * (n//2 - 1)) == 1 # Check if e and phi(n) are coprime
def test_encrypt_decrypt():
n, e, d = generate_key(16)
data =... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bits):",
"function_name": "generate_prime",
"parameter_list": "(bits)"
},
{
"docstring": "Generate RSA public and private keys.\n\nArgs:\n- k_bits (int): Number of bits for the primes p and q used to compute n.\n\nReturns:\n- T... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, randprime\nfrom math import gcd\n\ndef generate_key(k_bits: int) -> (int, int, int):\n if k_bits < 2:\n ra... | trial_gpt4o_1 | {
"original_instruction": "### RSA Key Generation and Encryption\n\nYou are required to implement RSA encryption and decryption using the principles outlined in the RSA algorithm. Your task is to write functions that:\n1. **Generate the RSA keys**: Public key (e, n) and private key (d, n).\n2. **Encrypt and Decrypt D... | 0.725481 | Data_Structure_41990 | C | [
"generate_prime",
"generate_key",
"gcd",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"generate_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | b16ecc5c0ab763fd89b3444bc1b9d04c440a0bdd | bf200bd31e1c385ef85a6b79ea02d12cb5fee9ba | |||
v1.0 | complete | Data_Structure | Data_Structure_42357_C | def is_prime(n: int, k: int) -> bool:
"""
Perform the Rabin-Miller primality test to determine if a given number n is a prime.
:param n: A positive integer n ≥ 2 to be tested for primality.
:param k: Number of iterations to perform the test, which influences the confidence level.
:return: True if n... | import random
def pow2_factor(num):
""" Factoring out the power of 2 from the number """
r = 0
d = num
while d % 2 == 0:
d //= 2
r += 1
return r, d
def valid_witness(a, n, r, d):
""" Check if a is a witness to the compositeness of n """
x = pow(a, d, n)
if x == 1 or x =... | from solution import is_prime
def test_small_primes():
assert is_prime(2, 5) == True
assert is_prime(3, 5) == True
def test_small_composites():
assert is_prime(4, 5) == False
assert is_prime(6, 5) == False
def test_large_primes():
# Using known large primes for testing
assert is_prime(101, 5)... | [
{
"docstring": "Factoring out the power of 2 from the number ",
"function_declaration": "def pow2_factor(num):",
"function_name": "pow2_factor",
"parameter_list": "(num)"
},
{
"docstring": "Check if a is a witness to the compositeness of n ",
"function_declaration": "def valid_witness(a,... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef pow2_factor(num: int) -> (int, int):\n \"\"\"Factor out powers of 2 from num such that num = 2^r * d with d odd.\"\"\"\n r = 0\n ... | trial_gpt4o_2 | {
"original_instruction": "### Rabin-Miller Primality Test Function Implementation\n\nAs a programming student, your task is to implement the Rabin-Miller primality test that determines if a given number \\( n \\) is a prime. The test is probabilistic with a tunable parameter \\( k \\) determining the number of itera... | 0.840392 | Data_Structure_42357 | C | [
"pow2_factor",
"valid_witness",
"is_prime"
] | 3 | [
[
"is_prime",
"pow2_factor"
],
[
"is_prime",
"valid_witness"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f059c6e78985fd013ff40d5c1ccb041237af8d0d | 9443c79906e1b60391e592fa2c2cf17582ede222 | |||
v1.0 | complete | Data_Structure | Data_Structure_42310_C | from typing import Dict, List, Tuple, Set
def traverse_and_count_components(graph: Dict[str, List[str]], start: str) -> Tuple[Set[str], Set[str], int]:
""" Traverse the graph using DFS and BFS starting from a given node, and count the number of connected components.
>>> graph = {
... "A": ["B", "C... | from typing import Dict, List, Tuple, Set
def dfs(graph: Dict[str, List[str]], start: str, visited: Set[str]):
stack = [start]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visite... | import pytest
from solution import traverse_and_count_components
def test_traverse_and_count_components_example():
graph = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
"G": ["H"],
"H": ["G"]
... | [
{
"docstring": null,
"function_declaration": "def dfs(graph, start, visited):",
"function_name": "dfs",
"parameter_list": "(graph, start, visited)"
},
{
"docstring": null,
"function_declaration": "def bfs(graph, start, visited):",
"function_name": "bfs",
"parameter_list": "(graph... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Dict, List, Tuple, Set\n\ndef traverse_and_count_components(graph: Dict[str, List[str]], start: str) -> Tuple[Set[str], Set[str], int]:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Graph Traversal and Node Count\n\nYou are provided an unweighted, undirected graph represented as an adjacency list where the nodes are identified by strings. Your task is to implement both Depth First Search (DFS) and Breadth First Search (BFS) traversals and calculate the number of co... | 0.575721 | Data_Structure_42310 | C | [
"dfs",
"bfs",
"count_connected_components",
"traverse_and_count_components"
] | 4 | [
[
"count_connected_components",
"dfs"
],
[
"traverse_and_count_components",
"bfs"
],
[
"traverse_and_count_components",
"count_connected_components"
],
[
"traverse_and_count_components",
"dfs"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 9d77c1f499084681fd762eacc412052106336ae6 | 3c0ad44ed3f8890cfd428071961f29a6b11e1f32 | |||
v1.0 | complete | Data_Structure | Data_Structure_42186_C | def dynamic_island_tracker(rows: int, cols: int, positions: List[List[int]]) -> List[int]:
""" Track the number of islands after each land formation operation in the grid.
>>> dynamic_island_tracker(3, 3, [[0, 0], [0, 1], [1, 2], [2, 1]])
[1, 1, 2, 3]
>>> dynamic_island_tracker(3, 3, [[0,0], [... | from typing import List
def find(parent, i):
if parent[i] != i:
parent[i] = find(parent, parent[i]) # path compression
return parent[i]
def union(parent, rank, x, y):
rootx = find(parent, x)
rooty = find(parent, y)
if rootx != rooty:
if rank[rootx] > rank[rooty]:
... | from solution import dynamic_island_tracker
def test_no_positions():
assert dynamic_island_tracker(5, 5, []) == []
def test_single_position():
assert dynamic_island_tracker(3, 3, [[0, 0]]) == [1]
def test_disconnected_positions():
assert dynamic_island_tracker(3, 3, [[0, 0], [2, 2]]) == [1, 2]
def test_... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef dynamic_island_tracker(rows: int, cols: int, positions: List[List[int]]) -> List[int]:\n parent = {}\n rank = {}\n isl... | trial_gpt4o_2 | {
"original_instruction": "## Question: Dynamic Island Tracker\n\n### Scenario\nYou are managing a coastal region represented by a 2D grid of water (0s) and land (1s). Initially, the grid is filled with water. Any land formation operation connects adjacent lands horizontally or vertically to form islands. Your task i... | 0.513404 | Data_Structure_42186 | C | [
"find",
"union",
"dynamic_island_tracker"
] | 3 | [
[
"dynamic_island_tracker",
"union"
],
[
"union",
"find"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7ff9c3f26525acf90bd22444e5c2f30ad5149985 | 880d6d584666d64f5a7b018baaf6cca2bfe0a985 | |||
v1.0 | complete | Data_Structure | Data_Structure_42438_C | from typing import List
def adaptive_search(array: List[int], search_key: int) -> int:
""" Perform adaptive search using Interpolation Search and Binary Search based on the distribution characteristics of the array.
>>> adaptive_search([-25, -12, -1, 10, 12, 15, 20, 41, 55], -1)
2
>>> adaptive_search([... | from typing import List
def interpolation_search(array: List[int], search_key: int) -> int:
lo, hi = 0, len(array) - 1
while lo <= hi and search_key >= array[lo] and search_key <= array[hi]:
if lo == hi:
if array[lo] == search_key:
return lo
return -1
... | from solution import adaptive_search
def test_adaptive_search_found():
assert adaptive_search([-25, -12, -1, 10, 12, 15, 20, 41, 55], -1) == 2
assert adaptive_search([5, 10, 12, 14, 17, 20, 21], 14) == 3
assert adaptive_search([5, 10, 12, 14, 17, 20, 21], 5) == 0
def test_adaptive_search_not_found():
... | [
{
"docstring": null,
"function_declaration": "def interpolation_search(array, search_key):",
"function_name": "interpolation_search",
"parameter_list": "(array, search_key)"
},
{
"docstring": null,
"function_declaration": "def binary_search(array, search_key):",
"function_name": "bin... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef adaptive_search(array: List[int], search_key: int) -> int:\n \"\"\"\n Performs adaptive search using Interpolation Search... | trial_gpt4o_1 | {
"original_instruction": "Advanced Search Implementation\n\nYou are part of a team building a high-performance search tool for large, sorted databases where the distribution of elements can vary. The current search functionality is built using binary search, but your team needs to optimize this for cases where the d... | 0.562226 | Data_Structure_42438 | C | [
"interpolation_search",
"binary_search",
"adaptive_search"
] | 3 | [
[
"adaptive_search",
"binary_search"
],
[
"adaptive_search",
"interpolation_search"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6b83c6531644b1eaa2e448272e0d87d1f3c87e3a | 3ef2f7c177f67431d15ae1aab8bf400139254240 | |||
v1.0 | complete | Data_Structure | Data_Structure_42221_C | from typing import Tuple
def extended_euclid(a: int, b: int) -> Tuple[int, int, int]:
""" Compute the coefficients and GCD using Extended Euclidean Algorithm.
>>> extended_euclid(1, 0) == (1, 0, 1)
>>> extended_euclid(25, 5) == (-1, 5, 5) or extended_euclid(25, 5) == (0, 1, 5)
>>> extended_euclid(240, ... | from typing import Tuple
def extended_euclid(a: int, b: int) -> Tuple[int, int, int]:
if b == 0:
return (1, 0, a)
else:
x1, y1, gcd = extended_euclid(b, a % b)
x = y1
y = x1 - (a // b) * y1
return (x, y, gcd)
def mod_inverse(a: int, m: int) -> int:
x, y, gcd = exten... | import pytest
from solution import extended_euclid, mod_inverse, secure_key_exchange
def test_extended_euclid():
assert extended_euclid(1, 0) == (1, 0, 1)
assert extended_euclid(25, 5) == (-1, 5, 5) or extended_euclid(25, 5) == (0, 1, 5)
assert extended_euclid(240, 46) == (-9, 47, 2) or extended_euclid(240... | [
{
"docstring": null,
"function_declaration": "def extended_euclid(a, b):",
"function_name": "extended_euclid",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def mod_inverse(a, m):",
"function_name": "mod_inverse",
"parameter_list": "(a, m)"
},
{
... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Tuple\n\ndef extended_euclid(a: int, b: int) -> Tuple[int, int, int]:\n \"\"\"\n Computes the greatest common divisor of a and b.\n ... | trial_gpt4o_4 | {
"original_instruction": "### Question: Implement Secure Key Exchange using Extended GCD\n\n#### Context\nIn modern cryptographic systems, especially those using RSA, it's critical to compute the modular inverse of large numbers for secure key exchange. To test your understanding of number theory and the Euclidean a... | 0.547061 | Data_Structure_42221 | C | [
"extended_euclid",
"mod_inverse",
"secure_key_exchange"
] | 3 | [
[
"mod_inverse",
"extended_euclid"
],
[
"secure_key_exchange",
"mod_inverse"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8c6cc05d6c82e00739d3f7ca6ac517b1351e18a6 | 6c5744d5bf04be7fab847ff2c07e723925248c7a | |||
v1.0 | complete | Data_Structure | Data_Structure_42150_C | def enhanced_gnome_sort(arr):
""" Sort a list of integers using gnome sort for lists with length <= 10 and a more efficient sorting algorithm for longer lists.
>>> enhanced_gnome_sort([34, 2, 78, 12, 5]) == [2, 5, 12, 34, 78]
>>> enhanced_gnome_sort([5, 8, 1, 3, 7, 9, 2]) == [1, 2, 3, 5, 7, 8, 9]
>>> en... | def gnome_sort(arr):
index = 0
while index < len(arr):
if index == 0 or arr[index] >= arr[index - 1]:
index += 1
else:
arr[index], arr[index - 1] = arr[index - 1], arr[index]
index -= 1
return arr
def enhanced_gnome_sort(arr):
if len(arr) <= 10:
... | from solution import enhanced_gnome_sort
def test_small_list():
assert enhanced_gnome_sort([34, 2, 78, 12, 5]) == [2, 5, 12, 34, 78]
assert enhanced_gnome_sort([5, 8, 1, 3, 7, 9, 2]) == [1, 2, 3, 5, 7, 8, 9]
assert enhanced_gnome_sort([3, 1, 2, 2, 1, 3]) == [1, 1, 2, 2, 3, 3]
def test_empty_and_single_ele... | [
{
"docstring": null,
"function_declaration": "def gnome_sort(arr):",
"function_name": "gnome_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def enhanced_gnome_sort(arr):",
"function_name": "enhanced_gnome_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_gnome_sort(arr):\n \"\"\"\n Sorts a list of integers using the gnome sort for small lists (len <= 10) \n and quicksort for larger lists.... | trial_gpt4o_2 | {
"original_instruction": "### Gnome Sort Implementation and Optimization\n\n#### Objective:\nYou are tasked with implementing the gnome sort algorithm as provided and enhancing it to switch to a more efficient sorting algorithm when the list is longer than a certain threshold.\n\n#### Problem Statement:\nWrite a fun... | 0.651076 | Data_Structure_42150 | C | [
"gnome_sort",
"enhanced_gnome_sort"
] | 2 | [
[
"enhanced_gnome_sort",
"gnome_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 82105fa40636d2cb5b5203448852a6bf9b7fca93 | b8ad33dabde8799a4cc441b02d1c68e1d0bfb206 | |||
v1.0 | complete | Data_Structure | Data_Structure_42175_C | import random
from typing import Tuple
def generate_key(k: int) -> Tuple[int, int, int]:
"""
Generates RSA key pair.
Parameters:
k (int): Key size in bits.
Returns:
tuple: (n, e, d) where
n is the modulus for public and private keys,
e is the public exponent,
... | import random
from sympy import isprime, mod_inverse
def generate_prime(bits):
"""Function to generate a prime number of given bits."""
p = random.getrandbits(bits)
while not isprime(p):
p = random.getrandbits(bits)
return p
def generate_key(k):
"""
Generates RSA key pair.
Par... | import pytest
from solution import generate_key, encrypt, decrypt
def test_key_generation():
n, e, d = generate_key(16)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert n > 0
assert e > 0
assert d > 0
def test_encrypt_decrypt_simple():
n, e, d = gene... | [
{
"docstring": "Function to generate a prime number of given bits.",
"function_declaration": "def generate_prime(bits):",
"function_name": "generate_prime",
"parameter_list": "(bits)"
},
{
"docstring": "Generates RSA key pair.\n\nParameters:\nk (int): Key size in bits.\n\nReturns:\ntuple: (n... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import randprime, gcd, mod_inverse\n\ndef generate_key(k):\n \"\"\"\n Generates RSA keys.\n \n Args:\n k (int): Key s... | trial_gpt4o_1 | {
"original_instruction": "### RSA Key Generation and Encryption/Decryption Implementation\n\nAs a skilled software engineer at a tech startup, you are tasked with implementing a secure message transfer system that uses RSA for encryption and decryption. Your first goal is to correctly generate RSA keys and ensure th... | 0.783567 | Data_Structure_42175 | C | [
"generate_prime",
"generate_key",
"encrypt",
"decrypt",
"gcd"
] | 5 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"generate_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 6ac5524695ff39cf13a988116586ec324fd96385 | 551de53d79850d6679ab8afaa1bd1a34979f2649 | |||
v1.0 | complete | Data_Structure | Data_Structure_41999_C | def search_insert(array, element, start, end):
""" Perform a binary search to find the index at which 'element' should be inserted into 'array'.
Args:
array (list): The list where the search should be performed.
element (int): The element for which to find the insertion index.
start (int): The star... | def search_insert(array, element, start, end):
"""
Perform a binary search to find the index at which 'element' should be inserted into 'array'.
Args:
array (list): The list where the search should be performed.
element (int): The element for which to find the insertion index.
start (int): The ... | from solution import binary_insertion_sort
def test_binary_insertion_sort_empty():
assert binary_insertion_sort([]) == []
def test_binary_insertion_sort_single_element():
assert binary_insertion_sort([1]) == [1]
def test_binary_insertion_sort_sorted_array():
assert binary_insertion_sort([1, 2, 3, 4, 5]) ... | [
{
"docstring": "Perform a binary search to find the index at which 'element' should be inserted into 'array'.\n\nArgs:\narray (list): The list where the search should be performed.\nelement (int): The element for which to find the insertion index.\nstart (int): The starting index of the sublist to be searched.\... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binary_search_insert_position(array, left, right, key):\n \"\"\"\n Utilizes binary search to find the insertion position for key in array[left:right... | trial_gpt4o_2 | {
"original_instruction": "**Scenario**: You are tasked with implementing a modified insertion sort algorithm for a performance-critical application. The classic insertion sort algorithm works efficiently for small arrays or nearly sorted arrays, but it can be slow on larger datasets due to its O(n^2) time complexity... | 0.62071 | Data_Structure_41999 | C | [
"search_insert",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dce24fc22312290c60ce7f1cb1e7d6ce0a54a1ff | 5ba3876be14d3186138351fe9229ced862793611 | |||
v1.0 | complete | Data_Structure | Data_Structure_42375_C | def diffie_hellman_key_exchange(a: int, p: int, print_keys: bool = False) -> bool:
"""
Perform Diffie-Hellman key exchange.
:param a: An integer, the primitive root modulo p.
:param p: A large prime integer.
:param print_keys: Optional; if set to True, print out the keys.
:return: True if the s... | import sympy
def prime_check(p):
return sympy.isprime(p)
def find_primitive_root(p):
if not prime_check(p):
return -1
for a in range(2, p):
powers = set(pow(a, i, p) for i in range(1, p))
if len(powers) == p - 1:
return a
return -1
def diffie_hellman_key_excha... | from solution import diffie_hellman_key_exchange
def test_diffie_hellman_valid():
a = 5
p = 23
assert diffie_hellman_key_exchange(a, p, print_keys=True) == True
def test_diffie_hellman_invalid_p():
a = 5
p = 24
assert diffie_hellman_key_exchange(a, p, print_keys=False) == False
def test_diffi... | [
{
"docstring": null,
"function_declaration": "def prime_check(p):",
"function_name": "prime_check",
"parameter_list": "(p)"
},
{
"docstring": null,
"function_declaration": "def find_primitive_root(p):",
"function_name": "find_primitive_root",
"parameter_list": "(p)"
},
{
... | [
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def prime_check(n: int) -> bool:\n \"\"\" Helper function to check if a number is prime. \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ... | trial_gpt4o_7 | {
"original_instruction": "### Diffie-Hellman Key Exchange Simulation\n\nImplement a simplified version of the Diffie-Hellman key exchange as follows:\n\n#### Function Signatures:\n```python\ndef diffie_hellman_key_exchange(a: int, p: int, print_keys: bool = False) -> bool:\n \"\"\"\n Perform Diffie-Hellman key... | 0.518001 | Data_Structure_42375 | C | [
"prime_check",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 3 | [
[
"diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"diffie_hellman_key_exchange",
"prime_check"
],
[
"find_primitive_root",
"prime_check"
]
] | 3 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 8bf3c28c81f657c2995de0eddc2a7ddd431514f2 | 643e415affb03fd2cdc3f9187fd27640e96409d5 | |||
v1.0 | complete | Data_Structure | Data_Structure_42180_C | from typing import List
def search_insert(arr: List[int], start: int, end: int, target: int) -> int:
""" Helper function to find the position to insert target into arr[start:end]."""
pass
def insertion_sort_with_helper(arr: List[int]) -> List[int]:
""" Sorts an array of integers using optimized insertion ... | from typing import List
def search_insert(arr: List[int], start: int, end: int, target: int) -> int:
""" Helper function to find the position to insert target into arr[start:end]."""
while start < end:
mid = (start + end) // 2
if arr[mid] < target:
start = mid + 1
else:
... | from solution import insertion_sort_with_helper
def test_insertion_sort_with_helper():
assert insertion_sort_with_helper([4, 2, 6, 1, 5]) == [1, 2, 4, 5, 6]
assert insertion_sort_with_helper([1, 3, 2, 4]) == [1, 2, 3, 4]
assert insertion_sort_with_helper([]) == []
assert insertion_sort_with_helper([5])... | [
{
"docstring": "Helper function to find the position to insert target into arr[start:end].",
"function_declaration": "def search_insert(arr, start, end, target):",
"function_name": "search_insert",
"parameter_list": "(arr, start, end, target)"
},
{
"docstring": "Sorts an array of integers us... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(arr: List[int], target: int, end: int) -> int:\n \"\"\"\n Binary search helper function to find the index w... | trial_gpt4o_2 | {
"original_instruction": "**Context**:\nYou are implementing a sorting functionality for a small e-commerce site that often processes relatively small and nearly sorted datasets. Given the nature of the data, an optimized insertion sort using a helper function to find the insertion position would be an ideal choice.... | 0.606475 | Data_Structure_42180 | C | [
"search_insert",
"insertion_sort_with_helper"
] | 2 | [
[
"insertion_sort_with_helper",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3bb4d362392fa351baf71035eccb9c08766cb895 | c2ddc0a89f37128e712b4ade0cf736c745e204a1 | |||
v1.0 | complete | Data_Structure | Data_Structure_41299_C | from typing import List
def bitonic_sort(arr: List[int], reverse: bool = False) -> List[int]:
"""
Sorts an array of integers using the bitonic sort algorithm.
Args:
arr (List[int]): List of integers to be sorted. The length should be a power of 2.
reverse (bool): If True, sort in descending or... | from typing import List
def bitonic_merge(arr: List[int], low: int, cnt: int, direction: bool) -> None:
if cnt > 1:
k = cnt // 2
for i in range(low, low + k):
if (direction == (arr[i] > arr[i + k])):
arr[i], arr[i + k] = arr[i + k], arr[i]
bitonic_merge(arr, low,... | from solution import bitonic_sort
def test_bitonic_sort_ascending():
arr = [3, 7, 2, 5, 6, 1, 4, 8]
expected = [1, 2, 3, 4, 5, 6, 7, 8]
assert bitonic_sort(arr, reverse=False) == expected
def test_bitonic_sort_descending():
arr = [10, 30, 20, 50, 60, 40, 90, 70]
expected = [90, 70, 60, 50, 40, 30,... | [
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, low, cnt, direction):",
"function_name": "bitonic_merge",
"parameter_list": "(arr, low, cnt, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_sort_recursive(arr, low, cnt, direction):",
"func... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef compare_and_swap(arr: List[int], i: int, j: int, direction: bool):\n if (direction and arr[i] > arr[j]) or (not direction an... | trial_gpt4o_2 | {
"original_instruction": "### Bitonic Sort Implementation\n\nYou are tasked with implementing the bitonic sort algorithm, which is useful for sorting arrays in parallel processing environments but here we are focused on a non-parallel implementation. Given an array of integers and a boolean indicating the desired or... | 0.689684 | Data_Structure_41299 | C | [
"bitonic_merge",
"bitonic_sort_recursive",
"bitonic_sort"
] | 3 | [
[
"bitonic_sort",
"bitonic_sort_recursive"
],
[
"bitonic_sort_recursive",
"bitonic_merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 64e55e647fdbda5951c17618aef682c7416a756f | f8d70c24f8c08a478bf238f01d49765fdcfdd704 | |||
v1.0 | complete | Data_Structure | Data_Structure_42279_C | def tree_print(tree: dict) -> None:
"""
Print each node and its corresponding children in a structured format.
Given a tree structure:
>>> tree = {
... 'a': ['Adam', 'Book', 4],
... 'b': ['Bill', ['Computer', 5, 'TV', 6], 'Jill', 'Sports', 1],
... 'c': ['Bill', 'Sports', 3],
... | def flatten_list(lst):
flattened = []
for item in lst:
if isinstance(item, list):
flattened.extend(flatten_list(item))
else:
flattened.append(item)
return flattened
def tree_print(tree):
for key, values in tree.items():
flattened_values = flatten_list(val... | from solution import tree_print
def test_tree_print_simple():
tree = {
'a': ['Adam', 'Book', 4],
'b': ['Bill']
}
tree_print(tree) # Output should be:
# a -> Adam -> Book -> 4
# b -> Bill
def test_tree_print_with_nested_lists():
tree = {
'a': ['Adam', 'Book', 4],
... | [
{
"docstring": null,
"function_declaration": "def flatten_list(lst):",
"function_name": "flatten_list",
"parameter_list": "(lst)"
},
{
"docstring": null,
"function_declaration": "def tree_print(tree):",
"function_name": "tree_print",
"parameter_list": "(tree)"
}
] | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def tree_print(tree: dict) -> None:\n def flatten_and_print(prefix, items):\n children = []\n for i in items:\n if isinstance(i, l... | trial_gpt4o_9 | {
"original_instruction": "### Tree Structure Printing\n\n#### Scenario:\nYou are working on a project to visualize hierarchical data in the form of organizational or directory structures. You have been provided with a nested dictionary, where keys represent node names and their values are lists of strings or sub-ele... | 0.517583 | Data_Structure_42279 | C | [
"flatten_list",
"tree_print"
] | 2 | [
[
"tree_print",
"flatten_list"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a591d57f8ee818c9e3ad592c1bc549bb7ece1807 | 2eb4cb1d2b20e49ce4e150e587c5454330886e7b | |||
v1.0 | complete | Data_Structure | Data_Structure_42434_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
""" Sorts an array of integers using the merge sort algorithm.
>>> merge_sort([38, 27, 43, 3, 9, 82, 10])
[3, 9, 10, 27, 38, 43, 82]
>>> merge_sort([1, 3, 2, 4, 2])
[1, 2, 2, 3, 4]
>>> merge_sort([])
[]
>>> merge_... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half,... | from solution import merge_sort
def test_merge_sort_example_1():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_example_2():
assert merge_sort([1, 3, 2, 4, 2]) == [1, 2, 2, 3, 4]
def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merg... | [
{
"docstring": "Sorts an array of integers using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into one sorted list.",
"function_declaration": "def merge(left... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_ha... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Implementation\n\nYou are tasked with implementing the `merge_sort` function designed to sort an array of integers using the merge sort algorithm.\n\n### Function Signature\n```python\ndef merge_sort(arr: List[int]) -> List[int]:\n pass\n```\n\n### Expected Input and Outpu... | 0.643265 | Data_Structure_42434 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d0805c1fa62a7c1a1ece8c06221506742789bfd7 | 5765b24c331c4215f0bc08a1a86679a0ed47bcc9 | |||
v1.0 | complete | Data_Structure | Data_Structure_41693_C | from typing import List
def search_insert(array: List[int], val: int) -> int:
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def insertion_sort(array: List... | from typing import List
def search_insert(array: List[int], val: int) -> int:
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def insertion_sort(array: List... | from solution import insertion_sort
def test_insertion_sort():
assert insertion_sort([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12]
assert insertion_sort([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13]
assert insertion_sort([]) == []
assert insertion_sort([1]) == [1]
assert insertion_sort([2, ... | [
{
"docstring": null,
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": null,
"function_declaration": "def insertion_sort(array):",
"function_name": "insertion_sort",
"parameter_list": "(a... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n low = 0\n high = len(array) - 1\n while low <= high:\n mid ... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort Enhancement with Binary Search\n\nInsertion Sort is a simple and intuitive algorithm suitable for small data sets. To perform insertion efficiently, we can utilize Binary Search to find the proper insertion spot instead of a linear search. \n\n**Prompt:**\n\nImplement the... | 0.636662 | Data_Structure_41693 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 848023e2fc1a44fc98b50feda53f13aaa3caa344 | 431ee613e602c03aba240e00936c7ea3eae416e2 | |||
v1.0 | complete | Data_Structure | Data_Structure_42549_C | def in_place_merge_sort(arr: list) -> list:
""" Sorts an array in place using the Merge Sort algorithm.
>>> in_place_merge_sort([38, 27, 43, 3, 9, 82, 10])
[3, 9, 10, 27, 38, 43, 82]
>>> in_place_merge_sort([])
[]
>>> in_place_merge_sort([1])
[1]
>>> in_place_merge_sort([6, 5, 4, 3, 2, 1... | def in_place_merge(arr, start, mid, end):
if arr[mid] <= arr[mid + 1]: # If the halves are already sorted
return
l, r = start, mid + 1
while l <= mid and r <= end:
if arr[l] <= arr[r]:
l += 1 # l is already in correct place
else:
temp = arr[r]
... | from solution import in_place_merge_sort
def test_in_place_merge_sort_empty():
assert in_place_merge_sort([]) == []
def test_in_place_merge_sort_single_element():
assert in_place_merge_sort([1]) == [1]
def test_in_place_merge_sort_multiple_elements():
assert in_place_merge_sort([38, 27, 43, 3, 9, 82, 10]... | [
{
"docstring": null,
"function_declaration": "def in_place_merge(arr, start, mid, end):",
"function_name": "in_place_merge",
"parameter_list": "(arr, start, mid, end)"
},
{
"docstring": null,
"function_declaration": "def in_place_merge_sort(arr):",
"function_name": "in_place_merge_so... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def in_place_merge_sort(arr):\n def merge(arr, l, m, r):\n # Merging two halves in place\n n1, n2 = m - l + 1, r - m\n for i in range(... | trial_gpt4o_2 | {
"original_instruction": "### Problem: Implement In-Place Merge Sort\n\nThe provided `merge_sort` function sorts an array using the Merge Sort algorithm. However, it uses additional memory which increases space complexity. Your task is to implement an in-place merge sort to reduce the space complexity.\n\n**Function... | 0.663908 | Data_Structure_42549 | C | [
"in_place_merge",
"in_place_merge_sort"
] | 2 | [
[
"in_place_merge_sort",
"in_place_merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4a80d7674d95dfb5d4f1394cb026b52081cba228 | a195b678ceaf526a1d868fef0635663eef7cc975 | |||
v1.0 | complete | Data_Structure | Data_Structure_42466_C | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def postorder_traversal(root: Node) -> dict:
""" Perform a post-order traversal of a binary tree and return a dictionary with iterative and recursive results.
Args:
... | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def recursive_postorder(root, result):
if root is not None:
recursive_postorder(root.left, result)
recursive_postorder(root.right, result)
result.append... | from solution import Node, postorder_traversal
def test_empty_tree():
assert postorder_traversal(None) == {"iterative": [], "recursive": []}
def test_single_node_tree():
root = Node(1)
expected = [1]
assert postorder_traversal(root) == {"iterative": expected, "recursive": expected}
def test_simple_tr... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef postorde... | trial_gpt4o_2 | {
"original_instruction": "### Post-order Traversal Challenge\n\nYou are given a binary tree, represented by the `Node` class below:\n\n```python\nclass Node:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n```\n\n#### Task\nWrite a f... | 0.508725 | Data_Structure_42466 | C | [
"recursive_postorder",
"iterative_postorder",
"postorder_traversal"
] | 3 | [
[
"postorder_traversal",
"iterative_postorder"
],
[
"postorder_traversal",
"recursive_postorder"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | true | [] | true | ebf324bb71e53d810e8434973fdb054d9d3e01c1 | a57e0442f1c32182b93f0aedfc780333b035f546 | |||
v1.0 | complete | Data_Structure | Data_Structure_42494_C | def concat_and_convert_to_int(int_list):
""" Concatenate a list of integers into a byte array in big-endian format
and return the byte array and the integer it represents.
>>> concat_and_convert_to_int([1, 256, 65536])
(b'\x00\x01\x00\x01\x00\x00\x01\x00', 4294967296 + 256 + 1)
>>> concat_and_conver... | def int_to_bytes_be(integer):
"""
Converts an integer to a byte array in big-endian format.
"""
if integer == 0:
return bytes([0])
byte_length = (integer.bit_length() + 7) // 8
return integer.to_bytes(byte_length, byteorder='big')
def bytes_to_int_be(byte_array):
"""
Converts a... | from solution import concat_and_convert_to_int
def test_concat_and_convert_to_int_single_element():
assert concat_and_convert_to_int([1]) == (b'\x01', 1)
assert concat_and_convert_to_int([256]) == (b'\x01\x00', 256)
assert concat_and_convert_to_int([65536]) == (b'\x01\x00\x00', 65536)
def test_concat_and_... | [
{
"docstring": "Converts an integer to a byte array in big-endian format.",
"function_declaration": "def int_to_bytes_be(integer):",
"function_name": "int_to_bytes_be",
"parameter_list": "(integer)"
},
{
"docstring": "Converts a big-endian byte array to an integer.",
"function_declaratio... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def int_to_bytes_big_endian(value):\n \"\"\"\n Converts an integer to a byte array in big-endian format\n \"\"\"\n return value.to_bytes((value.bi... | trial_gpt4o_2 | {
"original_instruction": "Given the implementations of functions to convert integers to byte arrays and back in both big-endian and little-endian formats, write a new function that takes a list of integers and returns a tuple:\n\n1. A byte array representation of their concatenation (all integers joined together) in... | 0.571168 | Data_Structure_42494 | C | [
"int_to_bytes_be",
"bytes_to_int_be",
"concat_and_convert_to_int"
] | 3 | [
[
"concat_and_convert_to_int",
"bytes_to_int_be"
],
[
"concat_and_convert_to_int",
"int_to_bytes_be"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6f47b79e341679308d66108e847095a6be0d307a | a9099aaae0805a0d8030c8a14d8d8d04da78e289 | |||
v1.0 | complete | Data_Structure | Data_Structure_42370_C | def matrix_mult(A: list, B: list) -> list:
"""
Multiplies two matrices A and B.
Args:
A (list): First matrix to multiply, a list of lists of integers.
B (list): Second matrix to multiply, a list of lists of integers.
Returns:
list: Result of matrix multiplication, a lis... | def matrix_mult(A, B):
"""
Multiplies two matrices A and B.
Assumes that A and B are square matrices of same dimensions.
"""
n = len(A)
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += A[i][k] * ... | import pytest
from solution import fast_matrix_exponentiation
def test_case_1():
mat = [[1, 2], [3, 4]]
power = 2
expected = [[7, 10], [15, 22]]
assert fast_matrix_exponentiation(mat, power) == expected
def test_case_2():
mat = [[2]]
power = 3
expected = [[8]]
assert fast_matrix_expone... | [
{
"docstring": "Multiplies two matrices A and B.\nAssumes that A and B are square matrices of same dimensions.",
"function_declaration": "def matrix_mult(A, B):",
"function_name": "matrix_mult",
"parameter_list": "(A, B)"
},
{
"docstring": "Creates an identity matrix of the given size.",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_multiply(A, B):\n d = len(A)\n result = [[0] * d for _ in range(d)]\n for i in range(d):\n for j in range(d):\n for k in... | trial_gpt4o_2 | {
"original_instruction": "## Matrix Exponentiation Challenge\n\n### Problem Statement\nYou are given a square matrix `mat` of size `d x d` and a positive integer `power`. Write a function `fast_matrix_exponentiation` to compute the matrix raised to the given power using repeated squaring method.\n\n### Function Sign... | 0.547828 | Data_Structure_42370 | C | [
"matrix_mult",
"matrix_identity",
"fast_matrix_exponentiation"
] | 3 | [
[
"fast_matrix_exponentiation",
"matrix_identity"
],
[
"fast_matrix_exponentiation",
"matrix_mult"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0435f413544dc094e191716898c590d7ad3aeba8 | 21bf1bbe2ceb8cf8bdd913aef9a7dc8aec25ef9b | |||
v1.0 | complete | Data_Structure | Data_Structure_42497_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big, small):
""" Determine if the smaller binary tree `small` is a subtree of the larger binary tree `big`.
Args:
big (TreeNode): The root nod... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_same_tree(tree1, tree2):
if not tree1 and not tree2:
return True
if not tree1 or not tree2:
return False
return (tree1.val == tree2.val and... | from solution import TreeNode, is_subtree
def test_subtree_exists():
# Creating nodes for the larger tree
n1 = TreeNode(3)
n2 = TreeNode(4)
n3 = TreeNode(5)
n4 = TreeNode(1)
n5 = TreeNode(2)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
# Creating nodes for the smal... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_0 | {
"original_instruction": "#### Scenario\nYou are a software engineer working on a project that involves processing and analyzing hierarchical data structures. One task requires determining if a specific configuration (represented as a smaller binary tree) is present within a larger dataset structure (represented as ... | 0.587488 | Data_Structure_42497 | C | [
"is_same_tree",
"is_subtree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 1cecf847e91bccd14c49ed20c4bccae511377066 | 341ff9f85060e22af0be4b27fa2700fa14272329 | |||
v1.0 | complete | Data_Structure | Data_Structure_42437_C | from typing import List, Tuple
def compress_vector(vector: List[float]) -> List[Tuple[int, float]]:
"""
Compresses a vector into a list of index-value pairs, excluding zeros.
"""
compressed = []
for i, value in enumerate(vector):
if value != 0.0:
compressed.append((i, value))
... | from typing import List, Tuple
def compress_vector(vector: List[float]) -> List[Tuple[int, float]]:
"""
Compresses a vector into a list of index-value pairs, excluding zeros.
"""
compressed = []
for i, value in enumerate(vector):
if value != 0.0:
compressed.append((i, value))
... | def test_optimized_dot_product_all_zeros():
vector1 = [0.0, 0.0, 0.0]
vector2 = [0.0, 0.0, 0.0]
assert optimized_dot_product(vector1, vector2) == 0.0
def test_optimized_dot_product_mixed_values():
vector1 = [1.0, 0.0, 3.0, 0.0, 4.0]
vector2 = [0.0, 2.0, 1.0, 0.0, 5.0]
assert optimized_dot_produ... | [
{
"docstring": "Compresses a vector into a list of index-value pairs, excluding zeros.",
"function_declaration": "def compress_vector(vector):",
"function_name": "compress_vector",
"parameter_list": "(vector)"
},
{
"docstring": "Computes the dot product of two sparse vectors represented as l... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef compress_vector(vector: List[float]) -> List[Tuple[int, float]]:\n \"\"\"\n Converts a sparse vector into a compre... | trial_gpt4o_9 | {
"original_instruction": "### Dot Product of Sparse Vectors\n\n#### Problem Statement\nYou are provided with a function to convert a list representing a vector into a compressed format (index-value pairs). The main task is to implement a new function that calculates the dot product of two such compressed vectors eff... | 0.559079 | Data_Structure_42437 | C | [
"compress_vector",
"optimized_dot_product"
] | 2 | [
[
"optimized_dot_product",
"compress_vector"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | e2dab10b1afa468e47b5797292b6e9a0febf1bd4 | 062873e8b35fb89be13d48dd42cc68b309d85717 | |||
v1.0 | complete | Data_Structure | Data_Structure_42066_C | import collections
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(s, t):
""" Returns True if binary tree t is a subtree of binary tree s.
>>> s = TreeNode(3)
>>> s.left = TreeNode(4)
>>> s.... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(s, t):
"""
Returns True if binary tree t is a subtree of binary tree s.
"""
if not s:
return False
if is_same_tree(s, t):
r... | from solution import TreeNode, is_subtree
def test_example_1():
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.left.right = TreeNode(2)
t = TreeNode(4)
t.left = TreeNode(1)
t.right = TreeNode(2)
assert is_subtree(s, t) == True
def t... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_1 | {
"original_instruction": "### Problem: Check if Tree is a Subtree\n\nGiven two binary trees `s` and `t`, write a function `is_subtree(s, t)` that returns `True` if `t` is a subtree of `s`, and `False` otherwise. A subtree of a tree `t` is a tree consisting of a node in `t` and all of its descendants. \n\n### Input F... | 0.618359 | Data_Structure_42066 | C | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 96d2b0ff886a4843ecf93f0b349e4166f3f01fe0 | d37c84ccab83bc17eda4963eec8c365ac7224603 | |||
v1.0 | complete | Data_Structure | Data_Structure_42588_C | def heap_sort(arr: list) -> list:
"""
Sorts the given list of integers in ascending order using Heap Sort.
:param arr: List of integers to be sorted.
:return: List of sorted integers.
>>> heap_sort([4, 10, 3, 5, 1])
[1, 3, 4, 5, 10]
>>> heap_sort([0, -5, 3, 7, 2])
[-5, 0, 2, 3, 7]... | def heapify(arr, n, i):
"""
To heapify a subtree rooted with node i which is an index in arr[].
n is size of heap.
"""
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is greater than root... | from solution import heap_sort
def test_heap_sort_basic():
assert heap_sort([4, 10, 3, 5, 1]) == [1, 3, 4, 5, 10]
def test_heap_sort_negative():
assert heap_sort([0, -5, 3, 7, 2]) == [-5, 0, 2, 3, 7]
def test_heap_sort_duplicate_values():
assert heap_sort([2, 2, 2, 2, 2]) == [2, 2, 2, 2, 2]
def test_hea... | [
{
"docstring": "To heapify a subtree rooted with node i which is an index in arr[].\nn is size of heap.",
"function_declaration": "def heapify(arr, n, i):",
"function_name": "heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Sorts the given list of integers in ascending order usin... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def heapify(arr, n, i):\n \"\"\"\n Helper function to maintain the heap property of a subtree rooted at index i,\n assuming that the subtrees are alr... | trial_gpt4o_2 | {
"original_instruction": "#### Scenario\nYou are developing a program that sorts employee performance scores stored in an array. To ensure the results are consistent, you have chosen to use Heap Sort since it guarantees O(n log(n)) time complexity and sorts in place.\n\n#### Problem\nYou need to implement a function... | 0.730835 | Data_Structure_42588 | C | [
"heapify",
"heap_sort"
] | 2 | [
[
"heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0ad90d70a72375f7674b724c08de00a015d5f52c | 82219c4395b72a3c6b25eda23931af7ba4932144 | |||
v1.0 | complete | Data_Structure | Data_Structure_42101_C | def find_factorial(n):
""" Calculates the factorial of a given number n """
# your code here
def krishnamurthy_number(n):
"""
Verifies if a given number n is a Krishnamurthy number.
A Krishnamurthy number is where the sum of the factorials of its digits equals the number itself.
>>> ... | def find_factorial(n):
"""Calculates the factorial of a given number n."""
if n == 0 or n == 1:
return 1
factorial = 1
for i in range(2, n + 1):
factorial *= i
return factorial
def krishnamurthy_number(n):
"""Checks if n is a Krishnamurthy number."""
def compute_digit_factor... | from solution import find_factorial, krishnamurthy_number
def test_find_factorial():
assert find_factorial(0) == 1
assert find_factorial(1) == 1
assert find_factorial(2) == 2
assert find_factorial(3) == 6
assert find_factorial(4) == 24
assert find_factorial(5) == 120
def test_krishnamurthy_num... | [
{
"docstring": "Calculates the factorial of a given number n.",
"function_declaration": "def find_factorial(n):",
"function_name": "find_factorial",
"parameter_list": "(n)"
},
{
"docstring": "Checks if n is a Krishnamurthy number.",
"function_declaration": "def krishnamurthy_number(n):",... | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_factorial(n):\n \"\"\"\n Calculates the factorial of a given number n.\n \"\"\"\n if n == 0:\n return 1\n factorial = 1\n fo... | trial_gpt4o_8 | {
"original_instruction": "### Krishnamurthy Number Checker\n\n#### Scenario:\nYou are working on a number puzzle game where players need to identify special numbers with unique properties. A Krishnamurthy number is a special number where the sum of the factorials of its digits equals the number itself. You need to w... | 0.524684 | Data_Structure_42101 | C | [
"find_factorial",
"krishnamurthy_number"
] | 2 | [
[
"krishnamurthy_number",
"find_factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7ac92196190d164e970c4642bd682ce12a616e7d | 0971ce45caab9953ebce8ac0b33153ed9bd69a98 | |||
v1.0 | complete | Data_Structure | Data_Structure_42425_C | def construct(arr):
"""
Constructs and returns a Binary Indexed Tree (BIT) from a given integer array `arr`.
"""
pass
def get_sum(bit_tree, index):
"""
Returns the sum of elements from the start of the array to the given `index` using the provided Binary Indexed Tree `bit_tree`.
"""
pas... | def construct(arr):
"""
Constructs and returns a Binary Indexed Tree (BIT) from a given integer array `arr`.
"""
n = len(arr)
bit_tree = [0] * (n + 1)
for i in range(n):
update_bit(bit_tree, i, arr[i])
return bit_tree
def get_sum(bit_tree, index):
"""
Returns the sum of el... | from solution import construct, get_sum, update_bit
def test_construct_empty_array():
arr = []
bit_tree = construct(arr)
assert bit_tree == [0]
def test_construct():
arr = [1, 2, 3, 4, 5]
bit_tree = construct(arr)
assert bit_tree == [0, 1, 3, 3, 10, 5]
def test_get_sum():
arr = [1, 2, 3, ... | [
{
"docstring": "Constructs and returns a Binary Indexed Tree (BIT) from a given integer array `arr`.",
"function_declaration": "def construct(arr):",
"function_name": "construct",
"parameter_list": "(arr)"
},
{
"docstring": "Returns the sum of elements from the start of the array to the give... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def construct(arr):\n \"\"\"\n Constructs and returns a Binary Indexed Tree (BIT) from a given integer array `arr`.\n \"\"\"\n n = len(arr)\n b... | trial_gpt4o_1 | {
"original_instruction": "### Question\n\nYou are required to implement a system that can efficiently manage prefix sum queries and updates on an array using a Fenwick Tree (also known as a Binary Indexed Tree). \n\n### Task\n\n1. **Function 1**: `construct(arr)`:\n - Constructs and returns a Binary Indexed Tree (... | 0.595379 | Data_Structure_42425 | C | [
"construct",
"get_sum",
"update_bit"
] | 3 | [
[
"construct",
"update_bit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 84e5b2fb1bf5c5fceb7da3b88fd263bee9c83d25 | 5dd87a08c33f617a924e031c9151309c3f3d52d8 | |||
v1.0 | complete | Data_Structure | Data_Structure_42336_C | from typing import List
import math
def insertion_sort(bucket):
"""
Helper function to sort an individual bucket using insertion sort,
which is efficient for small datasets.
"""
for i in range(1, len(bucket)):
key = bucket[i]
j = i - 1
while j >= 0 and bucket[j] > key:
... | from typing import List
import math
def insertion_sort(bucket):
"""
Helper function to sort an individual bucket using insertion sort,
which is efficient for small datasets.
"""
for i in range(1, len(bucket)):
key = bucket[i]
j = i - 1
while j >= 0 and bucket[j] > key:
... | from solution import bucket_sort
def test_bucket_sort_unsorted():
assert bucket_sort([0.45, 0.12, 0.89, 0.39, 0.71]) == [0.12, 0.39, 0.45, 0.71, 0.89]
def test_bucket_sort_mixed():
assert bucket_sort([0.23, 0.56, 0.22, 0.78, 0.35]) == [0.22, 0.23, 0.35, 0.56, 0.78]
def test_bucket_sort_empty():
assert bu... | [
{
"docstring": "Helper function to sort an individual bucket using insertion sort,\nwhich is efficient for small datasets.",
"function_declaration": "def insertion_sort(bucket):",
"function_name": "insertion_sort",
"parameter_list": "(bucket)"
},
{
"docstring": "Sorts a list of floating poin... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[float]) -> List[float]]:\n \"\"\"\n Helper function to sort an individual bucket using insertion... | trial_gpt4o_2 | {
"original_instruction": "You are provided with a list of floating point numbers. Your task is to write a function called `bucket_sort` that sorts these numbers using the bucket sort algorithm. Additionally, make improvements to handle poor distributions efficiently. Ensure that the bucket sort is not only competiti... | 0.588183 | Data_Structure_42336 | C | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6b22a1600ed3dff5668370aff05f5b84236dd0d1 | 6ac5d9a057d7564870adf5c625eed89533537c03 | |||
v1.0 | complete | Data_Structure | Data_Structure_42934_C | def enhanced_radix_sort(arr: list[int]) -> list[int]:
""" Radix Sort Implementation for Large Dataset
Sort a list of non-negative integers using the Radix Sort algorithm.
>>> enhanced_radix_sort([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66, 75, 90, 170, 802]
>>> enhanced_radix_sort([1, 4, ... | def enhanced_radix_sort(arr: list[int]) -> list[int]:
"""
This function sorts a list of non-negative integers using Radix Sort.
"""
if not arr:
return arr
# Find the maximum number in the array to determine the number of digits
max_num = max(arr)
exp = 1 # Start with the least... | from solution import enhanced_radix_sort
def test_enhanced_radix_sort_example_1():
assert enhanced_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_enhanced_radix_sort_example_2():
assert enhanced_radix_sort([1, 4, 1, 2, 7, 5, 2]) == [1, 1, 2, 2, 4, 5, 7]
def test_e... | [
{
"docstring": "This function sorts a list of non-negative integers using Radix Sort.",
"function_declaration": "def enhanced_radix_sort(arr):",
"function_name": "enhanced_radix_sort",
"parameter_list": "(arr)"
},
{
"docstring": "A utility function to perform counting sort on arr[] according... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_radix_sort(arr: list[int]) -> list[int]:\n def counting_sort(arr: list[int], exp: int) -> list[int]:\n n = len(arr)\n output = [... | trial_gpt4o_2 | {
"original_instruction": "### Radix Sort Implementation: Large Dataset Sorting\n\n##### Background\n\nYou are tasked with implementing a highly efficient sorting algorithm to handle a vast dataset comprising non-negative integers. Your solution must leverage the Radix Sort algorithm to sort these integers. This sort... | 0.666875 | Data_Structure_42934 | C | [
"enhanced_radix_sort",
"counting_sort"
] | 2 | [
[
"enhanced_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f41cbb432c7260a0c8f3306674cfaf5ab6d0f7be | ade26ba70c3364efffabb1e04547993369a6df20 | |||
v1.0 | complete | Data_Structure | Data_Structure_42841_C | class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def is_same_inorder(tree1: Node, tree2: Node) -> bool:
""" Check if two binary trees have the same in-order traversal.
>>> n1 = Node(100)
>>> n2 = Node(50)
>>> n3 = Node(150)
>>> n4 =... | class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def inorder_traversal(root):
if root is None:
return []
return inorder_traversal(root.left) + [root.val] + inorder_traversal(root.right)
def is_same_inorder(tree1: Node, tree2: Node) -> b... | from solution import Node, is_same_inorder
def test_identical_trees():
# Tree 1
n1 = Node(100)
n2 = Node(50)
n3 = Node(150)
n4 = Node(25)
n5 = Node(75)
n6 = Node(125)
n7 = Node(175)
n1.left, n1.right = n2, n3
n2.left, n2.right = n4, n5
n3.left, n3.right = n6, n7
# Tree ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, value: int):\n self.value = value\n self.left = None\n self.right = None\n\ndef is_same_inorder(tree1... | trial_gpt4o_2 | {
"original_instruction": "#### Task\n\nWrite a function, `is_same_inorder(tree1: Node, tree2: Node) -> bool`, that takes two binary trees and checks if they have the same in-order traversal.\n\n#### Description\n\nGiven two binary trees, determine if the sequence of values in their in-order traversal is identical. T... | 0.568298 | Data_Structure_42841 | C | [
"inorder_traversal",
"is_same_inorder"
] | 2 | [
[
"is_same_inorder",
"inorder_traversal"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 0b58366046489b8116bda97164e307fc6f16b728 | 891510019fb1f44c1bd133568ac09975eac18ff8 | |||
v1.0 | complete | Data_Structure | Data_Structure_42083_C | def get_bit(num: int, i: int) -> int:
"""
Returns the value of the bit at index i.
"""
pass
def set_bit(num: int, i: int) -> int:
"""
Sets the bit at index i to 1.
"""
pass
def clear_bit(num: int, i: int) -> int:
"""
Clears (sets to 0) the bit at index i.
"""
pass
def ... | def get_bit(num, i):
"""
Returns the value of the bit at index i.
"""
return (num >> i) & 1
def set_bit(num, i):
"""
Sets the bit at index i to 1.
"""
return num | (1 << i)
def clear_bit(num, i):
"""
Clears (sets to 0) the bit at index i.
"""
return num & ~(1 << i)
def... | from solution import get_bit, set_bit, clear_bit, update_bit, modify_bits
def test_get_bit():
assert get_bit(0b0101, 0) == 1
assert get_bit(0b0101, 1) == 0
assert get_bit(0b0101, 2) == 1
assert get_bit(0b0101, 3) == 0
def test_set_bit():
assert set_bit(0b0100, 0) == 0b0101
assert set_bit(0b000... | [
{
"docstring": "Returns the value of the bit at index i.",
"function_declaration": "def get_bit(num, i):",
"function_name": "get_bit",
"parameter_list": "(num, i)"
},
{
"docstring": "Sets the bit at index i to 1.",
"function_declaration": "def set_bit(num, i):",
"function_name": "set... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple, Optional\n\ndef get_bit(num: int, i: int) -> int:\n \"\"\"\n Returns the value of the bit at index i.\n \"\"\"\n r... | trial_gpt4o_2 | {
"original_instruction": "You have been provided with a set of fundamental bit manipulation functions that perform basic operations on individual bits of an integer. These four functions are:\n\n1. `get_bit(num, i)` - Returns the value of the bit at index `i`.\n2. `set_bit(num, i)` - Sets the bit at index `i` to 1.\... | 0.723798 | Data_Structure_42083 | C | [
"get_bit",
"set_bit",
"clear_bit",
"update_bit",
"modify_bits"
] | 5 | [
[
"modify_bits",
"clear_bit"
],
[
"modify_bits",
"get_bit"
],
[
"modify_bits",
"set_bit"
],
[
"modify_bits",
"update_bit"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | d36971254fdcd9003be877e16701b324a3b08341 | 228bd68d183492f7650d2ccd725894a1876e247b | |||
v1.0 | complete | Data_Structure | Data_Structure_42849_C | def invert_matrix(matrix):
""" Computes and returns the inverse of a square, invertible matrix.
The function follows these steps:
1. Compute the matrix of minors.
2. Form the matrix of cofactors.
3. Adjugate the matrix.
4. Calculate the inverse.
Args:
matrix (list of list of int): ... | def determinant(matrix):
if len(matrix) == 1:
return matrix[0][0]
if len(matrix) == 2:
return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]
det = 0
for c in range(len(matrix)):
det += ((-1)**c) * matrix[0][c] * determinant(minor(matrix, 0, c))
return det
def minor(ma... | from solution import invert_matrix
def test_invert_matrix():
assert invert_matrix(123) == [[-1]]
def test_invert_matrix_not_a_square():
assert invert_matrix([[1, 2, 3], [4, 5, 6]]) == [[-2]]
def test_invert_matrix_size_less_than_2():
assert invert_matrix([[5]]) == [[-3]]
def test_invert_matrix_singular_... | [
{
"docstring": null,
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def minor(matrix, i, j):",
"function_name": "minor",
"parameter_list": "(matrix, i, j)"
},
{
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef invert_matrix(matrix):\n if not isinstance(matrix, list) or not all(isinstance(row, list) for row in matrix):\n return [[-... | trial_gpt4o_1 | {
"original_instruction": "You are given a square, invertible matrix represented as a list of lists in Python. Write a function `invert_matrix` that computes and returns the inverse of the matrix using the matrix inversion algorithm outlined below.\n\n### Algorithm Steps\n1. Compute the **matrix of minors**: For each... | 0.551391 | Data_Structure_42849 | C | [
"determinant",
"minor",
"matrix_of_minors",
"matrix_of_cofactors",
"transpose",
"invert_matrix"
] | 6 | [
[
"determinant",
"minor"
],
[
"invert_matrix",
"determinant"
],
[
"invert_matrix",
"matrix_of_cofactors"
],
[
"invert_matrix",
"matrix_of_minors"
],
[
"invert_matrix",
"transpose"
],
[
"matrix_of_minors",
"determinant"
],
[
"matrix_of_minor... | 7 | [] | false | [] | false | pytest | true | [] | true | f485b22656f78d3c341ba24acb1e6002028d9452 | d4e2961da115932a20519870923666a931522baa | |||
v1.0 | complete | Data_Structure | Data_Structure_42888_C | import random
from sympy import isprime, mod_inverse
def generate_rsa_keys(bits, seed=None):
"""Generate RSA keys for encryption and decryption.
>>> n, e, d = generate_rsa_keys(16, seed=42)
>>> isinstance(n, int) and isinstance(e, int) and isinstance(d, int)
True
"""
# Function implementation g... | import random
from sympy import isprime, mod_inverse
def generate_prime(bits, seed=None):
if seed is not None:
random.seed(seed)
while True:
num = random.getrandbits(bits)
if isprime(num):
return num
def generate_rsa_keys(bits, seed=None):
if bits <= 1:
raise Va... | from solution import generate_rsa_keys, rsa_encrypt, rsa_decrypt
def test_generate_rsa_keys():
n, e, d = generate_rsa_keys(16, seed=42)
assert n > 0
assert e > 0
assert d > 0
def test_rsa_encrypt_decrypt():
n, e, d = generate_rsa_keys(16, seed=42)
data = 123
encrypted_data = rsa_encrypt(da... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bits, seed=None):",
"function_name": "generate_prime",
"parameter_list": "(bits, seed=None)"
},
{
"docstring": null,
"function_declaration": "def generate_rsa_keys(bits, seed=None):",
"function_name": "generate_rsa_keys... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, gcd\n\ndef generate_large_prime(bits, seed=None):\n if seed is not None:\n random.seed(seed)\n while Tr... | trial_gpt4o_1 | {
"original_instruction": "### RSA Encryption Design & Implementation\n\nAs a new encryption expert, you've been tasked with developing a secure communication channel for a company's internal systems, using RSA encryption. \n\n**Objective**: Implement an RSA encryption-decryption system tailored for small data messag... | 0.676733 | Data_Structure_42888 | C | [
"generate_prime",
"generate_rsa_keys",
"rsa_encrypt",
"rsa_decrypt"
] | 4 | [
[
"generate_rsa_keys",
"generate_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 4aa0b040988685d557581f081568fe636efce3b9 | acae23b28166404dd9fc67269fd4bd786a9fe9d8 | |||
v1.0 | complete | Data_Structure | Data_Structure_42942_C | from typing import List, Dict
def multi_pattern_search(patterns: List[str], text: str) -> Dict[str, List[int]]:
"""
Searches for multiple patterns in the main text using an optimized Rabin-Karp algorithm.
Returns a dictionary mapping each pattern to a list of its starting indices in the text.
>>>... | def rabin_karp_search(pattern, text, base=256, mod=101):
"""
Searches for occurrences of a pattern in the text using Rabin-Karp algorithm.
Returns a list of starting indices where the pattern is found.
"""
m, n = len(pattern), len(text)
if m > n:
return []
# Compute the hash val... | from solution import multi_pattern_search
def test_multi_pattern_search_basic():
patterns = ["abc", "bc", "a"]
text = "abcabcabc"
expected = {
"abc": [0, 3, 6],
"bc": [1, 4, 7],
"a": [0, 3, 6]
}
assert multi_pattern_search(patterns, text) == expected
def test_multi_pattern_... | [
{
"docstring": "Searches for occurrences of a pattern in the text using Rabin-Karp algorithm.\nReturns a list of starting indices where the pattern is found.",
"function_declaration": "def rabin_karp_search(pattern, text, base=256, mod=101):",
"function_name": "rabin_karp_search",
"parameter_list": ... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def rabin_karp_search(pattern, text, base=256, mod=101):\n \"\"\"\n Searches for occurrences of a pattern in the text using Rabin-Karp algorithm.\n R... | trial_gpt4o_0 | {
"original_instruction": "You are provided with the implementation of the Rabin-Karp algorithm for substring searching within a main string. Your task is to extend and optimize this algorithm to handle multiple patterns efficiently and reduce the likelihood of hash collisions.\n\n### Objective\n\nImplement a functio... | 0.702995 | Data_Structure_42942 | C | [
"rabin_karp_search",
"multi_pattern_search"
] | 2 | [
[
"multi_pattern_search",
"rabin_karp_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f79fe926b848e79a887da2fbb1f1c3bbdc5215fb | e7fcb416d6665987aaeb33861610bd5557824948 | |||
v1.0 | complete | Data_Structure | Data_Structure_42961_C | def hybrid_sort(arr: list[int], threshold: int) -> list[int]:
"""
Sorts an array of integers using a hybrid of Heap Sort and Quick Sort.
:param arr: List of integers to be sorted.
:param threshold: Size threshold for switching between Heap Sort and Quick Sort.
For sub-arrays large... | def hybrid_sort(arr, threshold):
"""
Sorts an array of integers using a hybrid of Heap Sort and Quick Sort.
:param arr: List of integers to be sorted.
:param threshold: Size threshold for switching between Heap Sort and Quick Sort.
For sub-arrays larger than this threshold, use He... | from solution import hybrid_sort
def test_hybrid_sort_small_array():
assert hybrid_sort([3, 1, 2], 2) == [1, 2, 3]
def test_hybrid_sort_with_duplicates():
assert hybrid_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], 5) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
def test_hybrid_sort_large_threshold():
assert hybrid_so... | [
{
"docstring": "Sorts an array of integers using a hybrid of Heap Sort and Quick Sort.\n\n:param arr: List of integers to be sorted.\n:param threshold: Size threshold for switching between Heap Sort and Quick Sort.\n For sub-arrays larger than this threshold, use Heap Sort.\n F... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def quick_sort(arr):\n \"\"\"\n Quick Sort implementation\n \"\"\"\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n le... | trial_gpt4o_2 | {
"original_instruction": "## Objective\nImplement a custom hybrid sorting algorithm that combines Heap Sort with another sorting algorithm like Quick Sort to optimize sorting performance. This algorithm should dynamically decide which sorting technique to use based on the characteristics of the sub-array being sorte... | 0.64455 | Data_Structure_42961 | C | [
"hybrid_sort",
"quick_sort",
"heap_sort"
] | 3 | [
[
"hybrid_sort",
"heap_sort"
],
[
"hybrid_sort",
"quick_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c10f5d50026fd2b697288b17a73ce23c799f18a3 | 4856c1c07695e814e3d0eb3ce7353b0698196480 | |||
v1.0 | complete | Data_Structure | Data_Structure_43065_C | from typing import List
def efficient_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers in non-decreasing order using an efficient algorithm.
Parameters:
arr (List[int]): List of integers to sort.
Returns:
List[int]: Sorted list of integers in non-decreasing order.
Example:... | from typing import List
def efficient_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers in non-decreasing order using Merge Sort.
Parameters:
arr (List[int]): List of integers to sort.
Returns:
List[int]: Sorted list of integers in non-decreasing order.
"""
if le... | from solution import efficient_sort
def test_sorted_list():
assert efficient_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list():
assert efficient_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_unsorted_list():
assert efficient_sort([4, 2, 5, 1, 3]) == [1, 2, 3, 4, 5]
def test_lis... | [
{
"docstring": "Sorts a list of integers in non-decreasing order using Merge Sort.\n\nParameters:\narr (List[int]): List of integers to sort.\n\nReturns:\nList[int]: Sorted list of integers in non-decreasing order.",
"function_declaration": "def efficient_sort(arr):",
"function_name": "efficient_sort",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef efficient_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of integers in non-decreasing order using Merge Sort... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement Efficient Sorting Algorithm\n\n#### Scenario\nYou are working on improving a legacy system where a highly inefficient Bogo Sort algorithm was previously used. Your task is to replace it with a more efficient sorting algorithm while ensuring it meets certain performan... | 0.683224 | Data_Structure_43065 | C | [
"efficient_sort",
"merge"
] | 2 | [
[
"efficient_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2ea82d65357987965835e2f4e17bbde66c8b417c | 4f1e561e34e6451d5caf7169c91d7bfcb29967fc | |||
v1.0 | complete | Data_Structure | Data_Structure_43145_C | from typing import List
def bitonic_sort(arr: List[int], reverse: bool = False) -> List[int]:
"""Implement the Bitonic Sort algorithm for a list of integers where the length of the list is a power of 2.
Args:
arr (List[int]): A list of integers where the length of the list is a power of 2.
reverse (bo... | from typing import List
def bitonic_merge(arr: List[int], low: int, cnt: int, reverse: bool):
if cnt > 1:
k = cnt // 2
for i in range(low, low + k):
if (arr[i] > arr[i + k]) == (not reverse):
arr[i], arr[i + k] = arr[i + k], arr[i]
bitonic_merge(arr, low, k, reve... | from solution import bitonic_sort
def test_bitonic_sort_ascending():
assert bitonic_sort([4, 2, 7, 1], False) == [1, 2, 4, 7]
assert bitonic_sort([10, -1, 3, 7, 5, 4, 6, 2], False) == [-1, 2, 3, 4, 5, 6, 7, 10]
assert bitonic_sort([], False) == []
assert bitonic_sort([1], False) == [1]
def test_bitoni... | [
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, low, cnt, reverse):",
"function_name": "bitonic_merge",
"parameter_list": "(arr, low, cnt, reverse)"
},
{
"docstring": null,
"function_declaration": "def bitonic_sort_rec(arr, low, cnt, reverse):",
"function_name": ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bitonic_sort(arr: List[int], reverse: bool = False) -> List[int]:\n def compare_and_swap(arr, i, j, direction):\n if ... | trial_gpt4o_1 | {
"original_instruction": "### Bitonic Sort Challenge\n\nYou are tasked to implement the Bitonic Sort algorithm in Python, a parallel sorting algorithm designed for sorting sequences efficiently where the sequence length is a power of 2. This algorithm constructs a bitonic sequence and recursively sorts and merges th... | 0.67244 | Data_Structure_43145 | C | [
"bitonic_merge",
"bitonic_sort_rec",
"bitonic_sort"
] | 3 | [
[
"bitonic_sort",
"bitonic_sort_rec"
],
[
"bitonic_sort_rec",
"bitonic_merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | dc18f72cdcce18d52144aa2100c97632d440413f | 48b85991fe07464db7854a6f8b679dc2c0e05863 | |||
v1.0 | complete | Data_Structure | Data_Structure_43090_C | from typing import List, Tuple
def heap_sort_kth_largest(arr: List[int], k: int) -> Tuple[List[int], int]:
""" Function that uses the Max-Heap Sort algorithm to sort an array of integers in ascending order,
and returns the sorted array along with the kth largest element in the array.
>>> heap_sort_kth_... | from typing import List, Tuple
def heapify(arr: List[int], n: int, i: int):
"""
Helper function to maintain the max-heap property.
"""
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[largest] < arr[left]:
largest = left
if right < n and arr[largest] ... | from solution import heap_sort_kth_largest
def test_heap_sort_kth_largest_case1():
arr = [3, 2, 3, 1, 2, 4, 5, 5, 6]
k = 4
sorted_arr, kth_largest = heap_sort_kth_largest(arr, k)
assert sorted_arr == [1, 2, 2, 3, 3, 4, 5, 5, 6]
assert kth_largest == 4
def test_heap_sort_kth_largest_case2():
ar... | [
{
"docstring": "Helper function to maintain the max-heap property.",
"function_declaration": "def heapify(arr, n, i):",
"function_name": "heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Function to sort the array using max-heap sort and return the sorted array \nalong with the k... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef heapify(arr: List[int], n: int, i: int):\n \"\"\"\n Helper function to maintain max heap property.\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "#### Problem Statement:\nImplement a function that uses the Max-Heap Sort algorithm to sort an array of integers in ascending order, but with a twist. You should also integrate a feature to find and return the kth largest element in the array during the sorting process.\n\n#### Detailed Req... | 0.742923 | Data_Structure_43090 | C | [
"heapify",
"heap_sort_kth_largest"
] | 2 | [
[
"heap_sort_kth_largest",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 24cd2599564b5e96a0f881ac240c9d7c2df83953 | bae8cd8f8e26f0da6340ee5c41da8c4a3abe8123 | |||
v1.0 | complete | Data_Structure | Data_Structure_43305_C | from typing import List
def optimized_bucket_sort(arr: List[int]) -> List[int]:
""" Implement bucket sort to sort a list of integers.
>>> optimized_bucket_sort([4, 3, 1, 2, 0, 5])
[0, 1, 2, 3, 4, 5]
>>> optimized_bucket_sort([4, 3])
[3, 4]
>>> optimized_bucket_sort([1, 2, 3, 4, 5, 6, 7, 8, 9, 0... | from typing import List
def insertion_sort(bucket: List[int]) -> List[int]:
for i in range(1, len(bucket)):
up = bucket[i]
j = i - 1
while j >= 0 and bucket[j] > up:
bucket[j + 1] = bucket[j]
j -= 1
bucket[j + 1] = up
return bucket
def optimized_bucket_s... | from solution import optimized_bucket_sort
def test_empty_array():
assert optimized_bucket_sort([]) == []
def test_single_element_array():
assert optimized_bucket_sort([1]) == [1]
def test_sorted_array():
assert optimized_bucket_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(bucket):",
"function_name": "insertion_sort",
"parameter_list": "(bucket)"
},
{
"docstring": null,
"function_declaration": "def optimized_bucket_sort(arr):",
"function_name": "optimized_bucket_sort",
"parameter_list... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef optimized_bucket_sort(arr: List[int]) -> List[int]:\n if len(arr) == 0:\n return arr\n\n min_value = min(arr)\n ... | trial_gpt4o_2 | {
"original_instruction": "### Bucket Sort Implementation Challenge\n\nImplement a function `optimized_bucket_sort` in Python that sorts an array of integers using the bucket sort technique. You should improve upon the given code to ensure better performance and reliability while considering edge cases and potential ... | 0.639035 | Data_Structure_43305 | C | [
"insertion_sort",
"optimized_bucket_sort"
] | 2 | [
[
"optimized_bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8cf7f08f6b929101243315fe8460670f275f2643 | c1dfe0a9fa0b732b45534b657a59b86b3ce103ce | |||
v1.0 | complete | Data_Structure | Data_Structure_42822_C | from typing import List
def pancake_sort(arr: List[int]) -> List[int]:
"""
Sorts the array using the Pancake Sort algorithm.
Args:
arr: A list of integers (0 ≤ len(arr) ≤ 100), where 0 ≤ arr[i] ≤ 10^9.
Returns:
A list of integers sorted in non-decreasing order.
Example:
... | from typing import List
def flip(arr: List[int], k: int) -> None:
"""
Reverses the order of the first k elements in the array.
"""
arr[:k] = arr[:k][::-1]
def find_max(arr: List[int], n: int) -> int:
"""
Returns the index of the maximum value in the first n elements of the array.
"""
m... | from solution import pancake_sort
def test_pancake_sort_example1():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
def test_pancake_sort_example2():
assert pancake_sort([1, 2, 3]) == [1, 2, 3]
def test_pancake_sort_example3():
assert pancake_sort([9, 3, 5, 1, 7]) == [1, 3, 5, 7, 9]
def test_pancake_s... | [
{
"docstring": "Reverses the order of the first k elements in the array.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Returns the index of the maximum value in the first n elements of the array.",
"function_declar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef pancake_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array using the Pancake Sort algorithm.\n \n Args:\n... | trial_gpt4o_2 | {
"original_instruction": "### Pancake Sort Implementation\n\nYou are provided with a partially implemented sorting algorithm called **Pancake Sort**. Your task is to complete this implementation ensuring it sorts the array correctly by repeatedly reversing sections of the array.\n\n#### Problem Description\nImplemen... | 0.774967 | Data_Structure_42822 | C | [
"flip",
"find_max",
"pancake_sort"
] | 3 | [
[
"pancake_sort",
"find_max"
],
[
"pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 12fdf24140339c829b3a8eabb8a0af5d9481af23 | 40e401ff7bb1689d3ee65098def4303b08f3fc47 | |||
v1.0 | complete | Data_Structure | Data_Structure_43173_C | def gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor (GCD) of two integers using Euclid's Algorithm.
>>> gcd(48, 18)
6
>>> gcd(0, 18)
18
>>> gcd(48, 0)
48
>>> gcd(13, 13)
13
>>> gcd(7, 3)
1
"""
def lcm(a: int, b: int) -> int:
"""
Computes ... | def gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor (GCD) of two integers using Euclid's Algorithm.
"""
while b:
a, b = b, a % b
return a
def lcm(a: int, b: int) -> int:
"""
Computes the least common multiple (LCM) of two integers using the relationship
betw... | from solution import gcd, lcm
def test_gcd():
assert gcd(48, 18) == 6
assert gcd(0, 18) == 18
assert gcd(48, 0) == 48
assert gcd(13, 13) == 13
assert gcd(7, 3) == 1
def test_lcm():
assert lcm(48, 18) == 144
assert lcm(0, 18) == 0
assert lcm(48, 0) == 0
assert lcm(13, 13) == 13
... | [
{
"docstring": "Computes the greatest common divisor (GCD) of two integers using Euclid's Algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the least common multiple (LCM) of two integers using the relationsh... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a: int, b: int) -> int:\n while b:\n a, b = b, a % b\n return a\n\ndef lcm(a: int, b: int) -> int:\n if a == 0 or b == 0:\n ret... | trial_gpt4o_2 | {
"original_instruction": "#### Background\nYou work as a software engineer at a company that develops tools for mathematical computations, and you need to implement a utility that computes the greatest common divisor (GCD) using Euclid's Algorithm and the least common multiple (LCM) of two integers. \n\nGiven two no... | 0.813773 | Data_Structure_43173 | C | [
"gcd",
"lcm"
] | 2 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a248b76671f450f631bbb0830f51749c6812f174 | 7accfb9056573bdce6efaf53abe1934b89335007 | |||
v1.0 | complete | Data_Structure | Data_Structure_42734_C | import math
from random import randint
def prime_check(num):
if num <= 1:
return False
if num == 2 or num == 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
j = 5
while j * j <= num:
if num % j == 0 or num % (j + 2) == 0:
return False
... | import math
from random import randint
def prime_check(num):
if num <= 1:
return False
if num == 2 or num == 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
j = 5
while j * j <= num:
if num % j == 0 or num % (j + 2) == 0:
return False
... | from solution import diffie_hellman_key_exchange
def test_diffie_hellman_key_exchange_valid():
# This is a simple valid test case
assert diffie_hellman_key_exchange(5, 23) == True
def test_diffie_hellman_key_exchange_non_prime():
# Test with a non-prime number
assert diffie_hellman_key_exchange(5, 24)... | [
{
"docstring": null,
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstri... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom random import randint\n\ndef prime_check(num):\n if num <= 1:\n return False\n if num == 2 or num == 3:\n return True\n ... | trial_gpt4o_2 | {
"original_instruction": "### Diffie-Hellman Key Exchange Implementation\n\nYou are to implement a secure key exchange using the Diffie-Hellman protocol. Given a large prime number \\( p \\) and its primitive root \\( a \\), write a function that simulates the key exchange process between two parties, Alice and Bob.... | 0.545804 | Data_Structure_42734 | C | [
"prime_check",
"euler_totient",
"find_order",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 5 | [
[
"diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"diffie_hellman_key_exchange",
"prime_check"
],
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"find_order"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | aee31acb8802f11f35285fb0305fe36a9f34f71e | 16bd3cead291ec681754085f1d7f85772e5e2667 | |||
v1.0 | complete | Data_Structure | Data_Structure_43221_C | from typing import List
def invert_matrix(m: List[List[float]]) -> List[List[float]]:
"""
Returns the inverse of an n x n matrix.
Special error matrices:
- Non-square matrix: [[-2]]
- Empty or 1x1 matrix: [[-3]]
- Singular matrix (determinant = 0): [[-4]]
- Not a matrix (non-uniform r... | from typing import List
def determinant(matrix: List[List[float]], n: int) -> float:
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for c in range(n):
submatrix = [[matrix[i][j] for j in range(n) if j != c]... | from solution import invert_matrix
def test_invert_2x2_matrix():
matrix = [
[4, 7],
[2, 6]
]
expected = [
[0.6, -0.7],
[-0.2, 0.4]
]
result = invert_matrix(matrix)
assert all(abs(result[i][j] - expected[i][j]) < 1e-9 for i in range(2) for j in range(2))
def test... | [
{
"docstring": null,
"function_declaration": "def determinant(matrix, n):",
"function_name": "determinant",
"parameter_list": "(matrix, n)"
},
{
"docstring": null,
"function_declaration": "def get_matrix_minor(matrix, i, j):",
"function_name": "get_matrix_minor",
"parameter_list"... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef invert_matrix(m: List[List[float]]) -> List[List[float]]:\n def transpose(matrix: List[List[float]]) -> List[List[float]]:\n... | trial_gpt4o_4 | {
"original_instruction": "### Matrix Inversion Coding Challenge\n\n#### Introduction\nMatrix inversion is a fundamental concept in linear algebra, where the goal is to find a matrix B that serves as the inverse of a given matrix A. When multiplied by A, matrix B yields the identity matrix.\n\n#### Task\nImplement a ... | 0.565399 | Data_Structure_43221 | C | [
"determinant",
"get_matrix_minor",
"invert_matrix"
] | 3 | [
[
"invert_matrix",
"determinant"
],
[
"invert_matrix",
"get_matrix_minor"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 28bbf81d07670a073992cf5369d6ff1c95e0d4e7 | 2a6ff3248677c7f17834daf5e3015d616642c8ee | |||
v1.0 | complete | Data_Structure | Data_Structure_43436_C | from typing import List
def enhanced_comb_sort(arr: List[int]) -> List[int]:
"""Enhanced Comb Sort algorithm that switches to Insertion Sort when the gap becomes less or equal to 3 for improved performance on nearly sorted lists.
Args:
arr (List[int]): List of integers to be sorted.
Returns:
... | from typing import List
def insertion_sort(arr: List[int], start: int, end: int) -> None:
for i in range(start + 1, end + 1):
key = arr[i]
j = i - 1
while j >= start and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def enhanced_comb_sort(arr: Li... | from solution import enhanced_comb_sort
def test_sorted_list():
assert enhanced_comb_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_order_list():
assert enhanced_comb_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_mixed_order_list():
assert enhanced_comb_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, start, end):",
"function_name": "insertion_sort",
"parameter_list": "(arr, start, end)"
},
{
"docstring": null,
"function_declaration": "def enhanced_comb_sort(arr):",
"function_name": "enhanced_comb_sort",
"pa... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[int], start: int, end: int) -> None:\n for i in range(start+1, end+1):\n key = arr[i]\n ... | trial_gpt4o_1 | {
"original_instruction": "Comb Sort Enhancement\n\nYou are tasked with enhancing the Comb Sort algorithm to handle large datasets more efficiently by integrating an alternative approach for smaller gaps to optimize performance. Implement a modified version of the Comb Sort algorithm that switches to Insertion Sort w... | 0.677442 | Data_Structure_43436 | C | [
"insertion_sort",
"enhanced_comb_sort"
] | 2 | [
[
"enhanced_comb_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 94501d9496d24456790f96f7f629c0a7d79aa9e2 | c92995b4c29fe4db7cc90fba17423ffd30e9b0b6 | |||
v1.0 | complete | Data_Structure | Data_Structure_43303_C | import random
from sympy import isprime, mod_inverse
def rsa_keygen_encrypt_decrypt(k: int, data: int, seed: int = None) -> dict:
""" Generate RSA keys, encrypt a number, and decrypt it using the generated keys.
Parameters:
k (int): Number of bits for modulus n.
data (int): The number to be encryp... | import random
from sympy import isprime, mod_inverse
def generate_large_prime(bits: int, seed: int = None) -> int:
if seed is not None:
random.seed(seed)
while True:
candidate = random.getrandbits(bits)
candidate |= (1 << bits - 1) | 1
if isprime(candidate):
return c... | from solution import rsa_keygen_encrypt_decrypt
def test_rsa_encrypt_decrypt_with_seed():
result = rsa_keygen_encrypt_decrypt(16, 42, seed=12345)
assert result['decrypted'] == 42
assert result['n'] > 0
assert result['e'] == 65537
assert result['d'] > 0
assert result['encrypted'] != 42
def test... | [
{
"docstring": null,
"function_declaration": "def generate_large_prime(bits, seed=None):",
"function_name": "generate_large_prime",
"parameter_list": "(bits, seed=None)"
},
{
"docstring": null,
"function_declaration": "def rsa_keygen_encrypt_decrypt(k, data, seed=None):",
"function_n... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, nextprime\nfrom math import gcd\n\ndef modinv(a, m):\n \"\"\"\n Compute the modular inverse of a under modulo ... | trial_gpt4o_2 | {
"original_instruction": "### RSA Key Generation and Encryption/Decryption\n\n#### Objective:\nWrite a Python function that generates RSA keys, encrypts, and decrypts a given message using the generated keys. Your implementation should correctly handle prime generation, modular arithmetic, and ensure valid encryptio... | 0.645346 | Data_Structure_43303 | C | [
"generate_large_prime",
"rsa_keygen_encrypt_decrypt",
"gcd"
] | 3 | [
[
"rsa_keygen_encrypt_decrypt",
"gcd"
],
[
"rsa_keygen_encrypt_decrypt",
"generate_large_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 35b92976fa6ef081d61839c414f2a608a0f6e7bf | e6fdca8101fc89802414141204d1775d7cc6dadf | |||
v1.0 | complete | Data_Structure | Data_Structure_43435_C | def lcm_bitwise(a: int, b: int) -> int:
"""
Calculate the least common multiple (LCM) of two non-negative integers using bitwise operations for the GCD calculation.
Args:
a (int): First non-negative integer.
b (int): Second non-negative integer.
Returns:
int: The LCM of a and b.
... | def gcd_bitwise(a: int, b: int) -> int:
"""
Calculate the GCD using the bitwise method.
"""
if a == 0:
return b
if b == 0:
return a
# Remove all common factors of 2 using bitwise operations
shift = 0
while ((a | b) & 1) == 0:
a >>= 1
b >>= 1
shift... | from solution import lcm_bitwise
def test_lcm_bitwise_normal_cases():
assert lcm_bitwise(12, 15) == 60
assert lcm_bitwise(7, 5) == 35
assert lcm_bitwise(21, 6) == 42
def test_lcm_bitwise_with_zero():
assert lcm_bitwise(0, 5) == 0
assert lcm_bitwise(10, 0) == 0
def test_lcm_bitwise_with_both_zero(... | [
{
"docstring": "Calculate the GCD using the bitwise method.",
"function_declaration": "def gcd_bitwise(a, b):",
"function_name": "gcd_bitwise",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate the LCM using bitwise GCD calculation.",
"function_declaration": "def lcm_bitwise(a, b):... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd_bitwise(a: int, b: int) -> int:\n \"\"\"\n Calculate the GCD using the bitwise method.\n \"\"\"\n if a == 0:\n return b\n if b =... | trial_gpt4o_0 | {
"original_instruction": "### Task\nWrite a function `lcm_bitwise(a: int, b: int) -> int` that calculates the least common multiple (LCM) of two non-negative integers using bitwise operations for the GCD calculation. The function should handle edge cases and invalid inputs appropriately.\n\n### Input\n- Two non-nega... | 0.676744 | Data_Structure_43435 | C | [
"gcd_bitwise",
"lcm_bitwise"
] | 2 | [
[
"lcm_bitwise",
"gcd_bitwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c3f0316e659a78a29b9093280d2f9b17188690b8 | 15a2ffe6d96bf75f7a2140c3f4511ea49ec70e37 | |||
v1.0 | complete | Data_Structure | Data_Structure_43334_C | from typing import List
def is_prime(n: int) -> bool:
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
retur... | from typing import List
def is_prime(n: int) -> bool:
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
retur... | from solution import range_prime_check
def test_range_prime_check_simple_range():
assert range_prime_check(10, 20) == [11, 13, 17, 19]
def test_range_prime_check_no_primes():
assert range_prime_check(14, 16) == []
def test_range_prime_check_single_prime():
assert range_prime_check(23, 23) == [23]
def te... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers between `start` and `end` (inclusive).",
"function_declaration": "def range_prime_check(st... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Checks if a number is a prime number.\n \"\"\"\n if n <= 1:\n return Fa... | trial_gpt4o_2 | {
"original_instruction": "Enhanced Primality Check Function\n\n#### Background\nAs part of a cybersecurity module, you are to implement a function that verifies the primality of a number and further extends the functionality by checking a range of numbers. Given the importance of prime numbers in encryption algorith... | 0.745137 | Data_Structure_43334 | C | [
"is_prime",
"range_prime_check"
] | 2 | [
[
"range_prime_check",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 23defca0152597a0a85914687508ec595a047b13 | a9dc2cfe91325ff43a625d9b0705ed1941a0cf2e | |||
v1.0 | complete | Data_Structure | Data_Structure_43573_C | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if the array is sorted.
"""
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def bogo_sort(arr: List[int], simulation: bool = False) -> List[int]:
"""
Sorts the array using Bogo S... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if the array is sorted.
"""
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def bogo_sort(arr: List[int], simulation: bool = False) -> List[int]:
"""
Sorts the array using Bogo S... | from solution import bogo_sort
def test_bogo_sort_empty_array():
assert bogo_sort([]) == []
def test_bogo_sort_already_sorted():
assert bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_bogo_sort_identical_elements():
assert bogo_sort([2, 2, 2]) == [2, 2, 2]
def test_bogo_sort_unsorted_array():
... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the array using Bogo Sort.\n\nArgs:\n- arr (List[int]): The array of integers to sort.\n- simulat... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to check if the array is sorted.\n \"\"\"... | trial_gpt4o_0 | {
"original_instruction": "### Programming Challenge: Bogo Sort Simulation with Edge Case Handling\n\n#### Context\nBogo Sort is a highly inefficient sorting algorithm that randomly shuffles the given array until it gets sorted. Although impractical, Bogo Sort is an interesting concept to demonstrate the implications... | 0.644299 | Data_Structure_43573 | C | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0615d13bc6a6393095a1084c52e77a87e185c016 | f42ce652887ded959cba26f5748ffa9a1b658d4b | |||
v1.0 | complete | Data_Structure | Data_Structure_43001_C | from typing import List, Tuple
def max_flow(V: int, edges: List[Tuple[int, int, int]], source: int, sink: int) -> int:
"""Calculate the maximum flow from the source to the sink in a transportation network.
Args:
V (int): Number of vertices (junctions) in the graph.
edges (List[Tuple[int, int, int]... | from collections import deque, defaultdict
def bfs(source, sink, parent, capacity_graph):
visited = set()
queue = deque([source])
visited.add(source)
while queue:
current = queue.popleft()
for neighbor, capacity in capacity_graph[current].items():
if neighbor n... | from solution import max_flow
def test_max_flow_example_case():
V = 4
edges = [(0, 1, 100), (0, 2, 100), (1, 2, 1), (1, 3, 100), (2, 3, 100)]
source = 0
sink = 3
assert max_flow(V, edges, source, sink) == 200
def test_max_flow_no_flow():
V = 4
edges = [(0, 1, 100), (2, 3, 100)]
source ... | [
{
"docstring": null,
"function_declaration": "def bfs(source, sink, parent, capacity_graph):",
"function_name": "bfs",
"parameter_list": "(source, sink, parent, capacity_graph)"
},
{
"docstring": null,
"function_declaration": "def max_flow(V, edges, source, sink):",
"function_name": ... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(C, F, source, sink, parent):\n visited = [False] * len(C)\n queue = deque([source])\n visited[source] = True... | trial_gpt4o_2 | {
"original_instruction": "### Max Flow in a Transport Network\n\nYou are working as a traffic engineer, and you need to determine the maximum flow of vehicles from a starting location to a destination in a transportation network, which is modeled as a directed graph. Each node represents a junction, and each directe... | 0.543954 | Data_Structure_43001 | C | [
"bfs",
"max_flow"
] | 2 | [
[
"max_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 60d35383701a1a2b0657ba8c0bf796ea4c889fa8 | 18026c7e60fce03ef22da6a4f0961e29e18a10dd | |||
v1.0 | complete | Data_Structure | Data_Structure_43384_C | def search_insert(array, val):
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def insert_sorted_score(scores, new_score):
"""
Inserts a new score in... | def search_insert(array, val):
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def insert_sorted_score(scores, new_score):
position = search_insert(score... | from solution import insert_sorted_score
def test_insert_sorted_score_middle():
scores = [55, 78, 89, 92]
new_score = 85
assert insert_sorted_score(scores, new_score) == [55, 78, 85, 89, 92]
def test_insert_sorted_score_start():
scores = [55, 78, 89, 92]
new_score = 50
assert insert_sorted_sco... | [
{
"docstring": null,
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": null,
"function_declaration": "def insert_sorted_score(scores, new_score):",
"function_name": "insert_sorted_score",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(array, val):\n low = 0\n high = len(array) - 1\n while low <= high:\n mid = low + (high - low) // 2\n if val > array[... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nYou are maintaining a list of scores for a game that must always be sorted in ascending order. Players constantly obtain new scores, and you need to efficiently insert each new score into the sorted list.\n\n### Problem Statement\nWrite a function `insert_sorted_score(scores, ... | 0.56074 | Data_Structure_43384 | C | [
"search_insert",
"insert_sorted_score"
] | 2 | [
[
"insert_sorted_score",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8f0d67f4da61c99725f230bf4c69e4a8af9b5617 | 64d839bd3d062c1d8873ee21bd71414b8e263ae8 | |||
v1.0 | complete | Data_Structure | Data_Structure_43748_C | from functools import reduce
from math import gcd
def list_lcm(nums: List[int]) -> int:
"""
Given a list of positive integers, computes the least common multiple (LCM) of all the integers in the list.
Parameters:
nums (List[int]): A list of positive integers
Returns:
int: The LCM of the l... | from math import gcd
from functools import reduce
def lcm(x, y):
"""
Computes the Least Common Multiple (LCM) of two positive integers.
"""
return x * y // gcd(x, y)
def list_lcm(nums):
"""
Given a list of positive integers, computes the least common multiple (LCM) of all the integers in the l... | from solution import list_lcm
def test_list_lcm_two_numbers():
assert list_lcm([4, 6]) == 12
def test_list_lcm_multiple_numbers():
assert list_lcm([2, 7, 3, 9, 4]) == 252
def test_list_lcm_with_one():
assert list_lcm([1, 4, 5, 6]) == 60
def test_list_lcm_large_numbers():
assert list_lcm([1000000, 99... | [
{
"docstring": "Computes the Least Common Multiple (LCM) of two positive integers.",
"function_declaration": "def lcm(x, y):",
"function_name": "lcm",
"parameter_list": "(x, y)"
},
{
"docstring": "Given a list of positive integers, computes the least common multiple (LCM) of all the integers... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import gcd\nfrom functools import reduce\n\ndef list_lcm(nums):\n \"\"\"\n Given a list of positive integers, computes the least common multip... | trial_gpt4o_2 | {
"original_instruction": "You are provided with functions to compute the GCD using both Euclid's Algorithm and bitwise operations, compute the LCM, and find the number of trailing zeroes in the binary representation of an integer. Based on these functions, implement a function to determine the least common multiple ... | 0.669657 | Data_Structure_43748 | C | [
"lcm",
"list_lcm"
] | 2 | [
[
"list_lcm",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f1d673ac4d4edd3e0f321aafa93ea59f28b5d533 | bd17c86768b602656017786652bec1cd0673f451 | |||
v1.0 | complete | Data_Structure | Data_Structure_43503_C | def count_primes_in_range(a: int, b: int) -> int:
"""
Returns the number of prime numbers between a and b (inclusive).
Parameters:
a (int): The start of the range, inclusive.
b (int): The end of the range, inclusive.
Returns:
int: The count of prime numbers within the specified range.
... | import math
def is_prime(n):
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
... | from solution import count_primes_in_range
def test_primes_in_small_range():
assert count_primes_in_range(10, 20) == 4 # Primes are: 11, 13, 17, 19
def test_primes_in_range_starting_from_zero():
assert count_primes_in_range(0, 10) == 4 # Primes are: 2, 3, 5, 7
def test_no_primes_in_single_number_range():
... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the number of prime numbers between a and b (inclusive).",
"function_declaration": "def count_primes_in_range(a, b):",... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_primes_in_range(a: int, b: int) -> int:\n \"\"\"\n Returns the number of prime numbers between a and b (inclusive).\n \n Using the Sieve... | trial_gpt4o_1 | {
"original_instruction": "**Title**: Optimized Prime Counting in a Range\n\n**Objective**: Write a function that counts the number of prime numbers in a given range `[a, b]`.\n\n**Function Signature**:\n```python\ndef count_primes_in_range(a: int, b: int) -> int:\n \"\"\"\n Returns the number of prime numbers ... | 0.720757 | Data_Structure_43503 | C | [
"is_prime",
"count_primes_in_range"
] | 2 | [
[
"count_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b6f0915e3f7c3a6b32c9cd3d566931e36e082781 | 6a0ab202cd8c90d548cc75550f333d70ba953a44 | |||
v1.0 | complete | Data_Structure | Data_Structure_42927_C | from typing import List
def bitonic_sort(arr: List[int], up: bool) -> List[int]:
"""
Helper function to sort an array using the bitonic sort.
If `up` is True, the array is sorted in ascending order.
If `up` is False, the array is sorted in descending order.
"""
def compare_and_swap(arr: List[in... | from typing import List
def bitonic_sort(arr: List[int], up: bool) -> List[int]:
"""
Helper function to sort an array using the bitonic sort.
If `up` is True, the array is sorted in ascending order.
If `up` is False, the array is sorted in descending order.
"""
def compare_and_swap(arr: List[in... | import pytest
from solution import kth_largest_element
def test_kth_largest_element_example():
arr = [3, 2, 1, 5, 6, 4]
k = 2
assert kth_largest_element(arr, k) == 5
def test_kth_largest_element_smallest():
arr = [1, 2]
k = 1
assert kth_largest_element(arr, k) == 2
def test_kth_largest_elemen... | [
{
"docstring": "Helper function to sort an array using the bitonic sort.\nIf `up` is True, the array is sorted in ascending order.\nIf `up` is False, the array is sorted in descending order.",
"function_declaration": "def bitonic_sort(arr, up):",
"function_name": "bitonic_sort",
"parameter_list": "(... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bitonic_sort(arr, up=True):\n \"\"\" Helper function to perform bitonic sort on the array \"\"\"\n def bitonic_merge(arr,... | trial_gpt4o_1 | {
"original_instruction": "### Question: Implement a Function to Find the Kth Largest Element Using Bitonic Sort\n\nYou are given an array of integers whose length is guaranteed to be a power of two and a positive integer `k`. Your task is to find the `k`th largest element in the array using the bitonic sort algorith... | 0.667897 | Data_Structure_42927 | C | [
"bitonic_sort",
"kth_largest_element"
] | 2 | [
[
"kth_largest_element",
"bitonic_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e3386acd692786814401afa7dc878faaa07b1f1c | 6ade7e2cfd26625b74743d61eb1227a1312eeaa6 | |||
v1.0 | complete | Data_Structure | Data_Structure_43440_C | def get_bit(num, i):
""" Return the i-th bit of the given number.
"""
pass
def set_bit(num, i):
""" Set the i-th bit of the given number to 1.
"""
pass
def clear_bit(num, i):
""" Clear the i-th bit of the given number.
"""
pass
def update_bit(num, i, bit):
""" Update the i-th ... | def get_bit(num, i):
return (num & (1 << i)) != 0
def set_bit(num, i):
return num | (1 << i)
def clear_bit(num, i):
mask = ~(1 << i)
return num & mask
def update_bit(num, i, bit):
mask = ~(1 << i)
return (num & mask) | (bit << i)
def bit_manipulator(nums, operations):
for operation in op... | def test_get_bit():
assert get_bit(5, 0) == True
assert get_bit(5, 1) == False
assert get_bit(5, 2) == True
def test_set_bit():
assert set_bit(5, 1) == 7
assert set_bit(5, 3) == 13
assert set_bit(0, 0) == 1
def test_clear_bit():
assert clear_bit(7, 0) == 6
assert clear_bit(7, 1) == 5
... | [
{
"docstring": null,
"function_declaration": "def get_bit(num, i):",
"function_name": "get_bit",
"parameter_list": "(num, i)"
},
{
"docstring": null,
"function_declaration": "def set_bit(num, i):",
"function_name": "set_bit",
"parameter_list": "(num, i)"
},
{
"docstring":... | [
0,
0,
0,
1,
1,
1,
1,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Provided helper functions\ndef get_bit(num, i):\n return (num & (1 << i)) != 0\n\ndef set_bit(num, i):\n return num | (1 << i)\n\ndef clear_bit(num, i... | trial_gpt4o_4 | {
"original_instruction": "Bit Manipulator\n\nYou have been given a series of functions that allow you to manipulate individual bits of an integer. Your task is to implement a function that uses these bit manipulation functions to perform complex bit-wise operations on a list of integers.\n\n#### Function Specificati... | 0.659529 | Data_Structure_43440 | C | [
"get_bit",
"set_bit",
"clear_bit",
"update_bit",
"bit_manipulator"
] | 5 | [
[
"bit_manipulator",
"clear_bit"
],
[
"bit_manipulator",
"set_bit"
],
[
"bit_manipulator",
"update_bit"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 6b33ea203d3dd7921f7a4fd9572b9ec09c98b90f | fea6e34efc0daa9c01217674758e5b145e6fd5a7 | |||
v1.0 | complete | Data_Structure | Data_Structure_43226_C | from typing import List
def maximum_flow_bfs(adjacency_matrix: List[List[int]]) -> int:
""" Calculate the maximum possible flow from the source server
(node 0) to the sink server (the last node) in a flow network
represented by an adjacency matrix.
Input:
- adjacency_matrix: A 2D list where ... | from typing import List
def bfs(graph: List[List[int]], s: int, t: int, parent: List[int]) -> bool:
visited = [False] * len(graph)
queue = []
queue.append(s)
visited[s] = True
while queue:
u = queue.pop(0)
for ind, val in enumerate(graph[u]):
if visited[ind... | from solution import maximum_flow_bfs
def test_maximum_flow_bfs_example():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow_bfs(graph) == 23
def test_... | [
{
"docstring": null,
"function_declaration": "def bfs(graph, s, t, parent):",
"function_name": "bfs",
"parameter_list": "(graph, s, t, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(adjacency_matrix):",
"function_name": "maximum_flow_bfs",
"paramet... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bfs(rGraph, s, t, parent):\n visited = [False] * len(rGraph)\n queue = []\n queue.append(s)\n visited[s] = True\n ... | trial_gpt4o_1 | {
"original_instruction": "### Maximum Flow Network Problem with Hidden Nodes\n\nYou are tasked with designing a flow network where each node represents a server, and each edge represents a direct connection between two servers with specific bandwidth limits. Given an adjacency matrix of a flow network where `graph[i... | 0.620791 | Data_Structure_43226 | C | [
"bfs",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 30fb3369ef22028c9e2b74201a70354dd856707f | af259c698248dc667fe119ec76fd1d9e8f9fad31 | |||
v1.0 | complete | Data_Structure | Data_Structure_44442_C | from typing import List
def merge(arr: List[int], l: int, m: int, r: int):
""" Helper function to merge two halves in an iterative merge sort.
"""
pass
def iterative_merge_sort(arr: List[int]) -> List[int]:
""" Implement an iterative version of the merge sort algorithm.
>>> iterative_merge_sort([3... | from typing import List
def merge(arr: List[int], l: int, m: int, r: int):
n1 = m - l + 1
n2 = r - m
# Create temporary arrays
L = arr[l:m+1]
R = arr[m+1:r+1]
i = 0
j = 0
k = l
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i +... | from solution import iterative_merge_sort
def test_iterative_merge_sort():
assert iterative_merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
assert iterative_merge_sort([1]) == [1]
assert iterative_merge_sort([]) == []
assert iterative_merge_sort([10, -1, 2, 5, 0]) == [-1, 0, 2, 5, ... | [
{
"docstring": null,
"function_declaration": "def merge(arr, l, m, r):",
"function_name": "merge",
"parameter_list": "(arr, l, m, r)"
},
{
"docstring": null,
"function_declaration": "def iterative_merge_sort(arr):",
"function_name": "iterative_merge_sort",
"parameter_list": "(arr... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge(arr, temp_arr, left, mid, right):\n i = left # Starting index for left subarray\n j = mid + 1 # Starting index for right subarray\n k = ... | trial_gpt4o_2 | {
"original_instruction": "### Coding Challenge: Implement Iterative Merge Sort\n\n#### Problem Statement:\nImplement an iterative version of the merge sort algorithm. The iterative approach uses a bottom-up methodology (non-recursive) to sort an array. This will help save space compared to the recursive method.\n\n#... | 0.596815 | Data_Structure_44442 | C | [
"merge",
"iterative_merge_sort"
] | 2 | [
[
"iterative_merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d91dcaf9214e426bae70a936af53f7b38bcea6f4 | a5d742fc6720ca68a4ae16573413de1fb313bea8 | |||
v1.0 | complete | Data_Structure | Data_Structure_44262_C | def is_prime(n: int) -> bool:
""" Returns True if n is a prime number, False otherwise.
>>> is_prime(5)
True
>>> is_prime(15)
False
"""
pass
def list_primes_up_to(m: int) -> list:
""" Returns a list of all prime numbers from 2 to m.
>>> list_primes_up_to(10)
[2, 3, 5, 7]
>>>... | def is_prime(n):
"""
Returns True if n is a prime number, False otherwise.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import is_prime, list_primes_up_to
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(10) == False
assert is_prime(11) == True
assert is_prime(1) == False
assert is_prime(0) == F... | [
{
"docstring": "Returns True if n is a prime number, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers from 2 to m.",
"function_declaration": "def list_primes_up_to(m)... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_prime(n):\n \"\"\"\n Returns True if n is a prime number, otherwise returns False.\n \"\"\"\n if n <= 1:\n return Fal... | trial_gpt4o_1 | {
"original_instruction": "### Description\n\nYou are implementing a system that needs to efficiently check if numbers are prime as part of its operation. Your task is to write a function that determines whether a given number is prime. Additionally, you will write a utility function to list all prime numbers up to a... | 0.780924 | Data_Structure_44262 | C | [
"is_prime",
"list_primes_up_to"
] | 2 | [
[
"list_primes_up_to",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 242c47694d3be155f23ac53eb9279ccdadf56988 | ecc08c89869f1cbb4b2532781989430f3fb736f7 | |||
v1.0 | complete | Data_Structure | Data_Structure_43912_C | from typing import List
def shortest_distance(grid: List[List[int]]) -> int:
""" Determine the shortest distance from all buildings to an empty plot.
If it's impossible for an empty plot to be reached by all buildings, return -1.
:param grid: 2D list of lists, where each element is 0, 1, or 2
:re... | import collections
from typing import List
def bfs(grid, start_x, start_y, distance, reach, buildings):
rows, cols = len(grid), len(grid[0])
queue = collections.deque([(start_x, start_y, 0)])
visited = set([(start_x, start_y)])
while queue:
x, y, dist = queue.popleft()
for... | from solution import shortest_distance
def test_example_case():
grid = [
[1, 0, 2, 0, 1],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0]
]
assert shortest_distance(grid) == 7
def test_no_empty_plot():
grid = [
[1, 2, 1],
[2, 2, 2],
[1, 2, 1]
]
assert shortest_... | [
{
"docstring": null,
"function_declaration": "def bfs(grid, start_x, start_y, distance, reach, buildings):",
"function_name": "bfs",
"parameter_list": "(grid, start_x, start_y, distance, reach, buildings)"
},
{
"docstring": null,
"function_declaration": "def shortest_distance(grid):",
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List\n\ndef shortest_distance(grid: List[List[int]]) -> int:\n if not grid or not grid[0]:\n retur... | trial_gpt4o_2 | {
"original_instruction": "#### Background\n\nYou are working on an urban planning project, and you need to assess the connectivity of one part of the city grid. The city is represented as a 2D grid where:\n- '1' denotes buildings,\n- '0' denotes empty plots,\n- '2' denotes obstacles.\n\nYour task is to determine the... | 0.610861 | Data_Structure_43912 | C | [
"bfs",
"shortest_distance"
] | 2 | [
[
"shortest_distance",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bda0efbf98dae44d3ab6cdafba6927d65fc1c89e | 11dcae4f0347ac914f716d53906454eea40f70bb | |||
v1.0 | complete | Data_Structure | Data_Structure_44516_C | from typing import List
def find_magic_numbers(numbers: List[int]) -> List[int]:
"""
Accepts a list of integers and returns a list of all magic numbers from the input list.
A magic number is defined as a number for which the sum of its digits is recursively summed until a single-digit number
is obtain... | def is_magic_number(n):
"""
Helper function to determine if a number is a magic number.
"""
while n >= 10:
n = sum(int(digit) for digit in str(n))
return n == 1
def find_magic_numbers(numbers):
"""
Returns a list of magic numbers from the given list.
"""
return [number for n... | from solution import find_magic_numbers
def test_find_magic_numbers_all_magic():
assert find_magic_numbers([50113, 1234, 199]) == [50113, 1234, 199]
def test_find_magic_numbers_some_magic():
assert find_magic_numbers([50113, 1234, 199, 111, 45]) == [50113, 1234, 199]
def test_find_magic_numbers_no_magic():
... | [
{
"docstring": "Helper function to determine if a number is a magic number.",
"function_declaration": "def is_magic_number(n):",
"function_name": "is_magic_number",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of magic numbers from the given list.",
"function_declaration": "... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_magic_numbers(numbers):\n \"\"\"\n Determine which numbers in the given list are magic numbers.\n \n A number is a magic number if the su... | trial_gpt4o_8 | {
"original_instruction": "#### Problem Context\n\nIn certain ancient cultures, number properties were often used for determining luck or prophecy. One such property is the concept of a \"Magic Number\".\n\nA number is said to be a magic number if summing the digits of the number and then recursively repeating this p... | 0.613801 | Data_Structure_44516 | C | [
"is_magic_number",
"find_magic_numbers"
] | 2 | [
[
"find_magic_numbers",
"is_magic_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d411412634dcebf29196ea69cf1fee14d729a7a6 | 760af24f26f225cbca2ceb72d86c512145b1716e | |||
v1.0 | complete | Data_Structure | Data_Structure_44194_C | from typing import List, Tuple, Optional
def get_bit(num: int, bit_index: int) -> int:
"""
Get the value of the bit at the specified index.
"""
pass
def set_bit(num: int, bit_index: int) -> int:
"""
Set the bit at the specified index to 1.
"""
pass
def clear_bit(num: int, bit_index: i... | from typing import List, Tuple, Optional
def get_bit(num: int, bit_index: int) -> int:
"""
Get the value of the bit at the specified index.
"""
return (num >> bit_index) & 1
def set_bit(num: int, bit_index: int) -> int:
"""
Set the bit at the specified index to 1.
"""
return num | (1 <... | from solution import bit_manipulation
def test_bit_manipulation():
start_num = 0b0101 # 5 in decimal
operations = [
('set', 1), # Set bit at index 1: Result -> 0b0111 (7 in decimal)
('clear', 2), # Clear bit at index 2: Result -> 0b0011 (3 in decimal)
('update', 0, 1) # Update ... | [
{
"docstring": "Get the value of the bit at the specified index.",
"function_declaration": "def get_bit(num, bit_index):",
"function_name": "get_bit",
"parameter_list": "(num, bit_index)"
},
{
"docstring": "Set the bit at the specified index to 1.",
"function_declaration": "def set_bit(n... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple, Optional\n\ndef get_bit(num: int, bit_index: int) -> int:\n \"\"\"Returns the value of the bit at the given index.\"\"\"\n ... | trial_gpt4o_1 | {
"original_instruction": "### Problem Description\nYou are given a series of operations that manipulate specific bits within a given integer. Your task is to implement a function that will process a list of these operations and return the final modified integer.\n\n### Function Signature\n```python\ndef bit_manipula... | 0.698053 | Data_Structure_44194 | C | [
"get_bit",
"set_bit",
"clear_bit",
"update_bit",
"bit_manipulation"
] | 5 | [
[
"bit_manipulation",
"clear_bit"
],
[
"bit_manipulation",
"get_bit"
],
[
"bit_manipulation",
"set_bit"
],
[
"bit_manipulation",
"update_bit"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 17b670cd20e3c1bf619f98e6ab8decb9555c32bd | 95fb3c4c2d2726925df1d7441eb0bc6d4d6fa4af | |||
v1.0 | complete | Data_Structure | Data_Structure_43765_C | from typing import List, Dict, Optional
import random
def predict_next_word(chain: Dict[str, Dict[str, float]], current_word: str) -> Optional[str]:
""" Predict the next word based on the given Markov Chain and the current word.
Args:
chain (dict): A dictionary representing the Markov Chain.
current_wo... | import random
def predict_next_word(chain, current_word):
"""
Predict the next word based on the given Markov Chain and the current word.
Args:
chain (dict): A dictionary representing the Markov Chain.
current_word (str): The current word whose next word needs to be predicted.
Returns... | from solution import predict_next_word, generate_sentence
def test_predict_next_word():
chain = {
'hello': {'world': 0.5, 'there': 0.5},
'world': {'hello': 1.0},
'there': {'world': 1.0}
}
assert predict_next_word(chain, 'hello') in ['world', 'there']
assert predict_next_wor... | [
{
"docstring": "Predict the next word based on the given Markov Chain and the current word.\n\nArgs:\nchain (dict): A dictionary representing the Markov Chain.\ncurrent_word (str): The current word whose next word needs to be predicted.\n\nReturns:\nstr: The next word based on the transition probabilities. Retu... | [
0,
0,
0,
1,
0,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef predict_next_word(chain, current_word):\n \"\"\"\n Given a word transition dictionary (Markov Chain) and the current word,\n thi... | trial_gpt4o_3 | {
"original_instruction": "### Context\nImagine you're building a predictive text engine that uses a Markov Chain to suggest the next word in a sentence. The engine has to generate the next word based on the current word, considering the probability distribution of possible subsequent words. You need to implement the... | 0.629938 | Data_Structure_43765 | C | [
"predict_next_word",
"generate_sentence"
] | 2 | [
[
"generate_sentence",
"predict_next_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8bdc3ff315521dfcc20eb220d153dfa5367d70fa | 2fe90f4a356537558d54f76cb1d477d424ff719c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.