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_33533_C | from typing import List
def search_insert(array: List[int], target: int) -> int:
"""
A helper function that performs binary search to find the target or the insertion index.
"""
left, right = 0, len(array) - 1
while left <= right:
mid = (left + right) // 2
if array[mid] == target:
... | from typing import List
def search_insert(array: List[int], target: int) -> int:
"""
A helper function that performs binary search to find the target or the insertion index.
"""
left, right = 0, len(array) - 1
while left <= right:
mid = (left + right) // 2
if array[mid] == target:
... | from solution import insert_and_search
def test_insert_and_search():
assert insert_and_search([3, 5, 7, 9], 6, 8) == 4
assert insert_and_search([1, 3, 5, 6], 5, 2) == 1
assert insert_and_search([1, 3, 5, 6], 7, 7) == 4
assert insert_and_search([1, 2, 4, 5, 6], 3, 5) == 4
assert insert_and_search([]... | [
{
"docstring": "A helper function that performs binary search to find the target or the insertion index.",
"function_declaration": "def search_insert(array, target):",
"function_name": "search_insert",
"parameter_list": "(array, target)"
},
{
"docstring": "Inserts a new value into the sorted... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], target: int) -> int:\n \"\"\"\n This helper function performs binary search on the array ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Extended Insertion Search Using Binary Search\n\nUsing the given binary search helper function, `search_insert`, write a function `insert_and_search` that first ensures the array is sorted, inserts a new value into the array in the correct position, and then searches for anoth... | 0.591651 | Data_Structure_33533 | C | [
"search_insert",
"insert_and_search"
] | 2 | [
[
"insert_and_search",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fb3fd97f4404d72bd5df542ba752c8d9a8228d01 | 2e69319ebeb4db0a0dc02e17223078358f615f45 | |||
v1.0 | complete | Data_Structure | Data_Structure_33105_C | def miller_rabin_is_prime(n, k=5):
"""
Implement the Miller-Rabin primality test to check if n is a prime number.
:param n: integer, the number to test.
:param k: integer, number of iterations for accuracy.
:return: boolean, True if n is probably prime, False if n is composite.
"""
pass
def... | import random
def miller_rabin_is_prime(n, k=5):
"""
Implement the Miller-Rabin primality test to check if n is a prime number.
:param n: integer, the number to test.
:param k: integer, number of iterations for accuracy.
:return: boolean, True if n is probably prime, False if n is composite.
""... | from solution import (
miller_rabin_is_prime,
extended_gcd,
modinv,
generate_key,
encrypt,
decrypt
)
def test_miller_rabin_is_prime():
assert miller_rabin_is_prime(2) is True
assert miller_rabin_is_prime(3) is True
assert miller_rabin_is_prime(11) is True
assert miller_rabin_is_... | [
{
"docstring": "Implement the Miller-Rabin primality test to check if n is a prime number.\n:param n: integer, the number to test.\n:param k: integer, number of iterations for accuracy.\n:return: boolean, True if n is probably prime, False if n is composite.",
"function_declaration": "def miller_rabin_is_pr... | [
0,
0,
0,
0,
0,
0,
1,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef miller_rabin_is_prime(n, k=5):\n \"\"\"\n Implement the Miller-Rabin primality test to check if n is a prime number.\n :param n:... | trial_gpt4o_6 | {
"original_instruction": "### RSA Encryption and Decryption Using Improved Key Generation\nYou have been given snippets implementing RSA key generation, encryption, and decryption functions. In the current form, the code uses a simplified method for generating primes and computing the modular inverse, which can be i... | 0.640625 | Data_Structure_33105 | C | [
"miller_rabin_is_prime",
"extended_gcd",
"modinv",
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt"
] | 8 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_key",
"modinv"
],
[
"generate_prime_number",
"generate_prime_candidate"
],
[
"generate_prime_number",
"miller_rabin_is_prime"
],
[
"modinv",
"extended_gcd"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 029f85f9c06649e69b747f9adac59aa081dc4aca | e8e674b4cb5dc408cee04dae86fced8ab127fe99 | |||
v1.0 | complete | Data_Structure | Data_Structure_33172_C | def radix_sort(arr, simulation=False):
"""
Implement the Radix Sort algorithm and optionally print the
intermediate steps of sorting arrays.
Given an array of non-negative integers, sort the array in ascending order.
If `simulation` is set to True, print the intermediate steps.
Args:
... | def counting_sort(arr, exp, simulation=False, iteration=0):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
if simulation:
print(f"Count array at iteration {iteration} for exp {exp}: {count}")
for i in ra... | from solution import radix_sort
def test_sort_regular_array():
arr = [170, 45, 75, 90, 802, 24, 2, 66]
result = radix_sort(arr)
assert result == [2, 24, 45, 66, 75, 90, 170, 802]
def test_sort_single_element_array():
arr = [5]
result = radix_sort(arr)
assert result == [5]
def test_sort_empty_... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation=False, iteration=0):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation=False, iteration=0)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=Fals... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp, simulation=False, iteration=0):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n for i in range(n):\n i... | trial_gpt4o_0 | {
"original_instruction": "You are tasked with implementing the Radix Sort algorithm. Your implementation should allow for an optional simulation mode that prints the intermediate steps of sorting arrays. Given an array of non-negative integers, sort the array in ascending order.\n\n### Function Signature\n```python\... | 0.663971 | Data_Structure_33172 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bdcc9fadc782e78885ae4d8920f42aa397a43b67 | c2e96436cd76afa23b5063b672ed3ddbfb01682c | |||
v1.0 | complete | Data_Structure | Data_Structure_33793_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
""" Implement a Recursive Merge Sort to sort an array of integers.
>>> merge_sort([38, 27, 43, 3, 9, 82, 10])
[3, 9, 10, 27, 38, 43, 82]
>>> merge_sort([])
[]
>>> merge_sort([1])
[1]
>>> merge_sort([1, 2, 3, 4, 5])
... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left: List[int], right: List[int]) -> List[int]:
sorted_array = []
... | from solution import merge_sort
def test_merge_sort_basic():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_already_sorted():
... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n def merge(left: List[int], right: Li... | trial_gpt4o_2 | {
"original_instruction": "Implement a Recursive Merge Sort\n\n#### Objective:\nImplement a Merge Sort algorithm to sort an array of integers, showcasing your understanding of divide-and-conquer strategies, recursive function implementation, and array manipulation.\n\n#### Description:\n\nWrite a function `merge_sort... | 0.614213 | Data_Structure_33793 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a1d1efdab918b1bef45b53458b3b45a776b37648 | 5cda5f023c778e79e8d91d4bc7974e891fd765b0 | |||
v1.0 | complete | Data_Structure | Data_Structure_33380_C | from typing import List, Tuple, Dict, Optional
def solve_sat(formula: List[Tuple[Tuple[str, bool], Tuple[str, bool]]]) -> Optional[Dict[str, bool]]:
""" Solve the 2-Satisfiability (2-SAT) problem using Strongly Connected Components (SCC).
Args:
formula (List[Tuple[Tuple[str, bool], Tuple[str, bool... | def add_edge(graph, vertex_from, vertex_to):
if vertex_from not in graph:
graph[vertex_from] = []
graph[vertex_from].append(vertex_to)
def build_graph(formula):
graph = {}
for (u, v) in formula:
u_name, u_sign = u
v_name, v_sign = v
add_edge(graph, (u_name, not u_sign), ... | def test_solve_sat_possible():
formula = [
(('x', False), ('y', False)),
(('y', True), ('y', True)),
(('a', False), ('b', False)),
(('a', True), ('c', True)),
(('c', False), ('b', True))
]
result = solve_sat(formula)
assert result is not None
assert result['x'... | [
{
"docstring": null,
"function_declaration": "def add_edge(graph, vertex_from, vertex_to):",
"function_name": "add_edge",
"parameter_list": "(graph, vertex_from, vertex_to)"
},
{
"docstring": null,
"function_declaration": "def build_graph(formula):",
"function_name": "build_graph",
... | [
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 add_edge(graph, vertex_from, vertex_to):\n if vertex_from not in graph:\n graph[vertex_from] = []\n graph[vertex_from].append(vertex_to)\n\nd... | trial_gpt4o_0 | {
"original_instruction": "### Question\nYou are tasked with implementing an algorithm to solve the 2-Satisfiability (2-SAT) problem using the concept of Strongly Connected Components (SCC). Given a formula in conjunctive normal form (2-CNF), your program should find a way to assign True/False values to all variables... | 0.478239 | Data_Structure_33380 | C | [
"add_edge",
"build_graph",
"dfs",
"dfs_transposed",
"scc",
"solve_sat"
] | 6 | [
[
"build_graph",
"add_edge"
],
[
"scc",
"add_edge"
],
[
"scc",
"dfs"
],
[
"scc",
"dfs_transposed"
],
[
"solve_sat",
"build_graph"
],
[
"solve_sat",
"scc"
]
] | 6 | [] | false | [] | false | pytest | false | [] | true | b90d346af98f684ee1e3c80a807dc11954ce2387 | 7a7a856a1a1fa2b34cd153977200e0af039e8c0b | |||
v1.0 | complete | Data_Structure | Data_Structure_33661_C | def sum_array_bitwise(arr: list) -> int:
""" Return the sum of all integers in the array using bitwise operations.
>>> sum_array_bitwise([1, 2, 3, 4, 5])
15
>>> sum_array_bitwise([0, 1, 2, 3, 4, 5])
15
>>> sum_array_bitwise([1000000000, 2000000000, 3000000000])
6000000000
"""
Unit Test... | def bitwise_add(a, b):
"""
Helper function to add two integers using bitwise operations.
"""
while b != 0:
carry = a & b
a = a ^ b
b = carry << 1
return a
def sum_array_bitwise(arr):
"""
Returns the sum of the elements in array `arr` using bitwise operations.
"""... | from solution import sum_array_bitwise
def test_sum_single_element():
assert sum_array_bitwise([5]) == 5
def test_sum_two_elements():
assert sum_array_bitwise([1, 2]) == 3
def test_sum_multiple_elements():
assert sum_array_bitwise([1, 2, 3, 4, 5]) == 15
def test_sum_with_zero():
assert sum_array... | [
{
"docstring": "Helper function to add two integers using bitwise operations.",
"function_declaration": "def bitwise_add(a, b):",
"function_name": "bitwise_add",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the sum of the elements in array `arr` using bitwise operations.",
"func... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add_bitwise(a, b):\n \"\"\"\n Helper function that adds two numbers using bitwise operations.\n \"\"\"\n while b != 0:\n carry = a & b\... | trial_gpt4o_2 | {
"original_instruction": "### Question: Bitwise Array Sum\n\n#### Context\nYou are working on a low-level system programming task where you need to perform additions without using the arithmetic '+' operator. Let's extend this need to an array of numbers instead of just two integers.\n\n#### Task\nWrite a function `... | 0.55699 | Data_Structure_33661 | C | [
"bitwise_add",
"sum_array_bitwise"
] | 2 | [
[
"sum_array_bitwise",
"bitwise_add"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3ed4bafc1043239c8b3384d2653041966fd9fe28 | c3418e38c67c85e93245521c0eba4ecfdfd0e0ae | |||
v1.0 | complete | Data_Structure | Data_Structure_33780_C | from typing import List
def transform_matrix(matrix: List[List[int]], commands: List[str]) -> List[List[int]]:
""" Perform a chain of transformations on the given matrix as specified by the command list.
Valid commands are:
- "rotate_clockwise": Rotate the matrix 90 degrees clockwise.
- "rotate_counte... | from typing import List
def rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:
n = len(matrix)
return [[matrix[n - j - 1][i] for j in range(n)] for i in range(n)]
def rotate_counterclockwise(matrix: List[List[int]]) -> List[List[int]]:
n = len(matrix)
return [[matrix[j][n - i - 1] for j in ... | from solution import transform_matrix
def test_rotate_clockwise():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
commands = ["rotate_clockwise"]
expected = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
assert transform_matrix(matrix, commands) == expected
d... | [
{
"docstring": null,
"function_declaration": "def rotate_clockwise(matrix):",
"function_name": "rotate_clockwise",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def rotate_counterclockwise(matrix):",
"function_name": "rotate_counterclockwise",
"par... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:\n return [list(row) for row in zip(*matrix[::-1])]\n\ndef rota... | trial_gpt4o_2 | {
"original_instruction": "#### Scenario\nYou've been provided a set of matrix transformation functions which include rotating and inverting the matrix. Your goal is to implement a new function that performs a chain of these transformations efficiently as specified by a command list.\n\n#### Problem\nWrite a function... | 0.538526 | Data_Structure_33780 | C | [
"rotate_clockwise",
"rotate_counterclockwise",
"top_left_invert",
"bottom_left_invert",
"transform_matrix"
] | 5 | [
[
"transform_matrix",
"bottom_left_invert"
],
[
"transform_matrix",
"rotate_clockwise"
],
[
"transform_matrix",
"rotate_counterclockwise"
],
[
"transform_matrix",
"top_left_invert"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 29d9a49e53d93395c642c02a56464623953543c4 | 410554dbb1a657f730f7838e4d67aa5cdd9ef504 | |||
v1.0 | complete | Data_Structure | Data_Structure_33910_C | def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
"""
Extended Euclidean Algorithm.
It returns a tuple (g, x, y) such that g = gcd(a, b) and a*x + b*y = g
"""
pass
def find_modular_inverse(e: int, phi_n: int) -> int:
"""Returns the modular inverse 'd' of 'e' modulo 'phi_n'.
>>... | def extended_gcd(a, b):
""" Extended Euclidean Algorithm.
It returns a tuple (g, x, y) such that g = gcd(a, b) and a*x + b*y = g
"""
if b == 0:
return a, 1, 0
g, x1, y1 = extended_gcd(b, a % b)
x = y1
y = x1 - (a // b) * y1
return g, x, y
def find_modular_inverse(e, phi_... | from solution import find_modular_inverse
def test_find_modular_inverse_example1():
e = 3
phi_n = 26
d = find_modular_inverse(e, phi_n)
assert (d * e) % phi_n == 1
assert 1 < d < phi_n
def test_find_modular_inverse_example2():
e = 17
phi_n = 3120
d = find_modular_inverse(e, phi_n)
... | [
{
"docstring": "Extended Euclidean Algorithm.\nIt returns a tuple (g, x, y) such that g = gcd(a, b) and a*x + b*y = g",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the modular inverse 'd' of 'e' mod... | [
0,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_modular_inverse(e: int, phi_n: int) -> int:\n def extended_gcd(a, b):\n if b == 0:\n return a, 1, 0\n gcd, x1, y1 = exten... | trial_gpt4o_6 | {
"original_instruction": "We have discussed the Extended Euclidean Algorithm and how it can be used to find the modular inverse of a number. Now it's time to implement this to solve a real-world problem in cryptography. \n\n#### Problem Statement\n\nAlice wants to encrypt a message using the RSA algorithm. For this,... | 0.622046 | Data_Structure_33910 | C | [
"extended_gcd",
"find_modular_inverse"
] | 2 | [
[
"find_modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4c941c46aa7d9d763f031bc7c9823354cb3987a8 | 8246b6925a9313c28d8e63317f8f9057c8474574 | |||
v1.0 | complete | Data_Structure | Data_Structure_33434_C | def enhanced_quick_sort(arr):
""" Sort an array using an enhanced Quick Sort with optimized pivot selection.
>>> enhanced_quick_sort([34, 7, 23, 32, 5, 62])
[5, 7, 23, 32, 34, 62]
>>> enhanced_quick_sort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>> enhanced_quick_sort([])
[]
>>> enhanced_qu... | def insertion_sort(arr, left, right):
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def median_of_three(arr, low, high):
mid = (low + high) // 2
if arr[low] > ... | from solution import enhanced_quick_sort
def test_enhanced_quick_sort_example():
arr = [34, 7, 23, 32, 5, 62]
sorted_arr = [5, 7, 23, 32, 34, 62]
assert enhanced_quick_sort(arr) == sorted_arr
def test_enhanced_quick_sort_empty():
arr = []
assert enhanced_quick_sort(arr) == []
def test_enhanced_qu... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def median_of_three(arr, low, high):\n mid = (low + high) // 2\n if arr[low] > arr[mid]:\n arr[low], arr[mid] = arr[mid], arr[low]\n if arr[lo... | trial_gpt4o_2 | {
"original_instruction": "### Question: Enhanced Quick Sort Implementation\n\n**Context:**\n\nYou are hired by a tech company to improve the performance of their flagship sorting library. One of the popular methods in this library is Quick Sort. The current implementation has some performance issues with large and s... | 0.563809 | Data_Structure_33434 | C | [
"insertion_sort",
"median_of_three",
"partition",
"quick_sort",
"enhanced_quick_sort"
] | 5 | [
[
"enhanced_quick_sort",
"quick_sort"
],
[
"partition",
"median_of_three"
],
[
"quick_sort",
"insertion_sort"
],
[
"quick_sort",
"partition"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | b88540dfa8cd56f912522208aabad06332fad217 | 7f20b6ef196370d9cafa7ef87b306f77f8c9b684 | |||
v1.0 | complete | Data_Structure | Data_Structure_33932_C | def gcd_advanced(a, b):
"""
Computes the greatest common divisor of a and b using bitwise operations.
>>> gcd_advanced(48, 18) # Output: 6
>>> gcd_advanced(0, 5) # Output: 5
>>> gcd_advanced(7, 0) # Output: 7
>>> gcd_advanced(0, 0) # Output: 0 # Assuming we return 0 for gcd(0, 0)
... | def gcd_advanced(a, b):
"""
Computes the greatest common divisor of a and b using bitwise operations.
"""
if a == 0:
return b
if b == 0:
return a
# Find the greatest power of 2 that divides both a and b
shift = 0
while ((a | b) & 1) == 0:
a >>= 1
b >>= 1
... | from solution import gcd_advanced, lcm_advanced
def test_gcd_advanced():
assert gcd_advanced(48, 18) == 6
assert gcd_advanced(0, 5) == 5
assert gcd_advanced(7, 0) == 7
assert gcd_advanced(24, 36) == 12
assert gcd_advanced(101, 103) == 1
def test_gcd_advanced_edge_cases():
assert gcd_advanced(0... | [
{
"docstring": "Computes the greatest common divisor of a and b using bitwise operations.",
"function_declaration": "def gcd_advanced(a, b):",
"function_name": "gcd_advanced",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the least common multiple of a and b using the gcd_advanced f... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd_advanced(a, b):\n \"\"\"\n Computes the GCD of a and b using bitwise operations.\n \"\"\"\n if a == 0: return b\n if b == 0: return a\n... | trial_gpt4o_1 | {
"original_instruction": "### Question: Advanced GCD Calculation\n\nYou are given two non-negative integers `a` and `b`. Your task is to implement two functions:\n1. `gcd_advanced(a, b)`: This function should compute the greatest common divisor (GCD) of `a` and `b` using the bitwise operations strategy, incorporatin... | 0.770726 | Data_Structure_33932 | C | [
"gcd_advanced",
"lcm_advanced"
] | 2 | [
[
"lcm_advanced",
"gcd_advanced"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 06172a58bdca4698bb80da3f9b13e681a96b8274 | 2a0c46e7a5a0cd37ddb1bfb82559cc8911d5209f | |||
v1.0 | complete | Data_Structure | Data_Structure_33937_C | def prime_check(n: int) -> bool:
"""
Check if a number is prime or not.
Parameters:
n (int): The number to check if prime
Returns:
bool: True if n is a prime number, False otherwise.
"""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 =... | def prime_check(n):
"""
Check if a number is prime or not.
Parameters:
n (int): The number to check if prime
Returns:
bool: True if n is a prime number, False otherwise.
"""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 ... | from solution import prime_sum
def test_prime_sum_case1():
assert prime_sum(10, 20) == 60 # Primes are 11, 13, 17, 19
def test_prime_sum_case2():
assert prime_sum(1, 10) == 17 # Primes are 2, 3, 5, 7
def test_prime_sum_case3():
assert prime_sum(20, 20) == 0 # There are no primes
def test_prime_sum_si... | [
{
"docstring": "Check if a number is prime or not.\n\nParameters:\nn (int): The number to check if prime\n\nReturns:\nbool: True if n is a prime number, False otherwise.",
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring":... | [
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 prime_check(n):\n \"\"\"\n Check if the number 'n' is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ret... | trial_gpt4o_2 | {
"original_instruction": "### Prime Validator Function\n\nGiven the code snippet for checking if a number is prime, we want to extend its functionality. Write a function `prime_sum(start, end)` that calculates the sum of all prime numbers within a given inclusive range [start, end].\n\n#### Input\n* An integer `star... | 0.75529 | Data_Structure_33937 | C | [
"prime_check",
"prime_sum"
] | 2 | [
[
"prime_sum",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 628aceda78a9d15839d59dc3b0184f37f1ed5775 | 81a8f656834c4962e0e160bc004a1bfa189bda6d | |||
v1.0 | complete | Data_Structure | Data_Structure_33869_C | from typing import List
def optimized_radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
"""
Implement and Optimize Radix Sort.
This function sorts a list of non-negative integers using an optimized version
of Radix Sort and returns the sorted list. If the 'simulation' parameter ... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool) -> None:
n = len(arr)
output = [0] * n # output array that will have sorted arr
count = [0] * 10 # count array to store count of occurrences of digits
# Store count of occurrences in count[]
for i in range(n):
... | def test_sorted_sequence():
assert optimized_radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sequence():
assert optimized_radix_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_mixed_sequence():
assert optimized_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170,... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
},
{
"docstring": null,
"function_declaration": "def optimized_radix_sort(arr, simulation=False):",
"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 counting_sort(arr: List[int], exp: int, simulation: bool) -> None:\n n = len(arr)\n output = [0] * n # output array that... | trial_gpt4o_0 | {
"original_instruction": "Implement and Optimize Radix Sort\n\nYou are tasked with implementing an optimized version of Radix Sort. Given an input list of non-negative integers, your goal is to sort the list efficiently. You are required to demonstrate a good grasp of the Radix Sort algorithm, handling various edge ... | 0.653998 | Data_Structure_33869 | C | [
"counting_sort",
"optimized_radix_sort"
] | 2 | [
[
"optimized_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | a7049cf74ebed1e1434ce92c663e345969621252 | c88cbc7f197931f9e20c7c1c760db4d65adad7a7 | |||
v1.0 | complete | Data_Structure | Data_Structure_33284_C | ### Scenario
You have been given two heap-sort implementations: one that utilizes a max heap and another that utilizes a min heap. Both have been designed to sort arrays in ascending order. Unfortunately, there is a requirement change, and now you need to enhance these functions to handle descending order sorting.
###... | def max_heapify(arr, n, i, simulation=False):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[i] < arr[left]:
largest = left
if right < n and arr[largest] < arr[right]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
... | from solution import max_heap_sort_descending, min_heap_sort_descending
def test_max_heap_sort_descending_basic():
arr = [4, 10, 3, 5, 1]
sorted_arr = max_heap_sort_descending(arr.copy())
assert sorted_arr == [10, 5, 4, 3, 1]
def test_max_heap_sort_descending_with_negatives():
arr = [2, -1, 3, 7, 3, 5... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, simulation=False):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def max_heap_sort_descending(arr, simulation=False):",
"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 max_heapify(arr, n, i, simulation=False):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n and arr[i] < arr[left]:\n ... | trial_gpt4o_1 | {
"original_instruction": "### Scenario\nYou have been given two heap-sort implementations: one that utilizes a max heap and another that utilizes a min heap. Both have been designed to sort arrays in ascending order. Unfortunately, there is a requirement change, and now you need to enhance these functions to handle ... | 0.636845 | Data_Structure_33284 | C | [
"max_heapify",
"max_heap_sort_descending",
"min_heapify",
"min_heap_sort_descending"
] | 4 | [
[
"max_heap_sort_descending",
"max_heapify"
],
[
"min_heap_sort_descending",
"min_heapify"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 556edbd24cc9cae0776a55fb65a56815ba4b35c0 | 89e766a2f5f42c0fc4130d48ced5e40b64d03e0b | |||
v1.0 | complete | Data_Structure | Data_Structure_34123_C | import math
from typing import Tuple, Dict
def distance(x: Tuple[float], y: Tuple[float]) -> float:
"""
Calculate the Euclidean distance between vectors x and y.
Arguments:
x, y: Tuple of numeric values
Returns:
float: The Euclidean distance between the two vectors
"""
assert ... | import math
def distance(x, y):
"""
Calculate the Euclidean distance between vectors x and y.
"""
assert len(x) == len(y), "The vectors must have the same length"
return math.sqrt(sum((a - b) ** 2 for a, b in zip(x, y)))
def nearest_neighbor(x, tSet):
"""
Classify a new data point x by fin... | from solution import nearest_neighbor
def test_nearest_neighbor_single_entry():
tSet = {
(2.0, 3.0): 'Class_A'
}
assert nearest_neighbor((1.0, 2.0), tSet) == 'Class_A'
def test_nearest_neighbor_multiple_entries():
tSet = {
(2.0, 3.0): 'Class_A',
(1.0, 2.0): 'Class_B',
(... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(x, y):\n \"\"\"\n Calculate the Euclidean distance between vectors x and y.\n\n Arguments:\n x, y: Tuple of numeri... | trial_gpt4o_2 | {
"original_instruction": "### Nearest Neighbor Classification Challenge\n\n#### Background\nIn pattern recognition, a simple yet powerful algorithm is the Nearest Neighbor algorithm. Given a set of training data, where each data point is a vector assigned to a class or label, the algorithm determines the class of a ... | 0.640048 | Data_Structure_34123 | C | [
"distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f111e1aa04ac5946c9e64e6a7b062812f3e98d02 | c253c3b558fa4dec7ee0f280ff1f0d671dc8b7f6 | |||
v1.0 | complete | Data_Structure | Data_Structure_33920_C | def secure_key_exchange(p: int, a: int) -> bool:
"""
Perform a secure Diffie-Hellman key exchange.
Parameters:
- p: A large prime number.
- a: A primitive root of `p`.
Returns:
- True if the key exchange is successful and both keys match.
- False if any validation fails or keys... | import random
def is_prime(n):
"""Check if a number is a prime number."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
... | from solution import secure_key_exchange
def test_basic_case():
assert secure_key_exchange(23, 5) == True
def test_wrong_prime():
assert secure_key_exchange(15, 5) == False # 15 is not a prime number
def test_wrong_primitive_root():
assert secure_key_exchange(23, 10) == False # 10 is not a primitive ro... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find the smallest primitive root of a prime number p.",
"function_declaration": "def primitive_root(p):",
"functi... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(n):\n \"\"\"Check if a number is a prime number.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return ... | trial_gpt4o_0 | {
"original_instruction": "**Scenario**:\nAlice and Bob work in a company that needs to securely exchange sensitive data. They decide to use Diffie-Hellman Key Exchange to generate a shared secret key. You need to help implement the system that will allow them to safely generate and exchange this key.\n\n**Task**:\nW... | 0.516359 | Data_Structure_33920 | C | [
"is_prime",
"primitive_root",
"gcd",
"secure_key_exchange"
] | 4 | [
[
"primitive_root",
"gcd"
],
[
"primitive_root",
"is_prime"
],
[
"secure_key_exchange",
"is_prime"
],
[
"secure_key_exchange",
"primitive_root"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 06ab2a1847a58c5936a6a09536c5b148040c5a51 | 3f4a9ff3c03991dc6bd201d455feccd38d3f3174 | |||
v1.0 | complete | Data_Structure | Data_Structure_34212_C | def compute_modular_inverse(a: int, m: int) -> int:
""" Computes the modular inverse of `a` modulo `m`.
Returns -1 if the modular inverse does not exist.
>>> compute_modular_inverse(3, 11) == 4
>>> compute_modular_inverse(10, 20) == -1
>>> compute_modular_inverse(123456789, 1000000007) == 18633540
... | def extended_gcd(a, b):
"""
Extended Euclidean Algorithm to find the coefficients x and y such that:
ax + by = gcd(a, b)
"""
if a == 0:
return b, 0, 1
gcd, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y
def compute_modular_inverse(a: int, m: i... | from solution import compute_modular_inverse
def test_inverse_exists():
assert compute_modular_inverse(3, 11) == 4 # Explanation: 3 * 4 = 12, 12 % 11 = 1
assert compute_modular_inverse(7, 26) == 15 # Explanation: 7 * 15 = 105, 105 % 26 = 1
def test_inverse_not_exists():
assert compute_modular_inverse(10... | [
{
"docstring": "Extended Euclidean Algorithm to find the coefficients x and y such that:\nax + by = gcd(a, b)",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the modular inverse of `a` modulo `m` usi... | [
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 extended_gcd(a, b):\n \"\"\"\n Extended Euclidean Algorithm to find the coefficients x and y such that:\n ax + by = gcd(a, b)\n \"\"\"\n if... | trial_gpt4o_0 | {
"original_instruction": "### Scenario\nA digital signature algorithm requires the use of modular inverses to secure data. Given integers \\( a \\) and \\( m \\), you need to compute the modular inverse of \\( a \\) modulo \\( m \\). If the modular inverse doesn't exist (i.e., \\( a \\) and \\( m \\) are not coprime... | 0.665997 | Data_Structure_34212 | C | [
"extended_gcd",
"compute_modular_inverse"
] | 2 | [
[
"compute_modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 522eae068170666d980d3cbc187d24d1193abb50 | 09052e9816c0b0bb7359dc13306e9f3d8a539668 | |||
v1.0 | complete | Data_Structure | Data_Structure_34387_C | def diffie_hellman_key_exchange(a: int, p: int) -> bool:
"""
Alice and Bob want to securely share a secret key over a public network using Diffie-Hellman key exchange.
They agree on a large prime number p and its primitive root a. This function demonstrates this key exchange
and ensures both parties co... | def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i ** 2 <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def gcd(a, b):
while b:
a, b = b,... | from solution import diffie_hellman_key_exchange
def test_diffie_hellman_valid():
assert diffie_hellman_key_exchange(5, 23) == True
def test_non_prime_p():
assert diffie_hellman_key_exchange(5, 20) == False
def test_invalid_primitive_root():
assert diffie_hellman_key_exchange(4, 23) == False
def test_sm... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5... | trial_gpt4o_0 | {
"original_instruction": "### Diffie-Hellman Key Exchange Exercise\n\nAlice and Bob want to securely share a secret key over a public network using Diffie-Hellman key exchange. They agree on a large prime number \\(p\\) and its primitive root \\(a\\). Your task is to implement a Python function that demonstrates thi... | 0.51045 | Data_Structure_34387 | C | [
"is_prime",
"gcd",
"is_primitive_root",
"mod_exp",
"diffie_hellman_key_exchange"
] | 5 | [
[
"diffie_hellman_key_exchange",
"is_prime"
],
[
"diffie_hellman_key_exchange",
"is_primitive_root"
],
[
"diffie_hellman_key_exchange",
"mod_exp"
],
[
"is_primitive_root",
"gcd"
],
[
"is_primitive_root",
"is_prime"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 1e566c4a2be182d0c2c5f51c59d34d4a015c090c | e5a97db3a4784cd3927e04b5b32627962593d298 | |||
v1.0 | complete | Data_Structure | Data_Structure_33419_C | def power(a: int, n: int, mod: int = None) -> int:
""" Efficiently computes a^n using a binary exponentiation algorithm.
This function calculates the power using either an iterative or
recursive approach and supports optional modulus operation:
1. Iterative version of binary exponentiation.
2. Rec... | def power_iter(a: int, n: int, mod: int = None) -> int:
"""
Efficiently computes a^n using an iterative version of binary exponentiation.
If mod is specified, returns a^n % mod.
Args:
- a (int): The base integer.
- n (int): The exponent integer.
- mod (int, optional): The modulus intege... | from solution import power, power_recur
def test_power_base_case():
assert power(2, 0) == 1
assert power(2, 1) == 2
assert power(0, 0) == 1
def test_power_no_mod():
assert power(2, 10) == 1024
assert power(3, 5) == 243
assert power(7, 3) == 343
def test_power_with_mod():
assert power(2, 1... | [
{
"docstring": "Efficiently computes a^n using an iterative version of binary exponentiation.\nIf mod is specified, returns a^n % mod.\n\nArgs:\n- a (int): The base integer.\n- n (int): The exponent integer.\n- mod (int, optional): The modulus integer. Default is None.\n\nReturns:\n- int: The result of the expo... | [
0,
0,
0,
0,
1,
1,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def power_iterative(a: int, n: int, mod: int = None) -> int:\n \"\"\"\n Iteratively computes a^n using binary exponentiation.\n \n Parameters:\n ... | trial_gpt4o_8 | {
"original_instruction": "You've been tasked with implementing a secure numerical computation system as part of a broader cryptographic module. One fundamental operation you need to implement is efficient exponentiation, given the frequent need to perform power calculations with high exponents and potentially large ... | 0.662048 | Data_Structure_33419 | C | [
"power_iter",
"power_recur",
"power"
] | 3 | [
[
"power",
"power_iter"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d0dea4d3d85729d608de7ff1f6e0ddeb86212a31 | 686956bd56b1f1d75fd15944e49fcdd1973d5683 | |||
v1.0 | complete | Data_Structure | Data_Structure_34113_C | def radix_sort(arr: List[int]) -> List[int]:
""" You are required to implement a sorting function that sorts an array of integers using the Radix Sort algorithm. Additionally, your function should be able to handle some potential edge cases and ensure stability during sorting.
>>> radix_sort([170, 45, 75, 90, ... | from typing import List
def counting_sort(arr: List[int], exp: int) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
for i in range(n - 1, -1, -... | from solution import radix_sort
def test_radix_sort_example():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802], "Error in test case example"
def test_radix_sort_all_same():
assert radix_sort([3, 3, 3, 3]) == [3, 3, 3, 3], "Error in test case with all same elements"
d... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef radix_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of integers using the Radix Sort algorithm.\n \"\"\"\... | trial_gpt4o_2 | {
"original_instruction": "You are required to implement a sorting function that sorts an array of integers using the Radix Sort algorithm. Additionally, your function should be able to handle some potential edge cases and ensure stability during sorting.\n\n### Function Signature\n\n```python\ndef radix_sort(arr: Li... | 0.684495 | Data_Structure_34113 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 439dc5dedd9d15e6dd4189c98741529f82809b78 | b27f836313ec85282a9837acb76d1ad3fb44196a | |||
v1.0 | complete | Data_Structure | Data_Structure_34159_C | from typing import List
def minimum_repeats(song_list: List[str], target_sequence: List[str]) -> int:
""" Returns the minimum number of times the song_list needs to be repeated
so that the target_sequence appears as a subgroup in the repeated list.
If no such repetition can achieve this, return -1.
... | def minimum_repeats(song_list, target_sequence):
"""
Returns the minimum number of times the song_list needs to be repeated
so that the target_sequence appears as a subgroup in the repeated list.
If no such repetition can achieve this, return -1.
"""
n = len(song_list)
m = len(target_se... | def test_minimum_repeats_example():
assert minimum_repeats(["hello", "world"], ["world", "hello", "world"]) == 2
def test_minimum_repeats_no_repeats_needed():
assert minimum_repeats(["a", "b", "c"], ["b", "c"]) == 1
def test_minimum_repeats_needs_repeating():
assert minimum_repeats(["a", "b"], ["b", "a", ... | [
{
"docstring": "Returns the minimum number of times the song_list needs to be repeated\nso that the target_sequence appears as a subgroup in the repeated list.\n\nIf no such repetition can achieve this, return -1.",
"function_declaration": "def minimum_repeats(song_list, target_sequence):",
"function_na... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimum_repeats(song_list, target_sequence):\n \"\"\"\n Returns the minimum number of repetitions of song_list\n such that target_sequence is a s... | trial_gpt4o_1 | {
"original_instruction": "#### Scenario\nYou are tasked with automating a pattern recognition system for a playlist application. Your system needs to identify repeated patterns within a list of song titles. Specifically, you need a function that determines how many times a given list of song titles needs to be repea... | 0.540309 | Data_Structure_34159 | C | [
"minimum_repeats",
"list_contains_sublist"
] | 2 | [
[
"minimum_repeats",
"list_contains_sublist"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | b65d6b0e546959aae4cecd4df6b9ae36d198ebbe | 624ec87b991d73947f92147dbf0d39ec89785729 | |||
v1.0 | complete | Data_Structure | Data_Structure_34015_C | def matrix_power(mat: list, p: int) -> list:
"""Calculate the power of a matrix using repeated squaring.
Args:
mat (list): The square matrix to be raised to a power.
p (int): The power to which the matrix is to be raised.
Returns:
list: The resultant matrix after exponentiation.
... | def multiply(mat1, mat2):
"""
Multiplies two matrices mat1 and mat2.
"""
n = len(mat1)
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] += mat1[i][k] * mat2[k][j]
return result
def identity(n):
... | from solution import matrix_power, determinant
def test_matrix_power():
mat1 = [
[1, 2],
[3, 4]
]
assert matrix_power(mat1, 2) == [[7, 10], [15, 22]]
mat2 = [
[2, 0],
[0, 2]
]
assert matrix_power(mat2, 3) == [[8, 0], [0, 8]]
mat3 = [
[5]
... | [
{
"docstring": "Multiplies two matrices mat1 and mat2.",
"function_declaration": "def multiply(mat1, mat2):",
"function_name": "multiply",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": "Returns an identity matrix of size n.",
"function_declaration": "def identity(n):",
"function... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def identity(size):\n \"\"\"\n Creates an identity matrix of given size\n \"\"\"\n return [[1 if i == j else 0 for j in range(size)] for i in rang... | trial_gpt4o_1 | {
"original_instruction": "### Question: Implement Matrix Operations\nYou are required to implement two key operations involving matrices: matrix exponentiation and determinant calculation. The provided implementations for matrix multiplication and identity matrix may be useful.\n\n#### Task 1: Matrix Exponentiation\... | 0.462357 | Data_Structure_34015 | C | [
"multiply",
"identity",
"matrix_power",
"determinant"
] | 4 | [
[
"matrix_power",
"identity"
],
[
"matrix_power",
"multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 161ca343f42065186553bb30b1efc6da095b53e8 | 89c14d063f89fe701b1b4f50a29e56a0a095778e | |||
v1.0 | complete | Data_Structure | Data_Structure_33861_C | def min_heap_sort(arr, simulation=False):
""" Heap Sort that uses a min heap to sort an array in ascending order.
Args:
- arr (List[int]): The list of integers to be sorted.
- simulation (bool): If True, print the array at each iteration.
Returns:
- List[int]: Sorted list of integers... | def min_heap_sort(arr, simulation=False):
""" Heap Sort that uses a min heap to sort an array in ascending order.
Args:
- arr (List[int]): The list of integers to be sorted.
- simulation (bool): If True, print the array at each iteration.
Returns:
- List[int]: Sorted list of integers... | from solution import min_heap_sort
def test_min_heap_sort_empty():
assert min_heap_sort([]) == []
def test_min_heap_sort_single_element():
assert min_heap_sort([1]) == [1]
def test_min_heap_sort_sorted():
assert min_heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_min_heap_sort_reverse_sorted():
... | [
{
"docstring": "Heap Sort that uses a min heap to sort an array in ascending order.\nArgs:\n - arr (List[int]): The list of integers to be sorted.\n - simulation (bool): If True, print the array at each iteration.\nReturns:\n - List[int]: Sorted list of integers.",
"function_declaration": "def min_... | [
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 min_heap_sort(arr, simulation=False):\n \"\"\"\n Heap Sort that uses a min heap to sort an array in ascending order.\n \n Args:\n - arr... | trial_gpt4o_2 | {
"original_instruction": "Heap Sort is a well-known sorting algorithm that can be implemented using either a max heap or a min heap. Based on the provided explanation and analysis, your task is to complete the implementation of the `min_heap_sort` function to sort an array in ascending order using a min heap. \n\nCo... | 0.704115 | Data_Structure_33861 | C | [
"min_heap_sort",
"heapify"
] | 2 | [
[
"min_heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 86885b38a27164912b6f1ea641764b3299cd91e9 | f195e5536289355861ee272f1407580c69cdcc36 | |||
v1.0 | complete | Data_Structure | Data_Structure_34267_C | from typing import List
def binary_insertion_sort(array: List[int]) -> List[int]:
""" Sort the provided array using binary insertion sort algorithm.
>>> binary_insertion_sort([12, 11, 13, 5, 6]) [5, 6, 11, 12, 13]
>>> binary_insertion_sort([]) []
>>> binary_insertion_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, ... | from typing import List
def binary_search_insert_position(array: List[int], left: int, right: int, key: int) -> int:
"""
Perform binary search to find the correct insertion point for the key in the subarray array[left:right+1].
"""
while left <= right:
mid = left + (right - left) // 2
i... | from solution import binary_insertion_sort
def test_binary_insertion_sort_example_case():
assert binary_insertion_sort([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13]
def test_binary_insertion_sort_empty():
assert binary_insertion_sort([]) == []
def test_binary_insertion_sort_sorted():
assert binary_insertion_... | [
{
"docstring": "Perform binary search to find the correct insertion point for the key in the subarray array[left:right+1].",
"function_declaration": "def binary_search_insert_position(array, left, right, key):",
"function_name": "binary_search_insert_position",
"parameter_list": "(array, left, right... | [
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\nimport bisect\n\ndef binary_insertion_sort(array: List[int]) -> List[int]:\n \"\"\"\n Sort the array using binary insertion sor... | trial_gpt4o_2 | {
"original_instruction": "Your task is to implement the insertion sort algorithm using a helper function that uses binary search to determine the correct insertion point for the next element in the partially sorted array. This will help minimize comparisons needed to find the correct position of the element.\n\n**Fu... | 0.71161 | Data_Structure_34267 | C | [
"binary_search_insert_position",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"binary_search_insert_position"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5bc8924b6740440e6e00938c952229c92d8b1145 | d465e1477e3d17925b77555a57d67f65ddede34c | |||
v1.0 | complete | Data_Structure | Data_Structure_33986_C | def merge_sort(arr):
"""
Sorts an array of integers using the Merge Sort algorithm.
Parameters:
arr (list): A list of integers to be sorted.
Returns:
list: A new list of integers, sorted in ascending order.
>>> merge_sort([34, 7, 23, 32, 5, 62])
[5, 7, 23, 32, 34, 62]
... | def merge_sort(arr):
"""
Sorts an array of integers using the Merge Sort algorithm.
Parameters:
arr (list): A list of integers to be sorted.
Returns:
list: A new list of integers, sorted in ascending order.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
l... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_array():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_array():
assert me... | [
{
"docstring": "Sorts an array of integers using the Merge Sort algorithm.\n\nParameters:\narr (list): A list of integers to be sorted.\n\nReturns:\nlist: A new list of integers, sorted in ascending order.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_li... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array of integers using the Merge Sort algorithm.\n \n Parameters:\n arr (list): A list of integers to... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement a More Efficient Sorting Algorithm\n\nYou have seen an example of the Bogo Sort algorithm, a highly inefficient sorting method. Your task is to demonstrate your understanding of sorting algorithms by implementing a more efficient algorithm: Merge Sort.\n\nMerge Sort ... | 0.649243 | Data_Structure_33986 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 553e2dc22ba4bf692db62a70537b48e8b99a3cb0 | ff3835b35d15e51f8d950e640a303e6b5653ea34 | |||
v1.0 | complete | Data_Structure | Data_Structure_34284_C | import random
def secure_diffie_hellman_key_exchange(a: int, p: int) -> bool:
""" Perform secure Diffie-Hellman key exchange.
This function validates if p is a prime number, verifies if a is a primitive root modulo p,
generates private and public keys for Alice and Bob, and computes the shared secret key.
... | from sympy.ntheory import isprime, totient
from random import randint
def find_primitive_root(p):
if not isprime(p):
return -1
phi = p - 1
primitive_roots = []
for a in range(1, p):
is_primitive_root = True
for q in set(factorize(phi)):
if pow(a, phi // q, p) ==... | def test_secure_diffie_hellman_key_exchange_valid_key():
assert secure_diffie_hellman_key_exchange(5, 23) == True
def test_secure_diffie_hellman_key_exchange_not_primitive_root():
assert secure_diffie_hellman_key_exchange(2, 23) == False # 2 is not a primitive root mod 23
def test_secure_diffie_hellman_key_e... | [
{
"docstring": null,
"function_declaration": "def find_primitive_root(p):",
"function_name": "find_primitive_root",
"parameter_list": "(p)"
},
{
"docstring": "Returns a list of prime factors of the given number `n` ",
"function_declaration": "def factorize(n):",
"function_name": "fac... | [
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, totient\n\ndef is_primitive_root(a, p):\n if not isprime(p):\n return False\n \n required_set = set(... | trial_gpt4o_2 | {
"original_instruction": "### Context\nAlice and Bob want to communicate securely using the Diffie-Hellman key exchange algorithm. They must ensure their exchange is protected by using a large prime number and its primitive root. The key exchange will involve both parties keeping their private keys secret while shar... | 0.537484 | Data_Structure_34284 | C | [
"find_primitive_root",
"factorize",
"secure_diffie_hellman_key_exchange"
] | 3 | [
[
"find_primitive_root",
"factorize"
],
[
"secure_diffie_hellman_key_exchange",
"find_primitive_root"
]
] | 2 | [] | false | [] | false | pytest | false | [
"sympy"
] | false | bfa619c989276413f3ad050a88c540e0ca16eba5 | 3f3cf13dbb2b4cb7acda15fb753645ff38c9ce10 | |||
v1.0 | complete | Data_Structure | Data_Structure_34019_C | from typing import List
def optimized_stoogesort(arr: List[int], l: int, h: int) -> List[int]:
"""
Sort an array using the Stooge Sort algorithm, optimized to check for already sorted subarrays to avoid unnecessary recursive calls.
:param arr: List of integers to be sorted
:param l: Starting inde... | from typing import List
def is_sorted(arr: List[int], l: int, h: int) -> bool:
for i in range(l, h):
if arr[i] > arr[i + 1]:
return False
return True
def optimized_stoogesort(arr: List[int], l: int, h: int) -> List[int]:
# Base case: if the subarray has one or no elements, it's already... | from solution import optimized_stoogesort
def test_empty_array():
assert optimized_stoogesort([], 0, -1) == []
def test_single_element_array():
arr = [1]
assert optimized_stoogesort(arr, 0, 0) == [1]
def test_sorted_array():
arr = [1, 2, 3, 4, 5]
assert optimized_stoogesort(arr, 0, 4) == [1, 2, 3... | [
{
"docstring": null,
"function_declaration": "def is_sorted(arr, l, h):",
"function_name": "is_sorted",
"parameter_list": "(arr, l, h)"
},
{
"docstring": null,
"function_declaration": "def optimized_stoogesort(arr, l, h):",
"function_name": "optimized_stoogesort",
"parameter_list... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef optimized_stoogesort(arr: List[int], l: int, h: int) -> List[int]:\n \"\"\"\n Sorts the subarray arr[l:h+1] using the opt... | trial_gpt4o_1 | {
"original_instruction": "### Sorting Algorithm Challenge: Stooge Sort Enhancement\n\n**Context**: \nYou have been provided with the Stooge Sort algorithm which is a recursive sorting algorithm having a worst-case time complexity of O(n^2.709). Despite its inefficiency in sorting large arrays, it offers a fundament... | 0.621763 | Data_Structure_34019 | C | [
"is_sorted",
"optimized_stoogesort"
] | 2 | [
[
"optimized_stoogesort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 72cf964655738609b00d3d26ac8b9b5410f4e7c7 | 9d2818caeceac1dca7dbb89bcd7e591f7517b8b7 | |||
v1.0 | complete | Data_Structure | Data_Structure_34656_C | def matrix_multiply(matrix1, matrix2, mod=None):
"""
Multiplies two 2x2 matrices and returns the resulting matrix.
"""
def matrix_power_iter(matrix, n, mod=None):
"""
Computes the nth power of a 2x2 matrix iteratively using Binary Exponentiation.
>>> matrix_power_iter([[1, 1], [1, 0]], 5) [[8, ... | def matrix_multiply(matrix1, matrix2, mod=None):
"""
Multiplies two 2x2 matrices and returns the resulting matrix.
"""
a11 = matrix1[0][0] * matrix2[0][0] + matrix1[0][1] * matrix2[1][0]
a12 = matrix1[0][0] * matrix2[0][1] + matrix1[0][1] * matrix2[1][1]
a21 = matrix1[1][0] * matrix2[0][0] + mat... | from solution import matrix_multiply, matrix_power_iter, matrix_power_recur
def test_matrix_multiply_no_mod():
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[2, 0], [1, 2]]
expected = [[4, 4], [10, 8]]
assert matrix_multiply(matrix1, matrix2) == expected
def test_matrix_multiply_with_mod():
matrix1 = [[1,... | [
{
"docstring": "Multiplies two 2x2 matrices and returns the resulting matrix.",
"function_declaration": "def matrix_multiply(matrix1, matrix2, mod=None):",
"function_name": "matrix_multiply",
"parameter_list": "(matrix1, matrix2, mod=None)"
},
{
"docstring": "Computes the nth power of a 2x2 ... | [
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 matrix_multiply(A, B, mod=None):\n \"\"\"\n Multiplies two 2x2 matrices A and B.\n \"\"\"\n a11 = (A[0][0] * B[0][0] + A[0][1] * B[1][0]) % mo... | trial_gpt4o_7 | {
"original_instruction": "**Question: Implement Binary Exponentiation with Matrix Representation**\n\n### Context:\nBinary exponentiation is a powerful technique to compute large powers efficiently. This approach can be extended to other mathematical structures like matrices. For example, computing the nth power of ... | 0.567552 | Data_Structure_34656 | C | [
"matrix_multiply",
"matrix_power_iter",
"matrix_power_recur"
] | 3 | [
[
"matrix_power_iter",
"matrix_multiply"
],
[
"matrix_power_recur",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 245173f26e828c5974d11da47868f9c95fc11b4d | 7cb1734f25e8f7b79fbdb1bebf9e7316979251cd | |||
v1.0 | complete | Data_Structure | Data_Structure_34912_C | def parallel_bitonic_sort(arr, reverse=False):
"""
Sorts the array arr in bitonic sequence in parallel.
Args:
arr : List[int] : The array to be sorted.
reverse : bool : If True, sorts the array in descending order, otherwise in ascending order.
Returns:
List[int] : Sorted array in ... | from multiprocessing import Process, Manager
def compare_and_swap(arr, i, j, direction):
if direction == (arr[i] > arr[j]):
arr[i], arr[j] = arr[j], arr[i]
def bitonic_merge(arr, start, length, direction):
if length > 1:
mid = length // 2
for i in range(start, start + mid):
... | from solution import parallel_bitonic_sort
def test_bitonic_sort_ascending():
assert parallel_bitonic_sort([3, 7, 2, 8, 6, 4, 5, 1]) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_bitonic_sort_descending():
assert parallel_bitonic_sort([3, 7, 2, 8, 6, 4, 5, 1], reverse=True) == [8, 7, 6, 5, 4, 3, 2, 1]
def test_bitoni... | [
{
"docstring": null,
"function_declaration": "def compare_and_swap(arr, i, j, direction):",
"function_name": "compare_and_swap",
"parameter_list": "(arr, i, j, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, start, length, direction):",
"function_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": "from multiprocessing import Pool\nimport math\n\ndef compare_and_swap(arr, i, j, reverse):\n if (arr[i] > arr[j]) == reverse:\n arr[i], arr[j] = arr... | trial_gpt4o_1 | {
"original_instruction": "You are given an implementation of the Bitonic Sort algorithm, a parallelizable sorting algorithm that can sort arrays of sizes that are powers of two in both increasing and decreasing order. The provided implementation is non-parallel and works for arrays where the length is a power of two... | 0.645952 | Data_Structure_34912 | C | [
"compare_and_swap",
"bitonic_merge",
"bitonic_sort_subarray",
"parallel_bitonic_sort"
] | 4 | [
[
"bitonic_merge",
"compare_and_swap"
],
[
"bitonic_sort_subarray",
"bitonic_merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 96a56420be4245483e693b27d4c2b9cb157e7992 | e4b719dfb834635962d4f0b1f61b470f421f9b69 | |||
v1.0 | complete | Data_Structure | Data_Structure_34183_C | def optimized_sort(arr: list) -> list:
""" Sort the input list using a more efficient sorting algorithm and return the sorted list.
"""
def bucket_sort(arr: list) -> list:
""" Perform bucket sort on the input list using optimized_sort to sort each bucket.
Args:
arr (list): The list of inte... | def optimized_sort(arr):
"""
Sort the input list using Timsort (as implemented by Python's sorted function) and return the sorted list.
"""
return sorted(arr)
def bucket_sort(arr):
if not arr:
return arr
num_buckets = len(arr)
max_value = max(arr)
buckets = [[] for _ in range(n... | from solution import optimized_sort, bucket_sort
def test_optimized_sort_empty():
assert optimized_sort([]) == []
def test_optimized_sort_single_element():
assert optimized_sort([1]) == [1]
def test_optimized_sort_already_sorted():
assert optimized_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_optim... | [
{
"docstring": "Sort the input list using Timsort (as implemented by Python's sorted function) and return the sorted list.",
"function_declaration": "def optimized_sort(arr):",
"function_name": "optimized_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "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 optimized_sort(arr):\n \"\"\"\n Sort the input list using a Timsort (via sorted() function) and return the sorted list.\n \"\"\"\n return sort... | trial_gpt4o_2 | {
"original_instruction": "### Bucket Sort Enhancement\n\nYou are provided with an implementation of the Bucket Sort algorithm which uses `next_sort` (insertion sort) to sort elements within each bucket. This implementation has a time complexity of O(n^2) in the worst case due to the use of insertion sort. Your task ... | 0.605222 | Data_Structure_34183 | C | [
"optimized_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"optimized_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3d9756d0c10dfa9406f80dffa9bc1ea0688205d1 | 8ecf31e5da48a45a44e77864c5c711039b1cf4a8 | |||
v1.0 | complete | Data_Structure | Data_Structure_34372_C | from typing import Tuple
def mod_inverse(e: int, phi: int) -> int:
""" Compute the modular inverse of e and phi.
>>> mod_inverse(7, 40)
23
"""
pass
def generate_key(k: int, seed: int = None) -> Tuple[int, int, int]:
""" Generate RSA public and private keys of bit length k.
>>> generate_key... | import random
from math import gcd
from sympy import isprime
def mod_inverse(e, phi):
"""
Use the Extended Euclidean Algorithm to find the multiplicative inverse of e mod phi.
"""
def egcd(a, b):
x0, x1, y0, y1 = 0, 1, 1, 0
while a != 0:
q, a, b = b // a, b % a, a
... | from solution import generate_key, encrypt, decrypt
def test_key_generation():
n, e, d = generate_key(128, seed=42)
assert isinstance(n, int) and n > 0
assert isinstance(e, int) and e > 0
assert isinstance(d, int) and d > 0
def test_encryption_decryption():
n, e, d = generate_key(128, seed=42)
... | [
{
"docstring": "Use the Extended Euclidean Algorithm to find the multiplicative inverse of e mod phi.",
"function_declaration": "def mod_inverse(e, phi):",
"function_name": "mod_inverse",
"parameter_list": "(e, phi)"
},
{
"docstring": "Generate a prime number of specified bit length.",
"... | [
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 math import gcd\nfrom sympy import isprime\n\ndef mod_inverse(e, phi):\n \"\"\"\n Use the Extended Euclidean Algorithm to find the m... | trial_gpt4o_0 | {
"original_instruction": "### RSA Encryption System Implementation\n\n**Objective**: Implement an RSA encryption/decryption system with specific focus on generating keys efficiently.\n\nYou are given a partially completed RSA encryption algorithm. Your task is to implement an optimized version of the `generate_key()... | 0.708336 | Data_Structure_34372 | C | [
"mod_inverse",
"generate_prime",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_prime"
],
[
"generate_key",
"mod_inverse"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | c96278306f264cfb1dfb7b8d3f9cc09dffb0700e | a030ce52ac793634608f7c3e8ce8d7c2e8947378 | |||
v1.0 | complete | Data_Structure | Data_Structure_34475_C | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def find_successor(root: TreeNode, node: TreeNode) -> TreeNode:
"""
Finds the in-order successor of the given node in the BST.
Parameters:
root (TreeNode): The root of the BST
nod... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def find_successor(root: TreeNode, node: TreeNode) -> TreeNode:
"""
Finds the in-order successor of the given node in the BST.
Parameters:
root (TreeNode): The root of the BST
nod... | from solution import TreeNode, find_successor
def test_find_successor_on_right_subtree():
root = TreeNode(20)
root.left = TreeNode(10)
root.right = TreeNode(30)
root.right.left = TreeNode(25)
root.right.right = TreeNode(35)
node = root
assert find_successor(root, node).val == 25
def test_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": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef find_successor(root: TreeNode, n... | trial_gpt4o_0 | {
"original_instruction": "## Question\n\n### Scenario\nA company manages a dynamically changing collection of sorted numerical data that needs constant querying for the next higher element. The data is stored in a Binary Search Tree (BST) for efficiency. An important feature in their application is to find the in-or... | 0.542637 | Data_Structure_34475 | C | [
"find_successor",
"find_min"
] | 2 | [
[
"find_successor",
"find_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 8032c5fd672614f6195bddea0e0b73ded36cf4f9 | 4f2450f3914cf07876ad86e8fdff14a112113890 | |||
v1.0 | complete | Data_Structure | Data_Structure_34934_C | from typing import List
def exchange_sort(arr: List[int]) -> List[int]:
"""Sorts the array using the Exchange Sort algorithm.
>>> exchange_sort([5, 3, 4, 1, 2])
[1, 2, 3, 4, 5]
>>> exchange_sort([34, 7, 23, 32, 5, 62])
[5, 7, 23, 32, 34, 62]
"""
pass
def optimized_sort(arr: List[int]) -> L... | def exchange_sort(arr):
"""
Sorts the array using the Exchange Sort algorithm.
"""
n = len(arr)
for i in range(n):
for j in range(i+1, n):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr
def optimized_sort(arr):
"""
Sorts the array usin... | from solution import exchange_sort, optimized_sort
def test_exchange_sort_empty():
assert exchange_sort([]) == []
def test_exchange_sort_single_element():
assert exchange_sort([1]) == [1]
def test_exchange_sort_sorted():
assert exchange_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_exchange_sort_uns... | [
{
"docstring": "Sorts the array using the Exchange Sort algorithm.",
"function_declaration": "def exchange_sort(arr):",
"function_name": "exchange_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the array using Python's built-in Timsort algorithm.",
"function_declaration": "def... | [
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 time\nfrom typing import List\n\ndef exchange_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array using the Exchange Sort algorithm.\n ... | trial_gpt4o_1 | {
"original_instruction": "### Background\nYou are given a simple sorting algorithm called \"Exchange Sort\" which compares each pair of elements in the list and swaps them if they are in the wrong order. However, due to its quadratic time complexity, this algorithm is quite inefficient for large datasets. Your task ... | 0.566931 | Data_Structure_34934 | C | [
"exchange_sort",
"optimized_sort",
"compare_sorts"
] | 3 | [
[
"compare_sorts",
"exchange_sort"
],
[
"compare_sorts",
"optimized_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 54edcc22dae3c0ec9e41b7d3c69e4ba1b4413964 | 27513aade67c2d8bb6c1453cdab204408b2a4acb | |||
v1.0 | complete | Data_Structure | Data_Structure_34007_C | import random
def enhanced_quick_sort(arr, threshold=10):
""" Enhanced version of Quick Sort with random pivot selection and insertion sort for small arrays.
Args:
arr (List[int]): List of integers to be sorted.
threshold (int): Subarray size below which Insertion Sort is applied, default is 10... | import random
def insertion_sort(arr, left, right):
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def enhanced_quick_sort(arr, threshold=10):
if len(arr) <= 1:
... | from solution import enhanced_quick_sort
def test_empty_array():
assert enhanced_quick_sort([]) == []
def test_single_element_array():
assert enhanced_quick_sort([1]) == [1]
def test_sorted_array():
assert enhanced_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
asser... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def enhanced_quick_sort(arr, threshold=10):",
"function_name": "enhanced_qu... | [
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 insertion_sort(arr, left, right):\n \"\"\"\n Sorts a portion of the array in place using Insertion Sort.\n \"\"\"\n for i in ... | trial_gpt4o_2 | {
"original_instruction": "### Coding Assessment: Enhanced Quick Sort\n\n#### Context:\nQuick Sort is an efficient, general-purpose, comparison-based sorting algorithm. This assessment checks your understanding and ability to implement optimizations to the Quick Sort algorithm to handle edge cases effectively and imp... | 0.628362 | Data_Structure_34007 | C | [
"insertion_sort",
"enhanced_quick_sort"
] | 2 | [
[
"enhanced_quick_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 479f08a7098ed7d47f93c482dc40432cc994710b | a87e64a5336f0186b255057a90ddbbbdb29ce09c | |||
v1.0 | complete | Data_Structure | Data_Structure_35011_C | from typing import List
def rotate_array(array: List[int], k: int) -> None:
""" Rotates the array to the right by k steps in-place.
>>> array = [1, 2, 3, 4, 5, 6, 7]
>>> k = 3
>>> rotate_array(array, k)
>>> array
[5, 6, 7, 1, 2, 3, 4]
>>> array = [-1, -100, 3, 99]
>>> k = 2
>>> rot... | from typing import List
def rotate_array(array: List[int], k: int) -> None:
"""
Rotates the array to the right by k steps in-place.
"""
n = len(array)
if n == 0:
return
k = k % n # Normalize k to handle cases where k > n
if k == 0:
return
# Reverse the whole array... | from solution import rotate_array
def test_rotate_array_example_1():
array = [1, 2, 3, 4, 5, 6, 7]
k = 3
rotate_array(array, k)
assert array == [5, 6, 7, 1, 2, 3, 4]
def test_rotate_array_example_2():
array = [-1, -100, 3, 99]
k = 2
rotate_array(array, k)
assert array == [3, 99, -1, -1... | [
{
"docstring": "Rotates the array to the right by k steps in-place.",
"function_declaration": "def rotate_array(array, k):",
"function_name": "rotate_array",
"parameter_list": "(array, k)"
},
{
"docstring": "Helper function to reverse elements in the array from index start to end.",
"fun... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def rotate_array(array, k):\n \"\"\"\n Rotates an array to the right by k steps in-place.\n \n :param array: List[int] - The array to rotate\n ... | trial_gpt4o_2 | {
"original_instruction": "### Rotate Array Problem\n\n#### Scenario\nYou are developing a feature in a game where players can move an array of prizes to the right by a certain number of steps. This feature should be efficient and handle various edge cases.\n\n#### Task\nWrite a function `rotate_array` that rotates a... | 0.633033 | Data_Structure_35011 | C | [
"rotate_array",
"reverse"
] | 2 | [
[
"rotate_array",
"reverse"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 436c4524be13c5a06986192303bc521a6250c1dd | 1f54cc1a9d806630f93dc12e13cd77d21977eee9 | |||
v1.0 | complete | Data_Structure | Data_Structure_35002_C | from typing import List
def find_words(board: List[List[str]], words: List[str]) -> List[str]:
""" Find all words from a given list that can be formed in a word search grid.
Each word must be constructed from letters of sequentially adjacent cells.
>>> board = [
... ['o','a','a','n'],
... [... | class TrieNode:
def __init__(self):
self.children = {}
self.word = None
def add_word(root, word):
node = root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.word = word
def find_words(board, w... | from solution import find_words
def test_example_case():
board = [
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath", "pea", "eat", "rain"]
assert sorted(find_words(board, words)) == sorted(["oath", "eat"])
def test_no_matches(... | [] | [
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 TrieNode:\n def __init__(self):\n self.children = {}\n self.word = None\n\ndef add_word(root, word):\n node = root\n for char in ... | trial_gpt4o_0 | {
"original_instruction": "### Objective\nConduct a comprehensive analysis of your understanding of Tries and Backtracking algorithms by implementing a function that finds all the words from a given list that can be formed in a word search grid.\n\n### Problem Description\nYou're given a 2D board of characters and a ... | 0.634803 | Data_Structure_35002 | C | [
"add_word",
"find_words"
] | 2 | [
[
"find_words",
"add_word"
]
] | 1 | [] | false | [
"TrieNode"
] | true | pytest | true | [] | true | 90fa013b883b10d694d04b39530512a2e6b62f72 | 74c4a9f6992d193bc573535a2e0678a41b2a99b8 | |||
v1.0 | complete | Data_Structure | Data_Structure_34355_C | def validate_diffie_hellman(a: int, p: int) -> int:
"""
Verifies the prime number p and primitive root a, then calculates
and returns the shared secret key if valid, otherwise raises an error.
Parameters:
a (int) : candidate primitive root
p (int) : candidate prime number
Returns:
in... | def is_prime(n: int) -> bool:
"""Returns True if n is a prime number, otherwise False."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import validate_diffie_hellman
def test_valid_diffie_hellman():
assert validate_diffie_hellman(5, 23) == pow(5, 6 * 15, 23)
assert validate_diffie_hellman(2, 13) == pow(2, 6 * 15, 13)
def test_invalid_prime():
try:
validate_diffie_hellman(2, 16)
except ValueError as e:
as... | [
{
"docstring": "Returns True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the value of Euler's Totient function phi(n).",
"function_declaration": "def euler_totient(n... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5... | trial_gpt4o_6 | {
"original_instruction": "Alice and Bob want to establish a secure communication channel using the Diffie-Hellman key exchange protocol. However, they suspect that there may be issues with the prime number \\( p \\) they are using or the primitive root \\( a \\).\n\nYou are to write a function that verifies whether ... | 0.530713 | Data_Structure_34355 | C | [
"is_prime",
"euler_totient",
"find_order",
"is_primitive_root",
"diffie_hellman_shared_secret",
"validate_diffie_hellman"
] | 6 | [
[
"is_primitive_root",
"euler_totient"
],
[
"is_primitive_root",
"is_prime"
],
[
"validate_diffie_hellman",
"is_prime"
],
[
"validate_diffie_hellman",
"is_primitive_root"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 96c530dc3c0b829e99dc6167646baabb24bb4881 | 35ef2f77ca1bd711a493f4c27b53ba6c6e473edb | |||
v1.0 | complete | Data_Structure | Data_Structure_34268_C | from typing import List
def improved_bucket_sort(arr: List[float]) -> List[float]:
"""
Sort the array using the improved bucket sort algorithm.
Parameters:
arr (List[float]): The input array of floating-point numbers to be sorted, where each number is in the range [0, 1).
Returns:
Lis... | from typing import List
def quicksort(arr):
"""Helper function to sort a given list using QuickSort algorithm."""
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
... | from solution import improved_bucket_sort
def test_improved_bucket_sort_empty_array():
assert improved_bucket_sort([]) == []
def test_improved_bucket_sort_all_identical_elements():
assert improved_bucket_sort([0.23, 0.23, 0.23, 0.23]) == [0.23, 0.23, 0.23, 0.23]
def test_improved_bucket_sort_example_case():
... | [
{
"docstring": "Helper function to sort a given list using QuickSort algorithm.",
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"parameter_list": "(arr)"
},
{
"docstring": "Sort the array using the improved bucket sort algorithm.",
"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\nimport math\n\ndef improved_bucket_sort(arr: List[float]) -> List[float]:\n \"\"\"\n Sorts a list of floating point numbers bet... | trial_gpt4o_2 | {
"original_instruction": "Improved Bucket Sort Implementation\n\nYou are tasked with implementing a more robust and efficient version of the Bucket Sort algorithm. The current implementation uses Insertion Sort to sort the elements within each bucket, which can be inefficient for larger datasets. Moreover, the curre... | 0.601305 | Data_Structure_34268 | C | [
"quicksort",
"improved_bucket_sort"
] | 2 | [
[
"improved_bucket_sort",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c8c769047054476e8b23dd6ad1087fd8e8fd9fd3 | d14a4d50d150f4f78dfccf974968d238eec18efd | |||
v1.0 | complete | Data_Structure | Data_Structure_34219_C | class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.height = 1 # Height of node in the AVL tree
self.key = key
class BST:
def __init__(self):
self.root = None
def insert(self, key):
if self.root is None:
self.roo... | class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.height = 1 # Height of node in the AVL tree
self.key = key
class BST:
def __init__(self):
self.root = None
def insert(self, key):
if self.root is None:
self.roo... | import pytest
from solution import BST, bst_insert_balanced
def test_empty_tree_insertion():
tree = BST()
tree.insert(10)
assert tree.root is not None
assert tree.root.key == 10
assert tree.root.left is None
assert tree.root.right is None
assert tree.root.height == 1
def test_insert_mainta... | [] | [
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, key):\n self.left = None\n self.right = None\n self.val = key\n self.height = 1 # Height ... | trial_gpt4o_2 | {
"original_instruction": "### Binary Search Tree Balanced Insertion Algorithm\n\n#### Context\nA Binary Search Tree (BST) is effective but can degenerate into a linked list in the worst case, especially with sequential data insertions. To mitigate this, we need to implement a balanced insertion mechanism. This ensur... | 0.522698 | Data_Structure_34219 | C | [
"bst_insert_balanced",
"rotate_left",
"rotate_right",
"get_height",
"get_balance"
] | 5 | [
[
"bst_insert_balanced",
"get_balance"
],
[
"bst_insert_balanced",
"get_height"
],
[
"bst_insert_balanced",
"rotate_left"
],
[
"bst_insert_balanced",
"rotate_right"
],
[
"get_balance",
"get_height"
],
[
"rotate_left",
"get_height"
],
[
"rot... | 7 | [] | false | [
"TreeNode",
"BST"
] | true | pytest | true | [] | true | 25df6332fb59188d51df98621097897604adf638 | d870ebcd29a39d4122ea6385cd700778d6ea91e5 | |||
v1.0 | complete | Data_Structure | Data_Structure_34590_C | from typing import List, Dict, Any
def hailstone(n: int) -> List[int]:
"""
Generates and returns the hailstone sequence starting from the given number `n`.
:param n: Starting integer (n > 0)
:return: List of integers representing the hailstone sequence.
"""
pass
def analyze_hailstone(n: i... | from typing import List, Dict, Any
def hailstone(n: int) -> List[int]:
"""
Generates and returns the hailstone sequence starting from the given number `n`.
:param n: Starting integer (n > 0)
:return: List of integers representing the hailstone sequence.
"""
sequence = []
while n != 1:
... | from solution import hailstone, analyze_hailstone
def test_hailstone_example1():
assert hailstone(5) == [5, 16, 8, 4, 2, 1]
def test_hailstone_example2():
assert hailstone(1) == [1]
def test_hailstone_example3():
assert hailstone(7) == [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
def t... | [
{
"docstring": "Generates and returns the hailstone sequence starting from the given number `n`.\n\n:param n: Starting integer (n > 0)\n:return: List of integers representing the hailstone sequence.",
"function_declaration": "def hailstone(n):",
"function_name": "hailstone",
"parameter_list": "(n)"
... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "def hailstone(n: int) -> list:\n \"\"\"\n Generates and returns the hailstone sequence starting from the given number `n`.\n\n ... | trial_gpt4o_2 | {
"original_instruction": "### Hailstone Sequence Analysis and Extension\n\nGiven the hailstone sequence defined by the following rules:\n* If the number is 1, the sequence ends.\n* If the number is even, the next number is `n / 2`.\n* If the number is odd, the next number is `3n + 1`.\n\nImplement a function `hailst... | 0.555614 | Data_Structure_34590 | C | [
"hailstone",
"analyze_hailstone"
] | 2 | [
[
"analyze_hailstone",
"hailstone"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0b2b12cdfc40c99421c86c9a22b6e99197dbc6d9 | db897844bd1b97545087b5f6726cf79aff6b9886 | |||
v1.0 | complete | Data_Structure | Data_Structure_34523_C | from typing import List
def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
"""
Sorts a list of non-negative integers using the radix sort algorithm.
If simulation is True, prints the list status after each digit-level sorting iteration.
Args:
arr (List[int]): A list of... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool):
"""
A function to do counting sort of arr[] according to
the digit represented by exp (exp is 10^i where i is
the current digit number)
"""
n = len(arr)
output = [0] * n
count = [0] * 10
# Stor... | from solution import radix_sort
def test_basic_case():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_single_element():
assert radix_sort([5]) == [5]
def test_already_sorted():
assert radix_sort([1, 2, 3, 4, 5, 6, 7, 8, 9]) == [1, 2, 3, 4, 5, 6, 7, 8, 9... | [
{
"docstring": "A function to do counting sort of arr[] according to \nthe digit represented by exp (exp is 10^i where i is \nthe current digit number)",
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
... | [
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 counting_sort(arr: List[int], exp: int, simulation: bool = False) -> None:\n n = len(arr)\n output = [0] * n\n count =... | trial_gpt4o_2 | {
"original_instruction": "You have been tasked with implementing the `radix_sort` function to help a logistics company efficiently sort large arrays of parcel tracking numbers. Each tracking number is a non-negative integer.\n\nTo ensure correctness and performance, please adhere to the specifications provided:\n\n#... | 0.671242 | Data_Structure_34523 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 435daa785abb8692ed728af274730d58d6472d27 | 6c795f9fc076e1960c61dbc6ca10c98a17e0a474 | |||
v1.0 | complete | Data_Structure | Data_Structure_35310_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts the given array using the merge sort algorithm with optimized in-place merge.
Args:
arr (List[int]): An array of integers.
Returns:
List[int]: Sorted array in ascending order.
Examples:
>>> merge_s... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts the given array using the merge sort algorithm with optimized in-place merge.
"""
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted():
assert merge_sort([5,... | [
{
"docstring": "Sorts the given array using the merge sort algorithm with optimized in-place merge.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(arr, left_half, right_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n def merge(left: List[int], right: Li... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nYou are developing a system that processes large datasets, and sorting these datasets efficiently is crucial. You've decided to use Merge Sort due to its consistent performance and stability.\n\n### Task\nImplement the Merge Sort algorithm in Python following the principles de... | 0.652134 | Data_Structure_35310 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 769a3d77d946ab8f3a51401b06e7d528c6019750 | 9e6d0ccea155918634e251a021e030e0cac64d37 | |||
v1.0 | complete | Data_Structure | Data_Structure_35043_C | import random
def enhanced_bogo_sort(arr: list, max_iterations: int) -> list:
"""
Sort the array using an enhanced version of Bogo Sort.
If the array is not sorted within the given number of iterations, return the best effort sorted array.
Parameters:
arr (list): List of integers to be sorted... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def enhanced_bogo_sort(arr, max_iterations):
"""
Sort the array using an enhanced version of Bogo Sort.
If the array is not sorted within... | from solution import enhanced_bogo_sort
def test_enhanced_bogo_sort_sorted_array():
assert enhanced_bogo_sort([1, 2, 3, 4, 5], 1000) == [1, 2, 3, 4, 5]
def test_enhanced_bogo_sort_unsorted_array_negative_iterations():
assert enhanced_bogo_sort([5, 4, 3, 2, 1], 0) == [5, 4, 3, 2, 1]
def test_enhanced_bogo_sor... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sort the array using an enhanced version of Bogo Sort.\nIf the array is not sorted within the given num... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef enhanced_bogo_sort(arr: list, max_iterations: int) -> list:\n def is_sorted(arr):\n \"\"\" Helper function to check if the arra... | trial_gpt4o_1 | {
"original_instruction": "### Problem: Enhanced Bogo Sort\n\n**Background**:\nAlice is learning about sorting algorithms in her computer science class. She has encountered the Bogo Sort algorithm and finds it fascinating despite its impracticality. She wants to explore it further by implementing a slightly modified ... | 0.596816 | Data_Structure_35043 | C | [
"is_sorted",
"enhanced_bogo_sort"
] | 2 | [
[
"enhanced_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 31e3521b5a7433061cab1cd93538780fe33374a8 | 2fd4a5149fb797dec4ee34c05cbadb14cce42201 | |||
v1.0 | complete | Data_Structure | Data_Structure_34772_C | from typing import List
def optimized_merge_sort(arr: List[int], threshold: int) -> List[int]:
"""
Sorts an array using an optimized merge sort approach that switches to
insertion sort for small subarrays.
Parameters:
arr (List[int]): The array of integers to sort.
threshold (int): The thresho... | from typing import List
def insertion_sort(arr: List[int], left: int, right: int) -> None:
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def merge(arr: List[int], lef... | from solution import optimized_merge_sort
def test_optimized_merge_sort():
assert optimized_merge_sort([34, 7, 23, 32, 5, 62, 32], 4) == [5, 7, 23, 32, 32, 34, 62]
assert optimized_merge_sort([], 4) == []
assert optimized_merge_sort([1], 4) == [1]
assert optimized_merge_sort([2, 1], 4) == [1, 2]
as... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def merge(arr, left, mid, right):",
"function_name": "merge",
"paramete... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[int], left: int, right: int):\n for i in range(left + 1, right + 1):\n key = arr[i]\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement an Enhanced Merge Sort\n\nGiven an array of integers, implement an optimized version of the Merge Sort algorithm. The algorithm should:\n1. Use a threshold to switch to Insertion Sort for small subarrays.\n2. Be stable.\n3. Be efficient in both time and space.\n\n###... | 0.587684 | Data_Structure_34772 | C | [
"insertion_sort",
"merge",
"optimized_merge_sort"
] | 3 | [
[
"optimized_merge_sort",
"insertion_sort"
],
[
"optimized_merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2b98a4e07b103c9776a51cb672ebc9a2d25002ed | b3e5ca789128cb85f2d78c613bb3abc89ab95b2e | |||
v1.0 | complete | Data_Structure | Data_Structure_35041_C | def pancake_sort(arr: List[int]) -> List[int]:
""" Sorts an unsorted list of integers using the Pancake Sort algorithm.
>>> pancake_sort([3, 2, 4, 1])
[1, 2, 3, 4]
>>> pancake_sort([10, 5, 7, 3, 2])
[2, 3, 5, 7, 10]
"""
# Here are some test cases to validate your solution
def test_already_sorte... | def flip(arr, k):
"""
Reverses the order of the first k elements in the array arr.
"""
arr[:k] = arr[:k][::-1]
def find_max_index(arr, n):
"""
Finds the index of the maximum element in arr upto the first n elements.
"""
return max(range(n), key=lambda i: arr[i])
def pancake_sort(arr):
... | from solution import pancake_sort
def test_already_sorted():
assert pancake_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted():
assert pancake_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_mixed_elements():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
assert pancake_sort([10,... | [
{
"docstring": "Reverses the order of the first k elements in the array arr.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Finds the index of the maximum element in arr upto the first n elements.",
"function_declar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def pancake_sort(arr):\n \"\"\"\n Sorts a list using the Pancake Sort algorithm.\n \n Args:\n arr (list): The list of integers to be sorted.\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question\n\nYou are given an unsorted list of integers. Your task is to implement the Pancake Sort algorithm to sort the list. Pancake Sorting is a variation of the selection sort wherein you repeatedly flip (reverse) subarrays to move the largest unsorted element to its correct positio... | 0.743639 | Data_Structure_35041 | C | [
"flip",
"find_max_index",
"pancake_sort"
] | 3 | [
[
"pancake_sort",
"find_max_index"
],
[
"pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cd10776d8492da2a0757dd8674ee363a69c2408f | 4a68b27a36f66eb94031593962f410376085df86 | |||
v1.0 | complete | Data_Structure | Data_Structure_34892_C | from typing import List
def search_insert(arr: List[int], target: int) -> int:
"""
Helper method to find the insertion position for a target value in a sorted array.
"""
left, right = 0, len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid] < target:
left = ... | from typing import List
def search_insert(arr: List[int], target: int) -> int:
"""
Helper method to find the insertion position for a target value in a sorted array.
"""
left, right = 0, len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid] < target:
left = ... | from solution import ordered_insert
def test_insert_single_value():
arr = []
values = [5]
expected = [5]
assert ordered_insert(arr, values) == expected
def test_insert_multiple_values():
arr = []
values = [5, 1, 4, 2, 3]
expected = [1, 2, 3, 4, 5]
assert ordered_insert(arr, values) == ... | [
{
"docstring": "Helper method to find the insertion position for a target value in a sorted array.",
"function_declaration": "def search_insert(arr, target):",
"function_name": "search_insert",
"parameter_list": "(arr, target)"
},
{
"docstring": "Insert each value from the list 'values' into... | [
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) -> int:\n \"\"\"\n Given a sorted array of integers arr and a target value, re... | trial_gpt4o_1 | {
"original_instruction": "Ordered Insert Position\n\nYou are provided with a helper method `search_insert` that implements binary search to find the appropriate insertion position of a target value in a given sorted array. Your task is to create a function that uses this helper method to insert multiple values into ... | 0.717787 | Data_Structure_34892 | C | [
"search_insert",
"ordered_insert"
] | 2 | [
[
"ordered_insert",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6dffea669d5b95bc70227a50fcdbeab385eb80f3 | a7fe081d5fd25dfa2567e4b0641efd85b8c8c9dd | |||
v1.0 | complete | Data_Structure | Data_Structure_34314_C | from typing import Optional, Tuple
def generate_key(k: int, seed: Optional[int] = None) -> Tuple[int, int, int]:
""" Generates an RSA key pair.
:param k: Number of bits for the modulus n.
:param seed: Optional seed for random number generation.
:return: A tuple (n, e, d) where n is the modulus, e is th... | import random
from typing import Optional, Tuple
def is_prime(n, k=128):
""" Test if a number is prime using the Miller-Rabin primality test. """
if n == 2 or n == 3:
return True
if n <= 1 or n % 2 == 0:
return False
# Write n-1 as 2^r * d
r, s = 0, n - 1
while s % 2 == 0:
... | from solution import generate_key, encrypt, decrypt
def test_key_generation():
n, e, d = generate_key(16, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_encrypt_decrypt():
n, e, d = generate_key(16, seed=42)
data = 20
encrypted = encrypt(dat... | [
{
"docstring": "Test if a number is prime using the Miller-Rabin primality test. ",
"function_declaration": "def is_prime(n, k=128):",
"function_name": "is_prime",
"parameter_list": "(n, k=128)"
},
{
"docstring": "Generate an odd integer randomly. ",
"function_declaration": "def generate... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import Tuple, Optional\nfrom sympy import primerange\n\ndef is_prime(n: int) -> bool:\n \"\"\"Returns True if n is a prime numbe... | trial_gpt4o_2 | {
"original_instruction": "### RSA Key Pair Generation and Encryption/Decryption\n\n#### Problem Statement\nYou are to implement an RSA encryption and decryption functionality, including key pair generation, using RSA principles. The implementation must include enhancements over the provided primality testing mechani... | 0.745578 | Data_Structure_34314 | C | [
"is_prime",
"generate_prime_candidate",
"generate_prime_number",
"gcd",
"modinv",
"generate_key",
"encrypt",
"decrypt"
] | 8 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"generate_prime_number"
],
[
"generate_key",
"modinv"
],
[
"generate_prime_number",
"generate_prime_candidate"
],
[
"generate_prime_number",
"is_prime"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | cc208a5b6aa33d0d2a9bc528435ad8f1da760817 | b7ed9c3a25cd1ca6a08002875b0617b1dee46d4c | |||
v1.0 | complete | Data_Structure | Data_Structure_34367_C | def compress_integers(integers: List[int]) -> str:
""" Compress a list of integers into a single encoded string using Elias γ coding.
>>> compress_integers([13, 5, 1]) "000011001010001"
"""
pass
def decompress_integers(encoded_string: str) -> List[int]:
""" Decode a string encoded using Elias γ cod... | from typing import List
def elias_gamma_encode(number: int) -> str:
if number <= 0:
raise ValueError("Number must be positive")
binary = bin(number)[2:] # Get the binary representation of the number without the '0b' prefix
n = len(binary) - 1
prefix = '0' * n
return prefix + binary
d... | from solution import compress_integers, decompress_integers
def test_compress_and_decompress():
original = [13, 5, 1]
encoded = compress_integers(original)
assert decompress_integers(encoded) == original
def test_large_range():
original = [1, 2, 3, 4, 5, 100, 1000, 10000, 999999, 1000000]
encoded ... | [
{
"docstring": null,
"function_declaration": "def elias_gamma_encode(number):",
"function_name": "elias_gamma_encode",
"parameter_list": "(number)"
},
{
"docstring": null,
"function_declaration": "def elias_gamma_decode(encoded_string, index):",
"function_name": "elias_gamma_decode",... | [
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 elias_gamma_encode(number: int) -> str:\n if number <= 0:\n raise ValueError(\"Elias Gamma encoding is only defined f... | trial_gpt4o_2 | {
"original_instruction": "## Problem Statement:\nYou are tasked with implementing a lossless universal integer coding scheme using the Elias γ and δ codes. Your implementation should compress a list of integers into a single encoded string and be able to decode that string back to the original list of integers.\n\n#... | 0.556358 | Data_Structure_34367 | C | [
"elias_gamma_encode",
"elias_gamma_decode",
"compress_integers",
"decompress_integers"
] | 4 | [
[
"compress_integers",
"elias_gamma_encode"
],
[
"decompress_integers",
"elias_gamma_decode"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6772bca0a9e395bb58c97028d57b6d6d83346412 | 712590e2eb9d16b77f73da8c5eb5f6b8728e1bd8 | |||
v1.0 | complete | Data_Structure | Data_Structure_34808_C | import math
def synchronize_interrupts(a: int, b: int) -> int:
"""
Returns the least common multiple of a and b, considering any trailing zeros in the binary forms of the inputs.
>>> synchronize_interrupts(8, 20)
40
>>> synchronize_interrupts(4, 5)
20
"""
pass
from solution import s... | import math
def remove_trailing_zeros(n):
"""
Removes trailing zeros from the binary representation of n.
"""
while n % 2 == 0:
n //= 2
return n
def synchronize_interrupts(a, b):
"""
Returns the least common multiple of a and b, considering any trailing zeros in the binary forms of... | from solution import synchronize_interrupts
def test_synchronize_interrupts_basic():
assert synchronize_interrupts(8, 20) == 40
assert synchronize_interrupts(4, 5) == 20
assert synchronize_interrupts(6, 8) == 24
assert synchronize_interrupts(9, 12) == 36
def test_synchronize_interrupts_with_trailing_z... | [
{
"docstring": "Removes trailing zeros from the binary representation of n.",
"function_declaration": "def remove_trailing_zeros(n):",
"function_name": "remove_trailing_zeros",
"parameter_list": "(n)"
},
{
"docstring": "Returns the least common multiple of a and b, considering any trailing z... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(x, y):\n while y:\n x, y = y, x % y\n return x\n\ndef lcm(x, y):\n return x * y // gcd(x, y)\n\ndef remove_trailing_zeros(x):\n whi... | trial_gpt4o_1 | {
"original_instruction": "**Problem Statement**:\n\nYou've been assigned a task to help optimize a scheduling system. Two subsystems utilize timer interrupts that reset based on their respective counts. To achieve synchronization in their executions, you need to calculate the Least Common Multiple (LCM) of their int... | 0.485501 | Data_Structure_34808 | C | [
"remove_trailing_zeros",
"synchronize_interrupts"
] | 2 | [
[
"synchronize_interrupts",
"remove_trailing_zeros"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 04d670f2770b80b5a2fca4b5b113237be1f7928b | 6a5d54bc1d3e125000d750ab3174b915af107416 | |||
v1.0 | complete | Data_Structure | Data_Structure_35309_C | def extended_gcd(a: int, b: int) -> [int, int, int]:
"""
Implements the Extended Euclidean Algorithm.
Returns a tuple (s, t, gcd) where s and t are such that a * s + b * t = gcd(a, b).
>>> extended_gcd(30, 20) == (1, -1, 10)
>>> extended_gcd(20, 30) == (-1, 1, 10)
"""
pass
def modular_inver... | def extended_gcd(a, b):
"""
Implements the Extended Euclidean Algorithm.
Returns a tuple (s, t, gcd) where s and t are such that a * s + b * t = gcd(a, b).
"""
if a == 0:
return (0, 1, b)
else:
s1, t1, gcd = extended_gcd(b % a, a)
s = t1 - (b // a) * s1
t = s1
... | from solution import extended_gcd, modular_inverse
def test_extended_gcd():
# Test cases for extended_gcd
assert extended_gcd(30, 20) == (1, -1, 10)
assert extended_gcd(20, 30) == (-1, 1, 10)
assert extended_gcd(7, 3) == (1, -2, 1)
assert extended_gcd(3, 7) == (-2, 1, 1)
assert extended_gcd(10,... | [
{
"docstring": "Implements the Extended Euclidean Algorithm.\nReturns a tuple (s, t, gcd) where s and t are such that a * s + b * t = gcd(a, b).",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the mod... | [
0,
0,
0,
1,
1,
0,
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": "def extended_gcd(a, b):\n \"\"\"\n Implements the Extended Euclidean Algorithm.\n Returns a tuple (s, t, gcd) where a * s + b * t = gcd(a, b).\n \... | trial_gpt4o_8 | {
"original_instruction": "#### Context:\nYou are developing a cryptographic tool that relies on number theory. To complete this tool, you need to implement two critical mathematical functions. One will compute the modular inverse, which is essential for decrypting messages.\n\n#### Task:\nImplement the following two... | 0.649859 | Data_Structure_35309 | C | [
"extended_gcd",
"modular_inverse"
] | 2 | [
[
"modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 786d51c3c3303a627ca9f41af0592bfc9387f321 | 76ac66e9a83d27e2c175f9b949c91b8c721a94a0 | |||
v1.0 | complete | Data_Structure | Data_Structure_35496_C | from typing import List
def pancake_sort(arr: List[int]) -> List[int]:
"""
Sort the provided list of integers using the Pancake Sort technique.
>>> pancake_sort([3, 2, 4, 1])
[1, 2, 3, 4]
>>> pancake_sort([8, 5, 7, 3, 2])
[2, 3, 5, 7, 8]
>>> pancake_sort([1])
[1]
>>> pancake_sort([]... | def flip(arr, k):
"""
Helper function to reverse the order of the first k elements of the array.
"""
arr[:k] = arr[:k][::-1]
def pancake_sort(arr):
"""
Function to sort the array using Pancake Sort technique.
"""
n = len(arr)
for size in range(n, 1, -1):
# Find index of the ... | from solution import pancake_sort
def test_pancake_sort_example():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
assert pancake_sort([8, 5, 7, 3, 2]) == [2, 3, 5, 7, 8]
def test_pancake_sort_single_element():
assert pancake_sort([1]) == [1]
def test_pancake_sort_empty():
assert pancake_sort([]) =... | [
{
"docstring": "Helper function to reverse the order of the first k elements of the array.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Function to sort the array using Pancake Sort technique.",
"function_declarat... | [
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 flip(arr, k):\n \"\"\"\n Helper function to reverse the order of the first k elements of the list.\n \"\"\"\n left = 0\n right = k - 1\n ... | trial_gpt4o_2 | {
"original_instruction": "### Pancake Sort Implementation\n\nYou have been tasked to implement the **Pancake Sort** algorithm, which sorts an array by repetitively flipping subarrays.\n\nWrite a function `pancake_sort(arr: List[int]) -> List[int]` that sorts the provided list of integers using the Pancake Sort techn... | 0.767905 | Data_Structure_35496 | C | [
"flip",
"pancake_sort"
] | 2 | [
[
"pancake_sort",
"flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 61c9f5bf8f0027ece9c665dbf2389e398ae756ef | 89b1351985ca2e985deeb8cbb16141843f520847 | |||
v1.0 | complete | Data_Structure | Data_Structure_35529_C | def enhanced_insertion_sort(arr: List[int]) -> List[int]:
""" Enhanced Insertion Sort algorithm:
- Uses binary search to find the correct position of the element to be inserted, reducing the number of comparisons.
- Maintains the stability of the sort.
- Sorts the given list of integers in ascending ord... | from typing import List
def binary_search(arr: List[int], val: int, start: int, end: int) -> int:
"""
Perform a binary search to find the insertion position for val in arr[start:end]
"""
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
start = mid + 1
e... | from solution import enhanced_insertion_sort
def test_enhanced_insertion_sort_simple():
assert enhanced_insertion_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90]
def test_enhanced_insertion_sort_with_duplicates():
assert enhanced_insertion_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
def... | [
{
"docstring": "Perform a binary search to find the insertion position for val in arr[start:end]",
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "Sorts the array of integers i... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef binary_search(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"Use binary search to find the correct insertio... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort Enhancements\n\nUsing the Insertion Sort algorithm above as a foundation, enhance the algorithm to handle larger datasets more efficiently. Implement a function `enhanced_insertion_sort` that:\n1. Uses binary search to find the correct position of the element to be insert... | 0.6366 | Data_Structure_35529 | C | [
"binary_search",
"enhanced_insertion_sort"
] | 2 | [
[
"enhanced_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f0ed0aeaaa15981afb67895c8bef8239a4cc4ad1 | aedfc378e1c53a312e8216f68455d77ecfe66c9b | |||
v1.0 | complete | Data_Structure | Data_Structure_35669_C | from typing import List
def generate_primes(k: int) -> List[int]:
"""
Generates a list of the first 'k' prime numbers.
Parameters:
k (int): The number of prime numbers to generate, k > 0
Returns:
List[int]: A list containing the first 'k' prime numbers.
>>> generate_primes(5)... | from typing import List
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def gene... | from solution import generate_primes
def test_generate_primes_example_cases():
assert generate_primes(5) == [2, 3, 5, 7, 11]
assert generate_primes(10) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
def test_generate_primes_smallest_k():
assert generate_primes(1) == [2]
def test_generate_primes_known_values():
... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def generate_primes(k):",
"function_name": "generate_primes",
"parameter_list": "(k)"
}
] | [
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 if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % ... | trial_gpt4o_0 | {
"original_instruction": "**Prime Sequence Generator**\n\n### Description\nYou are tasked with creating an algorithm to generate a sequence of the first `k` prime numbers. The function should utilize the primality checking logic to ensure each number in the sequence is prime.\n\n### Function Signature\n```python\nde... | 0.684955 | Data_Structure_35669 | C | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e1e8f0c9cbf8c29524b8d562079bf49ceb1786d2 | 3c4d0171965390b896c15ec1bb3ee7157e54896e | |||
v1.0 | complete | Data_Structure | Data_Structure_35660_C | from typing import Tuple
def solve_diophantine(a: int, b: int) -> Tuple[int, int, int]:
"""
Solves the equation ax + by = gcd(a, b) to find x, y and gcd(a, b).
Parameters:
a (int): The first integer coefficient.
b (int): The second integer coefficient.
Returns:
Tuple[int, int, int... | from typing import Tuple
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
"""
Implementation of the Extended Euclidean Algorithm.
Returns x, y, and gcd such that a*x + b*y = gcd.
"""
if b == 0:
return (1, 0, a)
else:
x1, y1, gcd = extended_gcd(b, a % b)
x = y1
... | from solution import solve_diophantine
def test_solve_diophantine_common_case():
x, y, g = solve_diophantine(30, 12)
assert g == 6
assert 30 * x + 12 * y == g
def test_solve_diophantine_coprime_case():
x, y, g = solve_diophantine(101, 10)
assert g == 1
assert 101 * x + 10 * y == g
def test_so... | [
{
"docstring": "Implementation of the Extended Euclidean Algorithm.\nReturns x, y, and gcd such that a*x + b*y = gcd.",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Solves the equation ax + by = gcd(a, b) to... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Tuple\n\ndef extended_gcd(a: int, b: int) -> Tuple[int, int, int]:\n if a == 0:\n return (b, 0, 1)\n else:\n gcd, x1, y... | trial_gpt4o_7 | {
"original_instruction": "### Diophantine Equation Solver\n\n**Problem Statement**: Implement a function to solve the Diophantine equation \\( ax + by = gcd(a, b) \\) using the Extended Euclidean Algorithm.\n\n**Function Signature**:\n```python\ndef solve_diophantine(a: int, b: int) -> Tuple[int, int, int]:\n \"\... | 0.661529 | Data_Structure_35660 | C | [
"extended_gcd",
"solve_diophantine"
] | 2 | [
[
"solve_diophantine",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cb5e693b330f02bf2a97e0de2b7db49f53ca53c0 | a890ce88f07e108a849a2d2b066fe31d622dd1eb | |||
v1.0 | complete | Data_Structure | Data_Structure_35124_C | from typing import List, Tuple
def merge_sort_tuples(arr: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
""" Sort a list of tuples based on the sum of the elements in the tuples.
>>> merge_sort_tuples([(3, 4), (1, 2), (5, 1), (2, 2)])
[(1, 2), (2, 2), (5, 1), (3, 4)]
"""
def merge(left: List[Tuple[i... | from typing import List, Tuple
def merge_sort_tuples(arr: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort_tuples(arr[:mid])
right = merge_sort_tuples(arr[mid:])
return merge(left, right)
def merge(left: List[Tupl... | from solution import merge_sort_tuples
def test_merge_sort_empty_list():
assert merge_sort_tuples([]) == []
def test_merge_sort_single_element():
assert merge_sort_tuples([(5, 2)]) == [(5, 2)]
def test_merge_sort_already_sorted():
assert merge_sort_tuples([(1, 3), (2, 2), (5, 1)]) == [(1, 3), (2, 2), (5,... | [
{
"docstring": null,
"function_declaration": "def merge_sort_tuples(arr):",
"function_name": "merge_sort_tuples",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
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 merge_sort_tuples(arr: List[Tuple[int, int]]) -> List[Tuple[int, int]]:\n if len(arr) <= 1:\n return arr\n ... | trial_gpt4o_0 | {
"original_instruction": "### Merge Sort Implementation and Extension\n\nYou are tasked to implement the Merge Sort algorithm with a slight twist. Instead of sorting a list of integers, you are required to sort a list of tuples based on the sum of the elements in the tuples. Your implementation should maintain the s... | 0.623798 | Data_Structure_35124 | C | [
"merge_sort_tuples",
"merge"
] | 2 | [
[
"merge_sort_tuples",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bba128accd44347154ec1c3bd2ab679b050ce879 | e1c606c3ebe11c10072de31df819ba64a1bb0a7a | |||
v1.0 | complete | Data_Structure | Data_Structure_35179_C | def construct_inorder_tree(pre: List[int], post: List[int]) -> List[int]:
"""Construct a full binary tree from given preorder and postorder traversal arrays and obtain its inorder traversal.
Args:
pre (List[int]): A list of integers representing the preorder traversal of a full binary tree.
post (List[... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def build_tree(pre, pre_start, pre_end, post, post_start, post_end):
if pre_start > pre_end or post_start > post_end:
return None
root = TreeNode(pre[pre_start])
if pre_start == pre_e... | def test_construct_inorder_tree_example_case():
pre = [1, 2, 4, 5, 3, 6, 7]
post = [4, 5, 2, 6, 7, 3, 1]
assert construct_inorder_tree(pre, post) == [4, 2, 5, 1, 6, 3, 7]
def test_construct_inorder_tree_single_node():
pre = [1]
post = [1]
assert construct_inorder_tree(pre, post) == [1]
def tes... | [] | [
0,
0,
0,
0,
1,
0,
1,
1,
1
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef... | trial_gpt4o_9 | {
"original_instruction": "**Goal**: Construct a full binary tree from given preorder and postorder traversal arrays and obtain its inorder traversal.\n\n**Scenario**: \nA software company is working on a new feature for their web-based visualization tool. The tool is supposed to reconstruct a full binary tree using ... | 0.529295 | Data_Structure_35179 | C | [
"build_tree",
"inorderTraversal",
"construct_inorder_tree"
] | 3 | [
[
"construct_inorder_tree",
"build_tree"
],
[
"construct_inorder_tree",
"inorderTraversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | false | [] | true | 41e243412c89573e8c2e72c6e5e5acc0ff453f52 | 614815fe597d5c8e7756b863ac566218cb92ae8d | |||
v1.0 | complete | Data_Structure | Data_Structure_35742_C | def multiply(x: int, y: int) -> int:
"""
Multiplies two non-negative integers without using the '*' operator.
Parameters:
x (int): Non-negative integer
y (int): Non-negative integer
Returns:
int: The result of multiplying x and y
>>> multiply(3, 5) == 15
>>> multiply(0, 7) == ... | def bitwise_add(a, b):
while b != 0:
carry = a & b
a = a ^ b
b = carry << 1
return a
def multiply(x: int, y: int) -> int:
result = 0
while y > 0:
if y & 1:
result = bitwise_add(result, x)
x <<= 1
y >>= 1
return result | from solution import multiply
def test_multiply_basic():
assert multiply(3, 5) == 15
assert multiply(0, 7) == 0
assert multiply(4, 6) == 24
assert multiply(1, 1) == 1
assert multiply(7, 8) == 56
def test_multiply_large_numbers():
assert multiply(123, 456) == 56088
assert multiply(1000, 100... | [
{
"docstring": null,
"function_declaration": "def bitwise_add(a, b):",
"function_name": "bitwise_add",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def multiply(x, y):",
"function_name": "multiply",
"parameter_list": "(x, y)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bitwise_add(a, b):\n \"\"\"\n Adds two integers using bitwise operations.\n \n Parameters:\n a (int): An integer.\n b (int): Another int... | trial_gpt4o_2 | {
"original_instruction": "#### Context:\nImagine you are developing a low-level system where standard arithmetic operations are restricted. Instead, you must use bitwise operations to compute results. \n\n#### Task:\nImplement a function to multiply two non-negative integers without using the '*' operator. Similar t... | 0.806984 | Data_Structure_35742 | C | [
"bitwise_add",
"multiply"
] | 2 | [
[
"multiply",
"bitwise_add"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bd006f91109fef09597e076329efe6d8ee1a2451 | 3be025428a13b5d1c5ec3e2480b6850a22fe32ba | |||
v1.0 | complete | Data_Structure | Data_Structure_35287_C | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(length):
"""Generate an odd integer randomly"""
p = random.getrandbits(length)
# apply a mask to set MSB and LSB to 1
p |= (1 << length - 1) | 1
return p
def generate_prime_number(length=1024):
"""Generate a prim... | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(length):
"""Generate an odd integer randomly"""
p = random.getrandbits(length)
# apply a mask to set MSB and LSB to 1
p |= (1 << length - 1) | 1
return p
def generate_prime_number(length=1024):
"""Generate a prim... | import pytest
from solution import generate_key_pairs, encrypt_message, decrypt_message
def test_generate_key_pairs():
public_key, private_key = generate_key_pairs(16)
assert len(public_key) == 2
assert len(private_key) == 2
assert public_key[1] == private_key[1]
def test_encrypt_decrypt_message():
... | [
{
"docstring": "Generate an odd integer randomly",
"function_declaration": "def generate_prime_candidate(length):",
"function_name": "generate_prime_candidate",
"parameter_list": "(length)"
},
{
"docstring": "Generate a prime number of 'length' bits",
"function_declaration": "def generat... | [
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 gcd(a, b):\n while b != 0:\n a, b = b, a % b\n return a\n\ndef mod_inverse(a, m):\n m0, x0, x1 = m, 0, 1\n if m == 1:\... | trial_gpt4o_2 | {
"original_instruction": "### RSA Encryption Coding Challenge\n\n#### Objective\nImplement functions to generate RSA keys, encrypt, and decrypt text messages. This exercise will test your understanding of RSA encryption, prime number generation, and modular arithmetic.\n\n#### Scenario\nYou are working on a secure c... | 0.6426 | Data_Structure_35287 | C | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key_pairs",
"gcd",
"encrypt_message",
"decrypt_message"
] | 6 | [
[
"generate_key_pairs",
"gcd"
],
[
"generate_key_pairs",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 3 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 6c038119b6c042bdf9d5357256c521e65c91dac9 | e67b819c452758c8f6cd6f60a2cc452df83ecdf3 | |||
v1.0 | complete | Data_Structure | Data_Structure_35780_C | from typing import List
def custom_radix_sort(arr: List[int]) -> List[int]:
"""
Given a list of non-negative integers, implement a custom variant of Radix Sort that sorts the list in descending order.
Args:
arr (List[int]): A list of non-negative integers.
Returns:
List[int]: A new list where... | def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[(index % 10)] += 1
for i in range(8, -1, -1):
count[i] += count[i + 1]
for i in range(n - 1, -1, -1):
index = arr[i] // exp
... | from solution import custom_radix_sort
def test_custom_radix_sort_example_1():
assert custom_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [802, 170, 90, 75, 66, 45, 24, 2]
def test_custom_radix_sort_example_2():
assert custom_radix_sort([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
def test_custom_radix_sort_empty... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def custom_radix_sort(arr):",
"function_name": "custom_radix_sort",
"parameter_list": "(a... | [
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 counting_sort(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # Co... | trial_gpt4o_1 | {
"original_instruction": "### Code Assessment: Radix Sort Custom Implementation\n\n#### Objective\nGiven a list of non-negative integers, implement a custom variant of Radix Sort that sorts the list in descending order.\n\n#### Task Requirements\n1. Implement a function `custom_radix_sort(arr: List[int]) -> List[int... | 0.71651 | Data_Structure_35780 | C | [
"counting_sort",
"custom_radix_sort"
] | 2 | [
[
"custom_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 79da46f086ccd58f9a995097f83a9e7535fefe7c | 1f4b62097351d1b22ec27a061efcf4773f4fd06d | |||
v1.0 | complete | Data_Structure | Data_Structure_35474_C | from typing import List
def prime_check(num: int) -> bool:
"""
Return True if num is a prime number else return False.
>>> prime_check(2)
True
>>> prime_check(17)
True
>>> prime_check(18)
False
>>> prime_check(29)
True
"""
pass
def euler_totient(n: int) -> int:
"""
... | from math import isqrt
def prime_check(num):
"""
Return True if num is a prime number else 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 % i == 0 or num ... | from solution import prime_check, euler_totient, find_order, find_primitive_root, diffie_hellman_key_exchange
def test_prime_check():
assert prime_check(2) is True
assert prime_check(17) is True
assert prime_check(18) is False
assert prime_check(29) is True
def test_euler_totient():
assert euler_t... | [
{
"docstring": "Return True if num is a prime number else return False.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Return the count of numbers coprime to n.",
"function_declaration": "def euler_totient(n... | [
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 prime_check(num):\n \"\"\"\n Return True if num is a prime number else return False.\n \"\"\"\n if num <= 1:\n return False\n if num... | trial_gpt4o_3 | {
"original_instruction": "### Diffie-Hellman Key Exchange Implementation\n\n#### Scenario\nAlice and Bob want to securely share a secret key using the Diffie-Hellman key exchange method. You are required to implement the algorithm to facilitate this secure key exchange.\n\n#### Function Implementation\n\n**Function ... | 0.663328 | Data_Structure_35474 | C | [
"prime_check",
"euler_totient",
"gcd",
"find_order",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 6 | [
[
"diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"diffie_hellman_key_exchange",
"prime_check"
],
[
"euler_totient",
"gcd"
],
[
"find_order",
"prime_check"
],
[
"find_primitive_root",
"gcd"
],
[
"find_primitive_root",
"prime_check"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | d7489aebf0a810ff8d9b72dbc957a41d8a7f609d | 1a8c0d3f885ea9a3b6636d7a36ce7233fbc69716 | |||
v1.0 | complete | Data_Structure | Data_Structure_35518_C | def max_heap_sort(arr: List[int], simulation: bool = False) -> List[int]:
"""
Sorts an array in ascending order using max-heap.
Args:
arr (List[int]): The array of integers to be sorted.
simulation (bool): Optional flag to simulate and print each iteration.
Returns:
List[int]: Sort... | def max_heapify(arr, n, i):
"""
Helper function to maintain the max-heap property.
"""
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... | import pytest
from solution import max_heap_sort, min_heap_sort
def test_max_heap_sort_basic():
assert max_heap_sort([4, 10, 3, 5, 1]) == [1, 3, 4, 5, 10]
def test_min_heap_sort_basic():
assert min_heap_sort([4, 10, 3, 5, 1]) == [1, 3, 4, 5, 10]
def test_max_heap_sort_empty():
assert max_heap_sort([]) ==... | [
{
"docstring": "Helper function to maintain the max-heap property.",
"function_declaration": "def max_heapify(arr, n, i):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Sorts an array using max-heap.",
"function_declaration": "def max_heap_sort(arr):... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Helper function to maintain the max heap property.\ndef max_heapify(arr, end, i):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if le... | trial_gpt4o_9 | {
"original_instruction": "Heap Sort is a well-known algorithm that sorts an array in-place using the properties of the heap data structure. We have two variations: `max_heap_sort` and `min_heap_sort`, which use max-heap and min-heap respectively to achieve ascending order sorting.\n\n#### Task\nGiven the following p... | 0.677794 | Data_Structure_35518 | 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 | a7cd08fbb61575fc9f1727c31c780a46dab40e80 | 177091341b6670f9f14a531f189b38344d9a779b | |||
v1.0 | complete | Data_Structure | Data_Structure_35426_C | from typing import List
def pancake_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers in ascending order using the Pancake Sort algorithm.
>>> pancake_sort([3, 2, 4, 1])
[1, 2, 3, 4]
>>> pancake_sort([0, -1, 5, 3, 2])
[-1, 0, 2, 3, 5]
>>> pancake_sort([])
[]
>>> panc... | from typing import List
def flip(arr: List[int], k: int) -> None:
"""
Helper function to reverse the order of the first k elements of the array.
"""
arr[:k] = arr[:k][::-1]
def find_max_index(arr: List[int], n: int) -> int:
"""
Helper function to find the index of the maximum element in the ar... | from solution import pancake_sort
def test_pancake_sort_example_1():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
def test_pancake_sort_example_2():
assert pancake_sort([0, -1, 5, 3, 2]) == [-1, 0, 2, 3, 5]
def test_pancake_sort_empty():
assert pancake_sort([]) == []
def test_pancake_sort_single_el... | [
{
"docstring": "Helper function to reverse the order of the first k elements of the array.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Helper function to find the index of the maximum element in the arr[0: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\n\ndef flip(arr: List[int], k: int) -> None:\n \"\"\"\n Reverses the order of the first k elements in the given list.\n \"\"\... | trial_gpt4o_2 | {
"original_instruction": "### Pancake Sorting Assessment Question\n\n#### Scenario\nYou have been hired as an intern at a software company. Your first task is to implement a classic sorting algorithm that sorts a stack of pancakes by size. Specifically, you need to sort arbitrary arrays using the Pancake Sort algori... | 0.774071 | Data_Structure_35426 | C | [
"flip",
"find_max_index",
"pancake_sort"
] | 3 | [
[
"pancake_sort",
"find_max_index"
],
[
"pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e2c83299cf4e55fbdb4a25f175d78f0d8e529a97 | 58b04c8e6cd75a9820e52e5f0c7e797acd0b83b1 | |||
v1.0 | complete | Data_Structure | Data_Structure_35688_C | from typing import List, Tuple
def is_strongly_connected(vertex_count: int, edges: List[Tuple[int, int]]) -> bool:
'''
Determine if the directed graph is strongly connected.
Parameters:
- vertex_count: An integer representing the number of vertices in the graph.
- edges: A list of tuples, where ea... | from typing import List, Tuple
def dfs(graph: List[List[int]], v: int, visited: List[bool]):
"""Depth first search"""
stack = [v]
while stack:
node = stack.pop()
if not visited[node]:
visited[node] = True
for neighbor in graph[node]:
if not visited[ne... | from solution import is_strongly_connected
def test_is_strongly_connected_case_1():
assert is_strongly_connected(5, [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 1)]) == True
def test_is_strongly_connected_case_2():
assert is_strongly_connected(4, [(0, 1), (1, 2), (2, 0), (2, 3)]) == False
def test_is_strongl... | [
{
"docstring": "Depth first search",
"function_declaration": "def dfs(graph, v, visited):",
"function_name": "dfs",
"parameter_list": "(graph, v, visited)"
},
{
"docstring": null,
"function_declaration": "def is_strongly_connected(vertex_count, edges):",
"function_name": "is_strongly... | [
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 collections\nfrom typing import List, Tuple\n\ndef is_strongly_connected(vertex_count: int, edges: List[Tuple[int, int]]) -> bool:\n '''\n Determ... | trial_gpt4o_1 | {
"original_instruction": "In graph theory, a *strongly connected component* (SCC) of a directed graph is a maximal subset of vertices such that every vertex in the subset is reachable from every other vertex in the subset. A graph is said to be *strongly connected* if every vertex is part of a single SCC. Your task ... | 0.526304 | Data_Structure_35688 | C | [
"dfs",
"is_strongly_connected"
] | 2 | [
[
"is_strongly_connected",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 200cef67918acc80a239af01ec5f21f346073d66 | b2c4115765bb71f26cf1e467feb0a6a9e8f9dbf4 | |||
v1.0 | complete | Data_Structure | Data_Structure_35837_C | def optimized_gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor (GCD) of two integers a and b.
Uses the Euclidean algorithm.
Parameters:
a (int): first integer
b (int): second integer
Returns:
int: the GCD of a and b
>>> optimized_gcd(54, 24)
6
>>> optim... | def optimized_gcd(a, b):
"""
Computes the greatest common divisor (GCD) of two integers a and b.
Uses the Euclidean algorithm.
Parameters:
a (int): first integer
b (int): second integer
Returns:
int: the GCD of a and b
"""
while b:
a, b = b, a % b
return abs... | from solution import optimized_gcd, optimized_lcm
def test_optimized_gcd():
assert optimized_gcd(54, 24) == 6
assert optimized_gcd(-54, 24) == 6
assert optimized_gcd(0, 24) == 24
assert optimized_gcd(24, 0) == 24
assert optimized_gcd(101, 103) == 1
def test_optimized_gcd_negatives():
assert op... | [
{
"docstring": "Computes the greatest common divisor (GCD) of two integers a and b.\nUses the Euclidean algorithm.\n\nParameters:\na (int): first integer\nb (int): second integer\n\nReturns:\nint: the GCD of a and b",
"function_declaration": "def optimized_gcd(a, b):",
"function_name": "optimized_gcd",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_gcd(a, b):\n \"\"\"\n Computes the greatest common divisor (GCD) of two integers using the Euclidean algorithm.\n \"\"\"\n if a == 0... | trial_gpt4o_2 | {
"original_instruction": "Optimized GCD and LCM Calculator\n\n#### Context\nYou are a developer tasked with enhancing the performance of a numeric utility library. Your goal is to write highly optimized functions for calculating the greatest common divisor (GCD) and the least common multiple (LCM) of given integers.... | 0.754313 | Data_Structure_35837 | C | [
"optimized_gcd",
"optimized_lcm"
] | 2 | [
[
"optimized_lcm",
"optimized_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c893899ad93c39c0b69d5789aad5676129f93145 | 30d378882a957546abcbb31538844aa5ce92901a | |||
v1.0 | complete | Data_Structure | Data_Structure_36008_C | from typing import List
def find_primes_in_range(m: int, n: int) -> List[int]:
""" Returns a list of all prime numbers in the range [m, n].
>>> find_primes_in_range(1, 10)
[2, 3, 5, 7]
>>> find_primes_in_range(10, 20)
[11, 13, 17, 19]
>>> find_primes_in_range(1, 1)
[]
>>> find_primes_in... | from typing import List
def is_prime(num: int) -> bool:
"""
Helper function to check if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or nu... | from solution import find_primes_in_range
def test_find_primes_in_range_basic():
assert find_primes_in_range(1, 10) == [2, 3, 5, 7]
assert find_primes_in_range(10, 20) == [11, 13, 17, 19]
assert find_primes_in_range(1, 1) == []
assert find_primes_in_range(20, 20) == []
def test_find_primes_in_range_la... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of all prime numbers in the range [m, n].",
"function_declaration": "def find_primes_in_... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(num: int) -> bool:\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n ... | trial_gpt4o_0 | {
"original_instruction": "### Prime Numbers within a Specified Range\n\n#### Scenario\nYou're designing a feature for a cryptographic application that requires frequent checking for prime numbers within large ranges. For optimal performance, you need to implement a solution efficiently finding all prime numbers with... | 0.644694 | Data_Structure_36008 | C | [
"is_prime",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 30ad48cbe13f5037a3def3c565fae43351bf1db0 | dfedd7e8e629c5ba9af9a7837549b79edf4ffbab | |||
v1.0 | complete | Data_Structure | Data_Structure_36007_C | def rotate_in_place(array: list[int], k: int) -> None:
"""Rotate the array in-place to the right by k steps using the array-reversing technique.
>>> array = [1, 2, 3, 4, 5, 6, 7]
>>> k = 3
>>> rotate_in_place(array, k)
>>> array
[5, 6, 7, 1, 2, 3, 4]
"""
pass # implementation goes here
... | def rotate_in_place(array, k):
"""
Rotate the array to the right by k steps in-place using the array-reversing technique.
"""
n = len(array)
k = k % n # In case k is larger than n
reverse(array, 0, n - 1)
reverse(array, 0, k - 1)
reverse(array, k, n - 1)
def reverse(array, start, end):... | from solution import rotate_in_place, rotate_with_slicing
def test_rotate_in_place():
array = [1, 2, 3, 4, 5, 6, 7]
k = 3
rotate_in_place(array, k)
assert array == [5, 6, 7, 1, 2, 3, 4]
def test_rotate_in_place_with_more_steps():
array = [1, 2, 3, 4, 5, 6, 7]
k = 10 # Equivalent to rotating 3... | [
{
"docstring": "Rotate the array to the right by k steps in-place using the array-reversing technique.",
"function_declaration": "def rotate_in_place(array, k):",
"function_name": "rotate_in_place",
"parameter_list": "(array, k)"
},
{
"docstring": null,
"function_declaration": "def rever... | [
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 rotate_in_place(array: list[int], k: int) -> None:\n \"\"\"\n Rotate the array in-place using reversing technique.\n \"\"\"\n n = len(array)\n... | trial_gpt4o_2 | {
"original_instruction": "### Array Rotation Challenge\nYou are tasked with rotating an array of `n` elements to the right by `k` steps. Implement the rotation function in at least two different ways, demonstrating an in-depth understanding of time and space complexity considerations. \n\nYou need to write two funct... | 0.622095 | Data_Structure_36007 | C | [
"rotate_in_place",
"reverse",
"rotate_with_slicing"
] | 3 | [
[
"rotate_in_place",
"reverse"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eb6111af26e9614c83986ae4e5160a69b0835dd3 | 04170a5e3d3a462a7ef7e736b88d5db90ee27c6a | |||
v1.0 | complete | Data_Structure | Data_Structure_35567_C | def merge_sort(arr):
"""Sort an array in ascending order using the merge sort algorithm.
>>> merge_sort([]) == []
True
>>> merge_sort([1]) == [1]
True
>>> merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
True
>>> merge_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
True
>>> merge_sort([3... | def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:])
merge(left, right, arr)
return arr
def merge(left, right, merged):
left_cursor, right_cursor = 0, 0
while left_cursor < len(left) and right_cursor < len(r... | from solution import merge_sort, shuffle_array
def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_array():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_array():... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right, merged):",
"function_name": "merge",
"parameter_list": "(left, right, merged)"
}... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n if len(arr) <= 1:\n return arr\n mid = len(arr) // 2\n left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:])\n ... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort and Array Shuffling\n\n#### Context\nYou're creating a large dataset of records that need to be sorted and later analyzed. The dataset is generated randomly, sorted for specific analyses, and shuffled again for testing purposes.\n\n#### Task\nWrite two functions:\n1. **merge_... | 0.58681 | Data_Structure_35567 | C | [
"merge_sort",
"merge",
"shuffle_array"
] | 3 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b95e4665d6b128de94497b514400d5079a097735 | 6106d87db70ca87b413af0a313c1a92d9308d349 | |||
v1.0 | complete | Data_Structure | Data_Structure_35910_C | from typing import List
def max_flow_solver(capacity: List[List[int]], source: int, sink: int) -> int:
""" Implement a robust maximum flow solver that selects the best algorithm
based on the graph's characteristics.
Args:
capacity (List[List[int]]): A 2D list representing the capacity of each edg... | from typing import List
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 v in range(len(capacity)):
if visited[v] == Fals... | def test_max_flow_solver_no_flow():
capacity = [
[0, 0],
[0, 0]
]
assert max_flow_solver(capacity, 0, 1) == 0
def test_max_flow_solver_simple():
capacity = [
[0, 1],
[0, 0]
]
assert max_flow_solver(capacity, 0, 1) == 1
def test_max_flow_solver_edmonds_karp_s... | [
{
"docstring": null,
"function_declaration": "def bfs(capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def edmonds_karp(capacity, source, sink):",
"function_name": "edmonds... | [
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(capacity, source, sink, parent):\n visited = [False] * len(capacity)\n queue = deque([... | trial_gpt4o_5 | {
"original_instruction": "### Coding Challenge: Implement a Robust Maximum Flow Solver\n\nGiven the implementations of three different maximum flow algorithms (Ford-Fulkerson, Edmonds-Karp, and Dinic's Algorithm), your task is to implement a function which can decide which algorithm to use based on the given graph p... | 0.616692 | Data_Structure_35910 | C | [
"bfs",
"edmonds_karp",
"dinic_bfs",
"dinic_dfs",
"dinics_algorithm",
"graph_density",
"max_flow_solver"
] | 7 | [
[
"dinics_algorithm",
"dinic_bfs"
],
[
"dinics_algorithm",
"dinic_dfs"
],
[
"edmonds_karp",
"bfs"
],
[
"max_flow_solver",
"dinics_algorithm"
],
[
"max_flow_solver",
"edmonds_karp"
],
[
"max_flow_solver",
"graph_density"
]
] | 6 | [] | false | [] | false | pytest | false | [] | true | 4fa7a754e3226d9e802bdcd49b1146dd035870c6 | bc7c25809be3ea9e684de99cd8c190eacc66fa4c | |||
v1.0 | complete | Data_Structure | Data_Structure_36022_C | import random
from sympy import isprime, primerange
def prime_check(num):
"""
Check if the given number is a prime number.
"""
pass
def find_primitive_root(n):
"""
Find primitive roots of 'n'.
"""
pass
def alice_private_key(p):
"""
Generate Alice's private key.
"""
pas... | import random
from sympy import isprime, primerange
def prime_check(num):
"""
Check if the given number is a prime number.
"""
return isprime(num)
def find_primitive_root(n):
"""
Find primitive roots of 'n'.
"""
def gcd(a, b):
while b:
a, b = b, a % b
return... | from solution import prime_check, find_primitive_root, alice_private_key, bob_private_key, alice_public_key, bob_public_key, alice_shared_key, bob_shared_key, diffie_hellman_key_exchange
def test_prime_check():
assert prime_check(23) == True
assert prime_check(24) == False
def test_find_primitive_root():
... | [
{
"docstring": "Check if the given number is a prime number.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Find primitive roots of 'n'.",
"function_declaration": "def find_primitive_root(n):",
"function... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef prime_check(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n ... | trial_gpt4o_1 | {
"original_instruction": "In this assignment, you are required to implement a secure communication setup using the Diffie-Hellman Key Exchange algorithm. Given a large prime number \\( p \\) and its primitive root \\( a \\), Alice and Bob need to securely exchange secret keys over an unsecured channel.\n\nThe algori... | 0.54241 | Data_Structure_36022 | C | [
"prime_check",
"find_primitive_root",
"alice_private_key",
"bob_private_key",
"alice_public_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"diffie_hellman_key_exchange"
] | 9 | [
[
"diffie_hellman_key_exchange",
"alice_private_key"
],
[
"diffie_hellman_key_exchange",
"alice_public_key"
],
[
"diffie_hellman_key_exchange",
"alice_shared_key"
],
[
"diffie_hellman_key_exchange",
"bob_private_key"
],
[
"diffie_hellman_key_exchange",
"bob_pu... | 8 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | d3074ce6f05defa3247374e5357fdc377c098365 | 7b97eb10cda89d26c08db5f6653eb066a3c38ce7 | |||
v1.0 | complete | Data_Structure | Data_Structure_36020_C | import random
def __choose_state(transitions):
"""
Choose the next state based on the given transition probabilities.
Args:
- transitions (dict): A dictionary of states and their corresponding probabilities.
Returns:
- next_state (str): The chosen next state.
"""
# Your implementa... | import random
def __choose_state(transitions):
"""
Choose the next state based on the given transition probabilities.
Args:
- transitions (dict): A dictionary of states and their corresponding probabilities.
Returns:
- next_state (str): The chosen next state.
"""
states = list(tra... | from solution import simulate_user_navigation, __choose_state
# Example chain for tests
chain = {
'Home': {'About': 0.1, 'Products': 0.6, 'Home': 0.3},
'About': {'Home': 0.8, 'Products': 0.2},
'Products': {'Home': 0.6, 'About': 0.1, 'Products': 0.3}
}
def test_choose_state():
transitions = {'Home': 0.... | [
{
"docstring": "Choose the next state based on the given transition probabilities.\n\nArgs:\n- transitions (dict): A dictionary of states and their corresponding probabilities.\n\nReturns:\n- next_state (str): The chosen next state.",
"function_declaration": "def __choose_state(transitions):",
"function... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef __choose_state(transition_dict):\n \"\"\"\n Chooses the next state based on the transition probabilities in `transition_dict`.\n ... | trial_gpt4o_1 | {
"original_instruction": "#### Context:\nYou have been tasked with simulating the random behavior of a user navigating through different pages on a website. The user's navigation pattern can be modeled using a Markov Chain where each page represents a state, and browsing behavior defines transition probabilities fro... | 0.501227 | Data_Structure_36020 | C | [
"__choose_state",
"simulate_user_navigation"
] | 2 | [
[
"simulate_user_navigation",
"__choose_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c52399a511e61491d48908c518e3a4b41221abae | d8e8e666e2f39788a79df44acf924f044924dbd5 | |||
v1.0 | complete | Data_Structure | Data_Structure_35782_C | def custom_base_radix_sort(arr: List[int], base: int) -> List[int]:
""" Sort a list of non-negative integers using the specified base and return the sorted list.
>>> custom_base_radix_sort([170, 45, 75, 90, 802, 24, 2, 66], 10)
[2, 24, 45, 66, 75, 90, 170, 802]
>>> custom_base_radix_sort([13, 1, 7,... | def custom_base_radix_sort(arr, base):
if len(arr) == 0:
return arr
max_value = max(arr)
exp = 1 # Exponent to extract digit
while max_value // exp > 0:
arr = counting_sort_by_digit(arr, exp, base)
exp *= base
return arr
def counting_sort_by_digit(arr, exp, base):... | from solution import custom_base_radix_sort
def test_custom_base_radix_sort_base10():
arr = [170, 45, 75, 90, 802, 24, 2, 66]
base = 10
assert custom_base_radix_sort(arr, base) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_custom_base_radix_sort_base2():
arr = [13, 1, 7, 20, 5]
base = 2
assert... | [
{
"docstring": null,
"function_declaration": "def custom_base_radix_sort(arr, base):",
"function_name": "custom_base_radix_sort",
"parameter_list": "(arr, base)"
},
{
"docstring": null,
"function_declaration": "def counting_sort_by_digit(arr, exp, base):",
"function_name": "counting_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef custom_base_radix_sort(arr: List[int], base: int) -> List[int]:\n if not arr:\n return arr\n\n def counting_sort(a... | trial_gpt4o_2 | {
"original_instruction": "### Radix Sort with Custom Base\n\n**Context**: You have been tasked with implementing a version of the radix sort algorithm that sorts an array of non-negative integers but allows for the digits to be interpreted in any arbitrary base `b` (2-10). \n\n**Objective**: Write a function `custom... | 0.633367 | Data_Structure_35782 | C | [
"custom_base_radix_sort",
"counting_sort_by_digit"
] | 2 | [
[
"custom_base_radix_sort",
"counting_sort_by_digit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2b256fab3e1621d9fdb6b6b78b9afb27f3d60b44 | fccc1c5305b7e96c8115d0c8770577f192933856 | |||
v1.0 | complete | Data_Structure | Data_Structure_36343_C | from typing import List
def bucket_sort(arr: List[float]) -> List[float]:
"""
Perform bucket sort on an array of floating-point numbers in the range [0, 1].
>>> bucket_sort([0.25, 0.5, 0.75, 0.1, 0.9])
[0.1, 0.25, 0.5, 0.75, 0.9]
>>> bucket_sort([0.1, 0.01, 0.99, 0.33, 0.81, 0.78])
[0.01, 0.1, ... | from typing import List
def insertion_sort(arr: List[float]) -> None:
"""
A simple insertion sort implementation used for sorting individual buckets.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
... | from solution import bucket_sort
def test_bucket_sort_empty():
assert bucket_sort([]) == []
def test_bucket_sort_single_element():
assert bucket_sort([0.4]) == [0.4]
def test_bucket_sort_already_sorted():
assert bucket_sort([0.1, 0.2, 0.3, 0.4, 0.5]) == [0.1, 0.2, 0.3, 0.4, 0.5]
def test_bucket_sort_rev... | [
{
"docstring": "A simple insertion sort implementation used for sorting individual buckets.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Perform bucket sort on an array of floating-point numbers in the r... | [
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 insertion_sort(bucket: List[float]) -> List[float]:\n \"\"\"\n Helper function to sort individual buckets using insertion... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with implementing the Bucket Sort algorithm to sort an array of floating-point numbers within a range from 0 to 1 (inclusive). Your implementation should also address possible optimizations and edge cases.\n\n### Requirements\n\n1. Implement `bucket_sort(arr: List[float]) -> ... | 0.659402 | Data_Structure_36343 | C | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e2c7c71141cc151bbc54932a33e23cd8e9631f3f | f91a353d522771ce3ce715fd42cc794663a50dee | |||
v1.0 | complete | Data_Structure | Data_Structure_35188_C | import random
from math import gcd
from typing import List
def prime_check(num: int) -> bool:
""" Check if a number is prime.
Args:
num: an integer to check for primality.
Returns:
True if the number is prime, False otherwise.
"""
pass
def euler_totient(n: int) -> int:
""" Calc... | import random
from math import gcd
# Function to check if a number is prime
def prime_check(num: int) -> bool:
if num <= 1:
return False
if num == 2 or 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 nu... | from solution import (
prime_check, euler_totient, find_order, find_primitive_root,
alice_private_key, alice_public_key, bob_private_key, bob_public_key,
alice_shared_key, bob_shared_key, diffie_hellman_key_exchange
)
def test_prime_check():
assert prime_check(2) == True
assert prime_check(3) == Tr... | [
{
"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 random\n\ndef prime_check(num: int) -> bool:\n \"\"\"\n Checks if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if ... | trial_gpt4o_2 | {
"original_instruction": "### Diffie-Hellman Key Exchange Function and Testing\n\n#### Introduction\nAlice and Bob want to establish a secure communication channel. They will use the Diffie-Hellman Key Exchange protocol to share a secret key. Your task is to complete the implementation of this protocol, considering ... | 0.576584 | Data_Structure_35188 | C | [
"prime_check",
"euler_totient",
"find_order",
"find_primitive_root",
"alice_private_key",
"alice_public_key",
"bob_private_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"diffie_hellman_key_exchange"
] | 11 | [
[
"diffie_hellman_key_exchange",
"alice_private_key"
],
[
"diffie_hellman_key_exchange",
"alice_public_key"
],
[
"diffie_hellman_key_exchange",
"alice_shared_key"
],
[
"diffie_hellman_key_exchange",
"bob_private_key"
],
[
"diffie_hellman_key_exchange",
"bob_pu... | 11 | [] | false | [] | false | pytest | true | [] | true | 7a16f97c7634cad72b820f493e069776b67bd71b | 56b60a6d7e33c2a46f8f0853e50b194ca470433f | |||
v1.0 | complete | Data_Structure | Data_Structure_35581_C | def constrained_max_flow(capacity: List[List[int]], source: int, sink: int, intermediate: int) -> int:
"""Compute the maximum flow from a given source to a sink in a flow network, with the constraint that a certain intermediate node must be visited exactly once.
Args:
capacity (List[List[int]]): A ... | from collections import deque
def bfs(capacity, source, sink, parent):
visited = [False] * len(capacity)
queue = deque([source])
visited[source] = True
while queue:
current = queue.popleft()
for next in range(len(capacity)):
if not visited[next] and capacity[current][n... | import pytest
from solution import constrained_max_flow
def test_example_case():
capacity = [
[0, 10, 10, 0],
[0, 0, 1, 10],
[0, 0, 0, 10],
[0, 0, 0, 0]
]
source = 0
sink = 3
intermediate = 2
assert constrained_max_flow(capacity, source, sink, intermediate) == 10... | [
{
"docstring": null,
"function_declaration": "def bfs(capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def edmonds_karp(capacity, source, sink):",
"function_name": "edmonds... | [
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\nfrom collections import deque\n\ndef bfs(rGraph, s, t, parent):\n visited = [False] * len(rGraph)\n queue = deque([s])\n vis... | trial_gpt4o_2 | {
"original_instruction": "### Problem: Maximum Flow with Intermediate Constraints\n\nYou are provided with a flow network represented by a capacity matrix. Compute the maximum flow from a given source to a sink using the algorithms discussed. Additionally, incorporate an intermediate constraint where a certain node ... | 0.577675 | Data_Structure_35581 | C | [
"bfs",
"edmonds_karp",
"constrained_max_flow"
] | 3 | [
[
"constrained_max_flow",
"edmonds_karp"
],
[
"edmonds_karp",
"bfs"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | edb07d6fe58fc36fbf8e30fdb63a51bbbf5d8a90 | 496d9c7e12e8c816c9584d587ab29239d076ef29 | |||
v1.0 | complete | Data_Structure | Data_Structure_36153_C | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Check if the given list is sorted in ascending order.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr: List[int]) -> List[int]:
"""
Perf... | import random
def is_sorted(arr):
"""
Check if the given list is sorted in ascending order.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr):
"""
Perform a Bogo Sort on the given list of integers.
Shuffle the list... | from solution import bogo_sort
def test_bogo_sort_single_element():
assert bogo_sort([5]) == [5]
def test_bogo_sort_already_sorted():
assert bogo_sort([1, 2, 3]) == [1, 2, 3]
def test_bogo_sort_reverse_order():
assert bogo_sort([3, 2, 1]) == [1, 2, 3]
def test_bogo_sort_unsorted():
assert bogo_sort(... | [
{
"docstring": "Check if the given list is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Perform a Bogo Sort on the given list of integers.\nShuffle the list randomly until it is sorted.\... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef bogo_sort(arr):\n \"\"\"\n Sorts a list of integers using the Bogo Sort algorithm.\n The function repeatedly shuffles the list u... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement a Bogo Sort\n\n#### Context\nBogo Sort is a very inefficient sorting algorithm that repeatedly shuffles an array until it is sorted. Though not useful for actual sorting needs, it serves as a good exercise in understanding sorting algorithms and complexity.\n\n#### T... | 0.614163 | Data_Structure_36153 | C | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 88b26f0fb22f4fe8d3ff785a91a8ed33fe5869b5 | b080a5afb79c021ca3795c94c7d8693b6c86c1aa | |||
v1.0 | complete | Data_Structure | Data_Structure_36011_C | from typing import List
def radix_sort(arr: List[int], simulation: bool=False) -> List[int]:
""" Sorts a list of non-negative integers using the LSD Radix Sort algorithm.
The list can be very large, so the algorithm is efficient in terms of both time and space complexity.
Args:
arr (List[int]): A ... | def counting_sort(arr, exp, simulation):
n = len(arr)
output = [0] * n # the output array elements that will have sorted arr
count = [0] * 10 # initialize count array as 0
# store count of occurrences in count[]
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
... | from solution import radix_sort
def test_radix_sort_standard_case():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_empty_list():
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort([5]) == [5]
def test_radix_... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp, simulation):\n n = len(arr)\n output = [0] * n # the output array elements that will have sorted arr\n count = [0] * 10 ... | trial_gpt4o_0 | {
"original_instruction": "### Question: Implement LSD Radix Sort\n\n**Context**:\nYou are given a list of non-negative integers that represents a sequence of priorities in a task management system. Your task is to sort this list in ascending order using the LSD (Least Significant Digit) variant of Radix Sort. The li... | 0.698464 | Data_Structure_36011 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6700530f25f0063d2323d0101108025bc4a6386a | a8aaa59ee9a08ec85f673c354c475f1443fc559b | |||
v1.0 | complete | Data_Structure | Data_Structure_36392_C | def vector_to_index_value_list(vector: list[float]) -> list[tuple[int, float]]:
"""
Converts a vector to a list of index-value pairs, omitting zero values.
Parameters:
vector (list[float]): The input sparse vector.
Returns:
list[tuple[int, float]]: A list of (index, value) pairs.
"... | def vector_to_index_value_list(vector):
"""
Converts a vector to a list of index-value pairs, omitting zero values.
Parameters:
vector (list[float]): The input sparse vector.
Returns:
list[tuple[int, float]]: A list of (index, value) pairs.
"""
return [(i, value) for i, value i... | import pytest
from solution import vector_to_index_value_list, dot_product, handle_zero_vectors
def test_vector_to_index_value_list():
assert vector_to_index_value_list([1.0, 0.0, 3.0]) == [(0, 1.0), (2, 3.0)]
assert vector_to_index_value_list([0.0, 0.0, 0.0]) == []
assert vector_to_index_value_list([]) ==... | [
{
"docstring": "Converts a vector to a list of index-value pairs, omitting zero values.\n\nParameters:\nvector (list[float]): The input sparse vector.\n\nReturns:\nlist[tuple[int, float]]: A list of (index, value) pairs.",
"function_declaration": "def vector_to_index_value_list(vector):",
"function_name... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def vector_to_index_value_list(vector):\n \"\"\"\n Converts a vector to a list of index-value pairs, omitting zero values.\n \n Parameters:\n v... | trial_gpt4o_2 | {
"original_instruction": "You are provided with a data storage structure and algorithm designed for efficiently handling sparse vectors. Sparse vectors mainly contain zero values, and only a few elements are non-zero. Your task is to improve upon and extend the existing implementation. You will need to:\n\n1. Implem... | 0.511388 | Data_Structure_36392 | C | [
"vector_to_index_value_list",
"dot_product",
"handle_zero_vectors"
] | 3 | [
[
"handle_zero_vectors",
"vector_to_index_value_list"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 978f05d05fc5e9ea28c3d93ee1335e3040d1bfe3 | 8c0201f7815c0f3d3c62be6b69400eccc344356e | |||
v1.0 | complete | Data_Structure | Data_Structure_36527_C | def optimized_stoogesort(arr: list, l: int, h: int) -> None:
""" Enhanced version of Stooge Sort that includes optimization for small arrays using
insertion sort and handles non-numeric values. The function modifies the list in place.
Args:
arr (list): The list to be sorted. It can contain integer... | def insertion_sort(arr, l, h):
for i in range(l+1, h+1):
key = arr[i]
j = i-1
while j >= l and arr[j] > key:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
def optimized_stoogesort(arr, l, h):
if l >= h:
return
if arr[l] > arr[h]:
arr[l]... | from solution import optimized_stoogesort
def test_optimized_stoogesort_integers():
arr = [5, 2, 8, 3, 1]
optimized_stoogesort(arr, 0, len(arr)-1)
assert arr == [1, 2, 3, 5, 8]
def test_optimized_stoogesort_sorted_integers():
arr = [1, 2, 3, 4, 5]
optimized_stoogesort(arr, 0, len(arr)-1)
asser... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, l, h):",
"function_name": "insertion_sort",
"parameter_list": "(arr, l, h)"
},
{
"docstring": null,
"function_declaration": "def optimized_stoogesort(arr, l, h):",
"function_name": "optimized_stoogesort",
"para... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_stoogesort(arr, l, h):\n \"\"\"\n Enhanced Stooge Sort with optimizations for small arrays and edge case handling.\n \n :param arr: ... | trial_gpt4o_2 | {
"original_instruction": "### Stooge Sort Enhancement and Analysis\n\n#### Problem Statement\n\nYou are provided with the Stooge Sort algorithm. Although it is known for its inefficiency, your task is to write an enhanced version of Stooge Sort that includes:\n1. **Optimization for small arrays**: If the length of t... | 0.580993 | Data_Structure_36527 | C | [
"insertion_sort",
"optimized_stoogesort"
] | 2 | [
[
"optimized_stoogesort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ec7bd61b173ec73a8624635cf97bd316aee9ce4b | b603b365a8f48b222ce481ea25ac081053f9dbc0 | |||
v1.0 | complete | Data_Structure | Data_Structure_36370_C | def merge_sort(arr):
"""
Sorts the input array using Merge Sort.
Parameters:
arr (list of int): The array to sort.
Returns:
list of int: The sorted array.
"""
pass
def merge(left, right):
"""
Merges two sorted arrays into one sorted array.
Parameters:
left... | def merge_sort(arr):
"""
Sorts the input array using Merge Sort.
Parameters:
arr (list of int): The array to sort.
Returns:
list of int: The sorted array.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(a... | from solution import merge_sort
def test_merge_sort_empty():
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_sorted():
assert merge_sort([1, 2, 3, 4, 5]) == [1,... | [
{
"docstring": "Sorts the input array using Merge Sort.\n\nParameters:\narr (list of int): The array to sort.\n\nReturns:\nlist of int: The sorted array.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two s... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts the input array using Merge Sort.\n \n Parameters:\n arr (list of int): The array to sort.\n \n Ret... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Implementation\n\nYou are tasked with implementing the Merge Sort algorithm. Merge Sort is a classic sorting algorithm that follows the divide-and-conquer strategy to sort an array. Your goal is to write a function `merge_sort` that sorts an array of integers in non-decreasin... | 0.668219 | Data_Structure_36370 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 86b38627a9efdb4d9c3c40f2b4284fd503cd9b05 | 796a401f2c81414244a1eae46ce837206bdf6d3e | |||
v1.0 | complete | Data_Structure | Data_Structure_36578_C | def bitonic_sort_non_power_of_two(arr, reverse=False):
""" Implement Bitonic Sorting for non-power of two arrays.
Pad the array to the next power of two, sort using Bitonic Sort,
and then return only the sorted elements corresponding to the original array size.
>>> bitonic_sort_non_power_of_two([3, 7, ... | def next_power_of_two(x):
return 1 if x == 0 else 2**(x - 1).bit_length()
def bitonic_sort(arr, up):
def compare_and_swap(arr, i, j, up):
if (arr[i] > arr[j]) == up:
arr[i], arr[j] = arr[j], arr[i]
def bitonic_merge(arr, low, cnt, up):
if cnt > 1:
mid = cnt // 2
... | from solution import bitonic_sort_non_power_of_two
def test_bitonic_sort_non_power_of_two():
assert bitonic_sort_non_power_of_two([3, 7, 8, 5, 2, 1, 9, 6], False) == [1, 2, 3, 5, 6, 7, 8, 9]
assert bitonic_sort_non_power_of_two([3, 7, 8, 5, 2, 1], True) == [8, 7, 5, 3, 2, 1]
assert bitonic_sort_non_power_o... | [
{
"docstring": null,
"function_declaration": "def next_power_of_two(x):",
"function_name": "next_power_of_two",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def bitonic_sort(arr, up):",
"function_name": "bitonic_sort",
"parameter_list": "(arr, up)"
}... | [
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\n\ndef bitonic_sort_non_power_of_two(arr, reverse=False):\n def next_power_of_two(x):\n return 1 << (x - 1).bit_length()\n \n def ... | trial_gpt4o_2 | {
"original_instruction": "Implement Bitonic Sorting for Non-Power of Two Arrays\n\n#### Background:\nYou are given an enhancement to the traditional Bitonic Sort algorithm which can handle arrays whose sizes are not powers of two. The objective is to pad the array to the next power of two, perform Bitonic Sort, and ... | 0.659481 | Data_Structure_36578 | C | [
"next_power_of_two",
"bitonic_sort",
"bitonic_sort_non_power_of_two"
] | 3 | [
[
"bitonic_sort_non_power_of_two",
"bitonic_sort"
],
[
"bitonic_sort_non_power_of_two",
"next_power_of_two"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c945d9bfcddb1d1a0022b3820f574069fb1c185b | 33c0bab5d77cc2a1f2fbda5911098b66d316cd24 | |||
v1.0 | complete | Data_Structure | Data_Structure_36026_C | def int_to_base(num, base):
"""
Converts an integer to a given base.
Arguments:
num : int : The integer to convert.
base : int : The base to convert to, between 2 and 36 inclusive.
Returns:
str : The string representation of the number in the given base.
Example:
>>> int_to_base(1... | def int_to_base(num, base):
"""Converts an integer to a given base and returns the string representation."""
if num == 0:
return "0"
digits = []
is_negative = False
if num < 0:
is_negative = True
num = -num
while num > 0:
digits.append(int(num % base))
... | def test_extended_base_conversion():
assert extended_base_conversion("-1A", 16, 8) == '-32'
assert extended_base_conversion("101", 2, 10) == '5'
assert extended_base_conversion("Z", 36, 10) == '35'
assert extended_base_conversion("35", 10, 36) == 'Z'
assert extended_base_conversion("0", 10, 2) == '0... | [
{
"docstring": "Converts an integer to a given base and returns the string representation.",
"function_declaration": "def int_to_base(num, base):",
"function_name": "int_to_base",
"parameter_list": "(num, base)"
},
{
"docstring": "Converts a string representation of a number in a given base ... | [
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 int_to_base(num, base):\n \"\"\"Convert an integer to its string representation in a given base.\"\"\"\n if num == 0:\n return \"0\"\n dig... | trial_gpt4o_2 | {
"original_instruction": "Extended Base Conversion\n\nYou are working on a software that needs to frequently convert numbers between various bases. You are provided with two fundamental functions for base conversion – `int_to_base` and `base_to_int`. Now, you need to extend these functionalities to handle some addit... | 0.846161 | Data_Structure_36026 | C | [
"int_to_base",
"base_to_int",
"extended_base_conversion"
] | 3 | [
[
"extended_base_conversion",
"base_to_int"
],
[
"extended_base_conversion",
"int_to_base"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | e561c219ee3296147b2710ceb32c2c429cd66dda | 7b7bc0ea6cfa19784ba8ec468fcd3d32f8383280 | |||
v1.0 | complete | Data_Structure | Data_Structure_36264_C | from typing import List
def binary_search(array: List[int], val: int) -> int:
"""
Given a sorted array and a target value, return the index if the target is
found. If not, return the index where it would be if it were inserted in order.
:param array: List[int]
:param val: int
:return: int
... | def binary_search(array, val):
"""
Given a sorted array and a target value, return the index if the target is
found. If not, return the index where it would be if it were inserted in order.
:param array: List[int]
:param val: int
:return: int
"""
low, high = 0, len(array) - 1
while ... | from solution import binary_search, insertion_sort_with_binary_search
def test_binary_search():
assert binary_search([1, 2, 3, 4, 5], 3) == 2
assert binary_search([1, 2, 3, 4, 5], 0) == 0
assert binary_search([1, 2, 3, 4, 5], 6) == 5
assert binary_search([1, 2, 3, 4, 5], 4) == 3
assert binary_searc... | [
{
"docstring": "Given a sorted array and a target value, return the index if the target is\nfound. If not, return the index where it would be if it were inserted in order.\n\n:param array: List[int]\n:param val: int\n:return: int",
"function_declaration": "def binary_search(array, val):",
"function_name... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binary_search(array, val):\n \"\"\"\n Given a sorted array and a target value, return the index if the target is \n found. If not, return the ind... | trial_gpt4o_2 | {
"original_instruction": "#### Task\nImplement an insertion sort algorithm for a list of integers and use a binary search function to determine the correct position for each element during the insertion process. This will help improve the efficiency of your insertion sort.\n\n#### Scenario\nYou are given a list of g... | 0.632743 | Data_Structure_36264 | C | [
"binary_search",
"insertion_sort_with_binary_search"
] | 2 | [
[
"insertion_sort_with_binary_search",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ecd43f55fd0abd252a1d8e23582fdd124d6863f6 | ac511a57569988ff2dfbc3953e739aa7c999d3a9 | |||
v1.0 | complete | Data_Structure | Data_Structure_36627_C | from typing import List, Optional
def verify_hermitian_positive_definite(matrix: List[List[float]]) -> bool:
"""
Verify if the given matrix is Hermitian positive-definite.
Args:
matrix (List[List[float]]): A square matrix
Returns:
bool: True if the matrix is Hermitian positive-definit... | import numpy as np
def verify_hermitian_positive_definite(matrix):
"""
Verify if the given matrix is Hermitian positive-definite.
Parameters:
matrix (List[List[float]]): A square matrix
Returns:
bool: True if the matrix is Hermitian positive-definite, False otherwise
"""
A = n... | from solution import verify_hermitian_positive_definite, cholesky_decomposition
def test_verify_hermitian_positive_definite():
assert verify_hermitian_positive_definite([[4, 12, -16], [12, 37, -43], [-16, -43, 98]]) == True
assert verify_hermitian_positive_definite([[1, 1], [2, 2]]) == False
assert verify_... | [
{
"docstring": "Verify if the given matrix is Hermitian positive-definite.\n\nParameters:\nmatrix (List[List[float]]): A square matrix\n\nReturns:\nbool: True if the matrix is Hermitian positive-definite, False otherwise",
"function_declaration": "def verify_hermitian_positive_definite(matrix):",
"funct... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom typing import List, Optional\n\ndef verify_hermitian_positive_definite(matrix: List[List[float]]) -> bool:\n \"\"\"\n Verifies ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Cholesky Decomposition Verification and Application\n\n#### Background:\nCholesky decomposition is a method in numerical linear algebra that decomposes a given Hermitian positive-definite matrix \\( A \\) into the product of a lower triangular matrix \\( V \\) and its conjugat... | 0.524091 | Data_Structure_36627 | C | [
"verify_hermitian_positive_definite",
"cholesky_decomposition"
] | 2 | [
[
"cholesky_decomposition",
"verify_hermitian_positive_definite"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | c7cf1d128690b301dcef4d189ef57bb455abfe70 | a398b622e3ed6698603621de2197e3b70e00e03f | |||
v1.0 | complete | Data_Structure | Data_Structure_35786_C | import random
def generate_key(k, seed=None):
"""
Generate RSA public and private keys.
Args:
k : int : Number of bits in the modulus 'n'
Returns:
(n, e, d) : Tuple of integers representing the keys.
"""
# Implementation here
def modinv(a, m):
"""
Calculate the modular inverse... | import random
from sympy import isprime, mod_inverse
def generate_key(k, seed=None):
if seed:
random.seed(seed)
def get_prime(bits):
while True:
num = random.getrandbits(bits)
if isprime(num):
return num
e = 65537
half_bits = k // 2
... | from solution import generate_key, encrypt, decrypt
def test_key_generation():
n, e, d = generate_key(32)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert n > 0
assert e > 0
assert d > 0
def test_encrypt_decrypt():
k = 32
data = 42
n, e, d = ... | [
{
"docstring": null,
"function_declaration": "def generate_key(k, seed=None):",
"function_name": "generate_key",
"parameter_list": "(k, seed=None)"
},
{
"docstring": null,
"function_declaration": "def modinv(a, m):",
"function_name": "modinv",
"parameter_list": "(a, 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 random\nfrom sympy import isprime, mod_inverse\n\ndef generate_key(k, seed=None):\n if seed:\n random.seed(seed)\n \n def get_prime... | trial_gpt4o_0 | {
"original_instruction": "### Question\n\n#### Problem Statement\nYou are asked to implement a simple RSA encryption system. Your program will generate RSA keys, encrypt a message using the public key, and decrypt it using the private key. You are provided with template functions, and your task is to complete them, ... | 0.748675 | Data_Structure_35786 | C | [
"generate_key",
"modinv",
"egcd",
"encrypt",
"decrypt"
] | 5 | [
[
"modinv",
"egcd"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 492dec7767822bf7b3db596742495ec61c611cd2 | 6f18c59f1eece4fa51bfb365c29a2f7d75895fcf | |||
v1.0 | complete | Data_Structure | Data_Structure_36645_C | class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def find_intersection(h1: Node, h2: Node) -> Node:
"""
Find the node at which two singly linked lists intersect.
If the two linked lists do not intersect, return None.
>>> a1 = Node(1)
>>... | class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def get_length(head: Node) -> int:
length = 0
current = head
while current:
length += 1
current = current.next
return length
def find_intersection(h1: Node, h2: Node) -> Node:
if n... | import pytest
from solution import Node, find_intersection
def test_find_intersection_case1():
a1 = Node(1)
b1 = Node(3)
c1 = Node(5)
d = Node(7)
e = Node(9)
f = Node(11)
a2 = Node(2)
b2 = Node(4)
c2 = Node(6)
a1.next = b1
b1.next = c1
c1.next = d
a2.next = b2
... | [] | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef get_length(head: Node... | trial_gpt4o_1 | {
"original_instruction": "### Intersection of Two Linked Lists\n\nYou are tasked with implementing a function to find the node at which two singly linked lists intersect. Given the following interface and definition for a Node, implement the function `find_intersection(h1, h2)` that returns the intersecting node. If... | 0.514859 | Data_Structure_36645 | C | [
"get_length",
"find_intersection"
] | 2 | [
[
"find_intersection",
"get_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | d4bb651dd6f02171b36f0d13c4829a291cf2b181 | 0cf3e3d64e8b820ba09ab924b5796c9788513aa1 | |||
v1.0 | complete | Data_Structure | Data_Structure_36537_C | import heapq
from typing import List, Tuple
def distance(point: Tuple[int, int], origin: Tuple[int, int] = (0, 0)) -> int:
return (point[0] - origin[0])**2 + (point[1] - origin[1])**2
def k_closest_restaurants(
restaurants: List[Tuple[int, int]],
k: int,
origin: Tuple[int, int] = (0, 0)
) -> List[Tu... | import heapq
def distance(point, origin=(0, 0)):
return (point[0] - origin[0])**2 + (point[1] - origin[1])**2
def k_closest_restaurants(restaurants, k, origin=(0, 0)):
"""
Finds the k closest restaurants to the given origin.
:param restaurants: List of tuples, each representing the coordinates (x... | from solution import k_closest_restaurants
def test_k_closest_basic():
restaurants = [(1, 2), (2, 3), (3, 4), (1, 1)]
k = 2
origin = (0, 0)
result = k_closest_restaurants(restaurants, k, origin)
assert set(result) == set([(1, 2), (1, 1)]) # order doesn't matter
def test_k_equals_restaurant_count(... | [
{
"docstring": null,
"function_declaration": "def distance(point, origin=(0, 0)):",
"function_name": "distance",
"parameter_list": "(point, origin=(0, 0))"
},
{
"docstring": "Finds the k closest restaurants to the given origin.\n\n:param restaurants: List of tuples, each representing the coo... | [
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 heapq\n\ndef distance(point, origin=(0, 0)):\n return (point[0] - origin[0])**2 + (point[1] - origin[1])**2\n\ndef k_closest_restaurants(restaurants... | trial_gpt4o_2 | {
"original_instruction": "#### Scenario:\nYou are working on a navigation system that helps users find the nearest restaurants around them. To build this feature, you need to write a function that finds the k closest restaurants (represented as points) to a given user location (origin).\n\n#### Function Specificatio... | 0.604958 | Data_Structure_36537 | C | [
"distance",
"k_closest_restaurants"
] | 2 | [
[
"k_closest_restaurants",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 44d3ca12c0f235f37210ecabca238a89ce147909 | ec41f69a55d8732bc4ba38a09f7222084aa54c22 | |||
v1.0 | complete | Data_Structure | Data_Structure_35735_C | def max_flow(capacity, source, sink):
"""
Compute the maximum flow from the source node to the sink node in a directed network graph.
Parameters:
capacity (List[List[int]]): The capacity matrix of the graph where capacity[i][j]
represents the capacity of the edge fr... | from collections import deque
def bfs(capacity, source, sink, parent):
"""
Perform BFS to find a path from source to sink with available capacity.
Returns True if a path is found and False otherwise.
"""
visited = [False] * len(capacity)
queue = deque([source])
visited[source] = True
... | def test_max_flow_simple_case():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert max_flow(capacity, source, sink) == 23
def test_max... | [
{
"docstring": "Perform BFS to find a path from source to sink with available capacity.\nReturns True if a path is found and False otherwise.",
"function_declaration": "def bfs(capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, source, sink, parent)"
},
{
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(capacity, source, sink, parent):\n visited = [False] * len(capacity)\n queue = deque([source])\n visited[sou... | trial_gpt4o_2 | {
"original_instruction": "You are given a directed network graph where each edge has a positive integer capacity. Your task is to compute the maximum flow from the source node to the sink node using one of the algorithms discussed: Ford-Fulkerson, Edmonds-Karp, or Dinic's algorithm.\n\n### Input:\n- The graph is rep... | 0.562549 | Data_Structure_35735 | C | [
"bfs",
"max_flow"
] | 2 | [
[
"max_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 8ef5d8b1f4b8f7ed659369e3448d8dbf69e2a918 | ac54cb0f0e6c2fa9cf731e7287b1321ee76be55f | |||
v1.0 | complete | Data_Structure | Data_Structure_36332_C | from typing import List, Optional
import math
def insertion_sort(arr: List[float]) -> List[float]:
for i in range(1, len(arr)):
j = i - 1
key = arr[i]
while arr[j] > key and j >= 0:
arr[j+1] = arr[j]
j = j - 1
arr[j + 1] = key
return arr
def dynamic_buck... | from typing import List, Optional
import math
def insertion_sort(arr: List[float]) -> List[float]:
for i in range(1, len(arr)):
j = i - 1
key = arr[i]
while arr[j] > key and j >= 0:
arr[j+1] = arr[j]
j = j - 1
arr[j + 1] = key
return arr
def dynamic_buck... | from solution import dynamic_bucket_sort
def test_dynamic_bucket_sort_even_distribution():
assert dynamic_bucket_sort([0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]) == [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
def test_dynamic_bucket_sort_single_element():
assert dynamic_buck... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def dynamic_bucket_sort(arr, num_buckets=None):",
"function_name": "dynamic_bucket_sort",
"parame... | [
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, Optional\nimport math\n\ndef insertion_sort(arr: List[float]) -> List[float]:\n \"\"\"\n Sorts a list using the insertion sort ... | trial_gpt4o_2 | {
"original_instruction": "### Bucket Sort with Flexible Bucket Management\n\n**Scenario**:\nYou are provided with an array of floating-point numbers representing scores ranging from `[0.0, 1.0)` for a programming competition. Your task is to sort the scores efficiently using Bucket Sort. To enhance flexibility and e... | 0.5486 | Data_Structure_36332 | C | [
"insertion_sort",
"dynamic_bucket_sort"
] | 2 | [
[
"dynamic_bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b4525a3d59779388c9fb2c4c9ac4c3c9495ee254 | 9ab7ff76745554a2e9c0663ace75756de8ff6717 | |||
v1.0 | complete | Data_Structure | Data_Structure_36561_C | import math
def gcd(a, b):
""" Compute the greatest common divisor of a and 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 % n == 1.
If gcd(a, n) != 1, return -1.
>>> find_order(2, 5)
4
... | 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 % n == 1.
If gcd(a, n) != 1, return -1.
"""
if gcd(a, n) != 1:
return -1
k = 1
power = a % n
while power ... | from solution import find_order
def test_find_order():
assert find_order(2, 5) == 4 # 2^4 % 5 == 1
assert find_order(3, 7) == 6 # 3^6 % 7 == 1
assert find_order(2, 4) == -1 # gcd(2, 4) != 1
assert find_order(10, 1) == -1 # 10 > 1 is out of constraints
assert find_order(5, 9) == 6 # 5^6 % 9 == ... | [
{
"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 % n == 1.\nIf gcd(a, n) != 1, return -1.",
"function_declaration": "def find_order(a, n):",
"functi... | [
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 find_order(a: int, n: int) -> int:\n \"\"\"\n Finds the smallest positive integer k such that a^k ≡ 1 (mod n).\n If no such k exists, returns -1.... | trial_gpt4o_3 | {
"original_instruction": "### Question\n\n**Order Finding Algorithm**\n\nYou are given a positive integer \\( n \\) and another integer \\( a \\) such that \\( \\text{gcd}(a, n) = 1 \\). Your task is to implement a function to find the smallest positive integer \\( k \\) (known as the order of \\( a \\) modulo \\( n... | 0.653273 | Data_Structure_36561 | C | [
"gcd",
"find_order"
] | 2 | [
[
"find_order",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f604a6bd356b76f073abc6678e2ea9c20590653e | f5eb4dbaabc104c96dbf6c7228e4c84c4b76be4c | |||
v1.0 | complete | Data_Structure | Data_Structure_36436_C | def construct_tree(pre: list, post: list, size: int) -> list:
"""
Constructs the Full Binary Tree and returns its inorder traversal.
Parameters:
pre (list) - List of integers representing preorder traversal.
post (list) - List of integers representing postorder traversal.
size (int) ... | class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def build_tree_util(pre, post, preIndex, l, h, size, postIndexMap):
# Base case
if preIndex[0] >= size or l > h:
return None
# The first node in preorder traversal is the root. So tak... | from solution import construct_tree
def test_construct_tree_simple():
pre = [1, 2, 4, 5, 3, 6, 7]
post = [4, 5, 2, 6, 7, 3, 1]
size = len(pre)
assert construct_tree(pre, post, size) == [4, 2, 5, 1, 6, 3, 7]
def test_construct_tree_empty():
pre = []
post = []
size = len(pre)
assert cons... | [] | [
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 construct_tree(pre, post, size):\n \"\"\"\n Constructs the Full Binary Tree and returns its inorder traversal.\n Parameters:\n pre (list) ... | trial_gpt4o_1 | {
"original_instruction": "### Question: Construct and Verify Full Binary Tree from Traversal Arrays\n\nYou are given arrays representing preorder and postorder traversal of a Full Binary Tree (a tree where every node has either 0 or 2 children). Your task is to construct the binary tree from these traversal arrays a... | 0.557102 | Data_Structure_36436 | C | [
"build_tree_util",
"build_tree",
"inorder_traversal",
"construct_tree"
] | 4 | [
[
"build_tree",
"build_tree_util"
],
[
"construct_tree",
"build_tree"
],
[
"construct_tree",
"inorder_traversal"
]
] | 3 | [] | false | [
"Node"
] | true | pytest | true | [] | true | fac09f16e796687e68690fcd3850a94f3c222230 | 1b8e0c141becd6dc729d031dd1eee0e63f9730db | |||
v1.0 | complete | Data_Structure | Data_Structure_36307_C | from typing import List
def find_median(arr: List[int]) -> float:
"""
Build a function that utilizes both Max and Min Heap Sort to find the median of an unsorted list of integers, `arr`.
If the list length is even, the median is the average of the two middle numbers after sorting.
>>> find_median([... | from typing import List
def find_median(arr: List[int]) -> float:
if not arr:
raise ValueError("The array must not be empty")
arr.sort()
n = len(arr)
if n % 2 == 1:
return float(arr[n // 2])
else:
return (arr[(n // 2) - 1] + arr[n // 2]) / 2.0
def max_heapify(arr,... | from solution import find_median, max_heap_sort, min_heap_sort
def test_find_median_odd_length():
assert find_median([7, 1, 3, 5]) == 4.0
def test_find_median_even_length():
assert find_median([1, 2, 3, 4, 5]) == 3.0
def test_find_median_single_element():
assert find_median([5]) == 5.0
def test_find_med... | [
{
"docstring": null,
"function_declaration": "def find_median(arr):",
"function_name": "find_median",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, step_by_step):",
"function_name": "max_heapify",
"parameter_list": "(arr, n,... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nfrom typing import List\n\ndef find_median(arr: List[int]) -> float:\n \"\"\"\n Finds the median of an unsorted list of integers.\n \"\... | trial_gpt4o_1 | {
"original_instruction": "### Heap Sort Enhancement and Application\n\nYou are part of a team developing educational tools for algorithm visualization. Your task is to create a new feature that extends the functionality of the provided Heap Sort implementations, and then build an advanced usage case that simulates r... | 0.789065 | Data_Structure_36307 | C | [
"find_median",
"max_heapify",
"max_heap_sort",
"min_heapify",
"min_heap_sort"
] | 5 | [
[
"max_heap_sort",
"max_heapify"
],
[
"min_heap_sort",
"min_heapify"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3d40e089d4c400bb34b91ca4a3eabd5bc142307d | 49c3914edd77ab7501989248e6304d2e7c1a155c | |||
v1.0 | complete | Data_Structure | Data_Structure_36877_C | def is_prime(n: int) -> bool:
"""
Check if a number n is prime.
>>> is_prime(2) True
>>> is_prime(4) False
"""
pass
def next_prime(n: int) -> int:
"""
Given an integer n, return the smallest prime number that is greater than n.
>>> next_prime(10) 11
>>> next_prime(14) 17
"""... | def is_prime(n):
"""
Check if a number n is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return Tr... | from solution import is_prime, next_prime
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(9)
def test_next_prime_small_numbers():
assert next_prime(10) == 11
assert next_prime(14) == 17
assert next_prime(17) == 19... | [
{
"docstring": "Check if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given an integer n, return the smallest prime number that is greater than n.",
"function_declaration": "def next_prime(n):",... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if an integer n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return T... | trial_gpt4o_3 | {
"original_instruction": "### Prime Checking & Advanced Number Theory Functions\n\n#### Context\nYou have been approached by a cryptography company to assist in optimizing their number theory functions, specifically focusing on primality testing and related operations. Their current implementation has been found eff... | 0.789985 | Data_Structure_36877 | C | [
"is_prime",
"next_prime"
] | 2 | [
[
"next_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 356b2964d9515892776d965edcb7412863c8dcff | e1df60044d962a400a884b2dfa56e238cff12193 | |||
v1.0 | complete | Data_Structure | Data_Structure_36715_C | def enhanced_diffie_hellman_key_exchange(a: int, p: int, validation: bool = None) -> bool:
"""Secure Communication Key Exchange using enhanced Diffie-Hellman method.
This function implements an enhanced version of the Diffie-Hellman key exchange
method to establish a shared secret key between two parti... | def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i * i) <= n:
if (n % i == 0) or (n % (i + 2) == 0):
return False
i += 6
return True
def is_primitive_root(a, p):
if p <=... | from solution import enhanced_diffie_hellman_key_exchange
def test_valid_keys():
assert enhanced_diffie_hellman_key_exchange(5, 23, True)
def test_invalid_prime():
assert not enhanced_diffie_hellman_key_exchange(5, 24, True)
def test_invalid_primitive_root():
assert not enhanced_diffie_hellman_key_exchan... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def is_primitive_root(a, p):",
"function_name": "is_primitive_root",
"parameter_list": "(a, p)"
},
{
"doc... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(n):\n \"\"\"Utility function to check if a number is prime using trial division.\"\"\"\n if n <= 1:\n return False\... | trial_gpt4o_1 | {
"original_instruction": "### Secure Communication Key Exchange\n\nIn a secure communication scenario, two parties, Alice and Bob, need to establish a shared secret key using the Diffie-Hellman key exchange method. However, this version employs some enhancements to improve the detection of potential problems.\n\nYou... | 0.446426 | Data_Structure_36715 | C | [
"is_prime",
"is_primitive_root",
"gcd",
"enhanced_diffie_hellman_key_exchange"
] | 4 | [
[
"enhanced_diffie_hellman_key_exchange",
"is_prime"
],
[
"enhanced_diffie_hellman_key_exchange",
"is_primitive_root"
],
[
"is_primitive_root",
"gcd"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 15b8a635b46082130132322de3707fdff94955b9 | f5874003b7232932cf739eb54aa0a2cf49399661 | |||
v1.0 | complete | Data_Structure | Data_Structure_36315_C | from typing import List
def custom_ford_fulkerson(capacity: List[List[int]], source: int, sink: int) -> int:
"""
Computes the maximum flow from source to sink in a directed graph using the Ford-Fulkerson algorithm.
Args:
- capacity: A 2D list representing the capacities in the graph, where capacity[i][... | from typing import List
def dfs(residual_capacity, source, sink, parent):
visited = [False] * len(residual_capacity)
stack = [source]
visited[source] = True
while stack:
u = stack.pop()
for v, capacity in enumerate(residual_capacity[u]):
if not visited[v] and capacity > 0:
... | from solution import custom_ford_fulkerson
def test_small_graph():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert custom_ford_fulke... | [
{
"docstring": null,
"function_declaration": "def dfs(residual_capacity, source, sink, parent):",
"function_name": "dfs",
"parameter_list": "(residual_capacity, source, sink, parent)"
},
{
"docstring": "Computes the maximum flow from source to sink in a directed graph using the Ford-Fulkerso... | [
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 custom_ford_fulkerson(capacity: List[List[int]], source: int, sink: int) -> int:\n def dfs(flow: int, current: int, visited:... | trial_gpt4o_1 | {
"original_instruction": "### Maximum Flow Problem: Custom Implementation\n\n#### Problem Statement\nYou are tasked with designing and implementing a custom function for finding the maximum flow in a directed graph using the Ford-Fulkerson algorithm with DFS. Your function needs to handle large input sizes efficient... | 0.54218 | Data_Structure_36315 | C | [
"dfs",
"custom_ford_fulkerson"
] | 2 | [
[
"custom_ford_fulkerson",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8d02b9b967dc784633bd3d8a2b5c34c208279079 | 78d5b42d7bbeab01704d2270997e3dffa202c668 | |||
v1.0 | complete | Data_Structure | Data_Structure_36107_C | import math
from random import randint
def prime_check(num):
"""Return True if num is a prime number."""
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 ... | import math
from random import randint
def prime_check(num):
"""Return True if num is a prime number."""
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 ... | import pytest
from solution import prime_check, optimized_find_primitive_root, secure_diffie_hellman_key_exchange
def test_prime_check():
assert prime_check(7) == True
assert prime_check(10) == False
assert prime_check(2) == True
assert prime_check(1) == False
assert prime_check(15) == False
def t... | [
{
"docstring": "Return True if num is a prime number.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Return the order of a modulo p.",
"function_declaration": "def order(a, p):",
"function_name": "order"... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom random import randint\n\ndef prime_check(num):\n \"\"\"Return True if num is a prime number.\"\"\"\n if num <= 1:\n return Fals... | trial_gpt4o_0 | {
"original_instruction": "### Advanced Coding Assessment: Diffie-Hellman Key Exchange Simulation\n\n**Objective**:\nImplement an advanced Diffie-Hellman key exchange algorithm that securely allows two parties to exchange keys over an insecure channel and enhance it in a way that optimizes the computation of primitiv... | 0.558277 | Data_Structure_36107 | C | [
"prime_check",
"order",
"euler_totient",
"find_primitive_roots",
"alice_private_key",
"alice_public_key",
"bob_private_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"optimized_find_primitive_root",
"secure_diffie_hellman_key_exchange"
] | 12 | [
[
"find_primitive_roots",
"euler_totient"
],
[
"find_primitive_roots",
"order"
],
[
"optimized_find_primitive_root",
"euler_totient"
],
[
"secure_diffie_hellman_key_exchange",
"alice_private_key"
],
[
"secure_diffie_hellman_key_exchange",
"alice_public_key"
... | 11 | [] | false | [] | false | pytest | true | [] | true | 2e2e7c67e05ef6e095b58e23431bdf33f182147a | 3be7277440a020ef7e4473c330347b67bb254416 | |||
v1.0 | complete | Data_Structure | Data_Structure_36605_C | from typing import List
def enhanced_bucket_sort(arr: List[int], num_buckets: int) -> List[int]:
"""
Perform bucket sort on a given list of numbers with specified number of buckets.
Args:
arr (List[int]): A list of integers to be sorted. Each value will be within the range `[0, 10^6]`.
num_bu... | from typing import List
def insertion_sort(bucket: List[int]) -> List[int]:
"""
Simple insertion sort function to sort each individual bucket.
"""
for i in range(1, len(bucket)):
key = bucket[i]
j = i - 1
while j >= 0 and key < bucket[j]:
bucket[j + 1] = bucket[j]
... | from solution import enhanced_bucket_sort
def test_enhanced_bucket_sort_empty():
assert enhanced_bucket_sort([], 5) == []
def test_enhanced_bucket_sort_single_element():
assert enhanced_bucket_sort([5], 5) == [5]
def test_enhanced_bucket_sort_multiple_elements():
arr = [42, 32, 33, 52, 37, 47, 51]
so... | [
{
"docstring": "Simple insertion sort function to sort each individual bucket.",
"function_declaration": "def insertion_sort(bucket):",
"function_name": "insertion_sort",
"parameter_list": "(bucket)"
},
{
"docstring": "Perform bucket sort on a given list of numbers with specified number of 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": "from typing import List\n\ndef insertion_sort(arr: List[int]) -> List[int]:\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n ... | trial_gpt4o_2 | {
"original_instruction": "#### Context\nYou are working on a project that requires efficient sorting of numerical data which is approximately uniformly distributed. You decide to implement the Bucket Sort algorithm due to its suitability for this data pattern.\n\n#### Task\nWrite a function `enhanced_bucket_sort(arr... | 0.601161 | Data_Structure_36605 | C | [
"insertion_sort",
"enhanced_bucket_sort"
] | 2 | [
[
"enhanced_bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5d898a149309e68b94b0e91a5a8467c32a7df8e1 | 1a42119b5c3fb347a2c87cb265ddd71e94ec051e | |||
v1.0 | complete | Data_Structure | Data_Structure_36194_C | from typing import List
def dfs(graph: List[List[int]], reach: List[List[int]], v: int, source: int):
"""
Helper function to perform DFS from source vertex.
"""
pass
def transitive_closure(V: int, graph: List[List[int]]) -> List[List[int]]:
""" Find the transitive closure of a directed graph using... | from typing import List
def dfs(graph: List[List[int]], reach: List[List[int]], v: int, source: int):
"""
Helper function to perform DFS from source vertex.
"""
for i in range(len(graph)):
if graph[source][i] and not reach[v][i]:
reach[v][i] = 1
dfs(graph, reach, v, i)
... | from solution import transitive_closure
def test_transitive_closure_example():
graph = [
[1, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]
]
expected_result = [
[1, 1, 1, 1],
[0, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, 0, 1]
]
assert trans... | [
{
"docstring": "Helper function to perform DFS from source vertex.",
"function_declaration": "def dfs(graph, reach, v, source):",
"function_name": "dfs",
"parameter_list": "(graph, reach, v, source)"
},
{
"docstring": null,
"function_declaration": "def transitive_closure(V, graph):",
... | [
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 transitive_closure(V, graph):\n # Initialize the transitive closure matrix the same as the original graph matrix\n reach = [[graph[i][j] for j in ra... | trial_gpt4o_2 | {
"original_instruction": "### Transitive Closure Matrix\n\nYou are given a directed graph with `V` vertices numbered from 0 to V-1. The graph is represented using an adjacency matrix, where `graph[i][j]` is 1 if there is a direct edge from vertex `i` to vertex `j`, and 0 otherwise. You need to find the transitive cl... | 0.573561 | Data_Structure_36194 | C | [
"dfs",
"transitive_closure"
] | 2 | [
[
"transitive_closure",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f3bbee24517255c41d51d24033b033dab62f234a | 60aa8add7e8e173834fdada56e7a42c16ac6b327 | |||
v1.0 | complete | Data_Structure | Data_Structure_37005_C | class Node:
def __init__(self, val: int = 0, next: 'Node' = None):
self.val = val
self.next = next
def cycle_length(head: Node) -> int:
"""
Detects if a cycle exists in a linked list and returns the length of the cycle.
If there is no cycle, returns 0.
"""
def calculate_cycle_lengt... | class Node:
def __init__(self, val: int = 0, next: 'Node' = None):
self.val = val
self.next = next
def cycle_length(head: Node) -> int:
"""
Detects if a cycle exists in a linked list and returns the length of the cycle.
If there is no cycle, returns 0.
"""
if not head:
r... | from solution import Node, cycle_length
def test_cycle_length_no_cycle():
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
assert cycle_length(head) == 0
def test_cycle_length_single_node_no_cycle():
head = Node(1)
assert cycle_length(head) == 0
def test_cycle_length_sing... | [] | [
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": "class Node:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef cycle_length(head: Node) -> int:\n \"\"\"\n... | trial_gpt4o_2 | {
"original_instruction": "You are given a linked list. Write a function to detect if the linked list contains a cycle. If there is a cycle, return the length of the cycle. Otherwise, return 0. Your solution should not use any extra space apart from a few variables.\n\n### Function Signature\n```python\ndef cycle_len... | 0.484137 | Data_Structure_37005 | C | [
"cycle_length",
"calculate_cycle_length"
] | 2 | [
[
"cycle_length",
"calculate_cycle_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | ab1b2d29c9d39943fae72cbbe9394336958690ce | 5981766b4e401dfdeaad2e818774225eae9c2402 | |||
v1.0 | complete | Data_Structure | Data_Structure_36540_C | from typing import List
def construct_bit_tree(arr: List[int]) -> List[int]:
"""
Constructs the Fenwick Tree for given array `arr` and returns it.
Parameters:
arr (List[int]): The input array of integers.
Returns:
List[int]: The constructed Fenwick Tree.
"""
pass
def prefix_s... | def construct_bit_tree(arr):
"""
Constructs the Fenwick Tree for given array `arr` and returns it.
Parameters:
arr (List[int]): The input array of integers.
Returns:
List[int]: The constructed Fenwick Tree.
"""
n = len(arr)
bit_tree = [0] * (n + 1)
for i in range(n... | def test_construct_and_query():
arr = [1, 7, 3, 0, 7, 8, 3, 2, 6, 2, 6, 8, 4, 9]
bit_tree = construct_bit_tree(arr)
assert prefix_sum(bit_tree, 5) == sum(arr[:6]) # Should return sum of first 6 elements
def test_update():
arr = [1, 7, 3, 0, 7, 8, 3, 2, 6, 2, 6, 8, 4, 9]
bit_tree = construct_bit_tr... | [
{
"docstring": "Constructs the Fenwick Tree for given array `arr` and returns it.\n\nParameters:\narr (List[int]): The input array of integers.\n\nReturns:\nList[int]: The constructed Fenwick Tree.",
"function_declaration": "def construct_bit_tree(arr):",
"function_name": "construct_bit_tree",
"para... | [
0,
0,
0,
0,
1,
0,
1,
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": "def construct_bit_tree(arr):\n \"\"\"\n Constructs the Fenwick Tree for given array `arr` and returns it.\n \"\"\"\n n = len(arr)\n bit_tree = ... | trial_gpt4o_7 | {
"original_instruction": "### Problem: Efficient Range Sum Query with Fenwick Tree\n\nYou have been provided with an integer array `arr` which contains `n` elements. Your task is to implement an efficient solution to perform the following operations:\n1. **Prefix Sum Query**: Return the sum of the first `i` elements... | 0.523417 | Data_Structure_36540 | C | [
"construct_bit_tree",
"prefix_sum",
"update_bit_tree"
] | 3 | [
[
"construct_bit_tree",
"update_bit_tree"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | d39ee1d0b451e54191476f1db5068e1c72f99823 | a7add58dc54bb43bb7cdda8a1a5d706c1aab1aa2 | |||
v1.0 | complete | Data_Structure | Data_Structure_36775_C | from typing import List
def maximum_flow(capacity: List[List[int]], source: int, sink: int, algorithm: str) -> int:
"""
This function should compute the maximum flow from the source to the sink in the provided graph.
:param capacity: A 2D list, where capacity[i][j] represents the capacity of the edge ... | from collections import deque
from typing import List
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... | import pytest
from solution import maximum_flow
def test_edmonds_karp_small_graph():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
algori... | [
{
"docstring": null,
"function_declaration": "def bfs(capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def edmonds_karp(capacity, source, sink):",
"function_name": "edmonds... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List\n\ndef bfs_capacity(residual_capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> b... | trial_gpt4o_1 | {
"original_instruction": "### Maximum Flow in a Flow Network\n\n**Context**:\nYou are working as a network engineer responsible for optimizing the data flow in a communication network. The network can be represented as a directed graph where nodes are routers, and edges are data paths with certain capacities. Your g... | 0.608867 | Data_Structure_36775 | C | [
"bfs",
"edmonds_karp",
"maximum_flow"
] | 3 | [
[
"edmonds_karp",
"bfs"
],
[
"maximum_flow",
"edmonds_karp"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7c440f3443cbf5b0e4d4b5d039fa458ca5089b6f | d2b9b723b156f096065294f2c5bc9b7a391374b4 | |||
v1.0 | complete | Data_Structure | Data_Structure_36676_C | import random
from math import gcd
def generate_key(k: int, seed: int = None) -> tuple:
""" Generate RSA key pairs.
Args:
k (int): The number of bits in the modulus `n`.
seed (int, optional): Seed for random number generator.
Returns:
tuple: A tuple `(n, e, d)` representing the modulus, the pu... | import random
from math import gcd
def is_prime(n):
""" Check if a number is prime using a simple method. Not optimized but works for small n. """
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if ... | from solution import generate_key, encrypt, decrypt
def test_rsa_encryption_decryption():
k = 16
n, e, d = generate_key(k, seed=42)
data = 20
encrypted = encrypt(data, e, n)
decrypted = decrypt(encrypted, d, n)
assert decrypted == data
def test_key_generation_with_fixed_seed():
k = 16
... | [
{
"docstring": "Check if a number is prime using a simple method. Not optimized but works for small n. ",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate a prime number with approximately k bits. ",
"function_de... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime\nfrom sympy.ntheory.generate import randprime\n\ndef gen_prime(bits):\n \"\"\"\n Gener... | trial_gpt4o_2 | {
"original_instruction": "### RSA Encryption Implementation\n\nYou are tasked with implementing an RSA encryption and decryption system. This involves writing functions to generate RSA keys, encrypt data with the public key, and decrypt data with the private key.\n\n#### Function Implementations\n\n* **generate_key(... | 0.71651 | Data_Structure_36676 | C | [
"is_prime",
"gen_prime",
"modinv",
"egcd",
"generate_key",
"encrypt",
"decrypt"
] | 7 | [
[
"gen_prime",
"is_prime"
],
[
"generate_key",
"gen_prime"
],
[
"generate_key",
"modinv"
],
[
"modinv",
"egcd"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 49f7c2c33914286f0f3d719ac3b2aa60d81218b9 | 3e9c9d667b9db1e48459a445e43ae80e886522bd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.