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_16669_C | from typing import List
def generalized_multiply(matrices: List[List[List[int]]]) -> List[List[int]]:
"""
Multiplies a list of matrices in the given order.
Parameters:
matrices (List[List[List[int]]]): A list of matrices to multiply.
Returns:
List[List[int]]: The result of multiplying... | from typing import List
def matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
"""
Multiplies two matrices A and B.
"""
# Check matrix dimensions
if len(A[0]) != len(B):
raise ValueError("Incompatible matrix dimensions for multiplication")
# Resultant matri... | from solution import generalized_multiply
def test_generalized_multiply_example1():
matrices = [
[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]
]
expected_result = [
[19, 22],
[43, 50]
]
assert generalized_multiply(matrices) == expected_result
def test_gene... | [
{
"docstring": "Multiplies two matrices A and B.",
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": "Multiplies a list of matrices in the given order.",
"function_declaration": "def generalized_multiply... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef multiply_matrices(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Multiplies two matrices A and B.... | trial_gpt4o_1 | {
"original_instruction": "### Matrix Multiplication Challenge\n\n#### Task:\nWrite a function `generalized_multiply(matrices: List[List[List[int]]]) -> List[List[int]]` that takes a list of matrices (each matrix represented as a 2D list of integers) and returns the result of their chained multiplication.\n\n#### Req... | 0.567156 | Data_Structure_16669 | C | [
"matrix_multiply",
"generalized_multiply"
] | 2 | [
[
"generalized_multiply",
"matrix_multiply"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0c2603e67d9f75f13d0d7aa4a901adf42bc2b668 | 73f3d46b195733b45a7cae25be86711190234259 | |||
v1.0 | complete | Data_Structure | Data_Structure_17293_C | from typing import List
def find_dna_patterns(dna_sequence: str, motif: str) -> List[int]:
"""
Given a DNA sequence and a motif (pattern), return a list of start indices where the motif is found in the sequence.
Args:
dna_sequence: A string representing the DNA sequence to search within.
m... | from typing import List
def compute_lps_array(pattern: str) -> List[int]:
"""
Computes the Longest Prefix Suffix (LPS) array with pattern as parameter.
LPS array is used to skip characters while matching.
"""
length = 0 # length of the previous longest prefix suffix
lps = [0] * len(pattern)... | from solution import find_dna_patterns
def test_exact_match():
assert find_dna_patterns("ACGTACGTACG", "ACG") == [0, 4, 8]
def test_no_match():
assert find_dna_patterns("ACGTACGTACG", "TTT") == []
def test_multiple_motifs():
assert find_dna_patterns("ACGTACGTACGTACGT", "ACGT") == [0, 4, 8, 12]
def test_... | [
{
"docstring": "Computes the Longest Prefix Suffix (LPS) array with pattern as parameter. \nLPS array is used to skip characters while matching. ",
"function_declaration": "def compute_lps_array(pattern):",
"function_name": "compute_lps_array",
"parameter_list": "(pattern)"
},
{
"docstring":... | [
0,
0,
0,
0,
1,
1,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_dna_patterns(dna_sequence, motif):\n def compute_lps(pattern):\n lps = [0] * len(pattern)\n length = 0\n i = 1\n while... | trial_gpt4o_4 | {
"original_instruction": "### Problem: KMP Algorithm Application in DNA Sequence Search\n\nResearchers are often required to find patterns within DNA sequences for analysis. You are tasked with implementing the Knuth-Morris-Pratt (KMP) string matching algorithm to locate patterns within a DNA sequence.\n\n#### Funct... | 0.602322 | Data_Structure_17293 | C | [
"compute_lps_array",
"find_dna_patterns"
] | 2 | [
[
"find_dna_patterns",
"compute_lps_array"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 714efcbf7999a258139d3b712fcd47a3f4eb798b | 17bbcaa7326ffcbce8985a12b25c7df39d16bbf0 | |||
v1.0 | complete | Data_Structure | Data_Structure_17526_C | from typing import List, Optional
def factorial_list(numbers: List[int], mod: Optional[int] = None) -> List[int]:
""" Extend a factorial calculation function to handle a list of integers, each potentially requiring the result to be taken modulo some number.
>>> factorial_list([0, 1, 2, 3, 5]) == [1, 1, 2, 6, 1... | from typing import List, Optional
def factorial(n: int, mod: Optional[int] = None) -> int:
result = 1
for i in range(1, n + 1):
result *= i
if mod:
result %= mod
return result
def factorial_list(numbers: List[int], mod: Optional[int] = None) -> List[int]:
return [factorial(... | from solution import factorial_list
def test_factorial_list_no_mod():
assert factorial_list([0, 1, 2, 3, 5]) == [1, 1, 2, 6, 120]
def test_factorial_list_with_mod():
assert factorial_list([0, 1, 2, 3, 5], mod=100) == [1, 1, 2, 6, 20]
assert factorial_list([0, 1, 2, 3, 5], mod=10) == [1, 1, 2, 6, 0]
def t... | [
{
"docstring": null,
"function_declaration": "def factorial(n, mod=None):",
"function_name": "factorial",
"parameter_list": "(n, mod=None)"
},
{
"docstring": null,
"function_declaration": "def factorial_list(numbers, mod=None):",
"function_name": "factorial_list",
"parameter_list... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef factorial(n: int, mod: int = None) -> int:\n \"\"\"\n Returns the factorial of n optionally taken modulo `mod`.\n \"\"... | trial_gpt4o_8 | {
"original_instruction": "You've been tasked to extend a factorial calculation function to handle a list of integers, each potentially requiring the result to be taken modulo some number.\n\n**Task**:\nWrite a function `factorial_list(numbers: List[int], mod: int = None) -> List[int]` that takes a list of non-negati... | 0.706423 | Data_Structure_17526 | C | [
"factorial",
"factorial_list"
] | 2 | [
[
"factorial_list",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7c05ecf3bcedd6fa56fdf837860d17aa97b4013a | 0585767b394394cee2e098913791b8d215b303eb | |||
v1.0 | complete | Data_Structure | Data_Structure_17022_C | import random
def next_state(chain: dict, current_state: str) -> str:
"""
Selects the next state based on the transition probabilities defined in the chain for the current state.
>>> next_state({'A': {'A': 0.6, 'B': 0.4}, 'B': {'A': 0.3, 'B': 0.7}}, 'A') in ['A', 'B']
True
>>> next_state({'A': {'A'... | import random
def next_state(chain, current_state):
"""
Selects the next state based on the transition probabilities defined in the chain for the current state.
"""
transitions = chain[current_state]
states = list(transitions.keys())
probabilities = list(transitions.values())
return random.... | from solution import next_state, iterating_markov_chain
def test_next_state():
chain = {
'A': {'A': 0.6, 'B': 0.4},
'B': {'A': 0.3, 'B': 0.7}
}
assert next_state(chain, 'A') in ['A', 'B']
assert next_state(chain, 'B') in ['A', 'B']
def test_iterating_markov_chain():
chain = {
... | [
{
"docstring": "Selects the next state based on the transition probabilities defined in the chain for the current state.",
"function_declaration": "def next_state(chain, current_state):",
"function_name": "next_state",
"parameter_list": "(chain, current_state)"
},
{
"docstring": "Generates a... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef next_state(chain: dict, current_state: str) -> str:\n \"\"\"\n Chooses the next state based on the current state's transition proba... | trial_gpt4o_1 | {
"original_instruction": "### Question Description\nYou are required to implement a Markov Chain simulator. The simulator will use a dictionary-based Markov Chain to generate a sequence of states, given an initial state. \n\n### Function Implementation\n\n#### Function 1: next_state\nCreate a function `next_state(ch... | 0.548275 | Data_Structure_17022 | C | [
"next_state",
"iterating_markov_chain"
] | 2 | [
[
"iterating_markov_chain",
"next_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ddc46ebb12454a41b33bbfded2311d3feb447021 | 823829595d274e3eee9421004da0bc2580ce31eb | |||
v1.0 | complete | Data_Structure | Data_Structure_16641_C | def trailing_zero(x):
"""
Returns the number of trailing zero bits in x.
For example, trailing_zero(8) returns 3 because the binary representation of 8 is 1000.
>>> trailing_zero(8) 3
>>> trailing_zero(16) 4
"""
def bitwise_gcd(a, b):
"""
Computes the GCD of two non-negative integer... | def trailing_zero(x):
"""
Returns the number of trailing zero bits in x.
For example, trailing_zero(8) returns 3 because the binary representation of 8 is 1000.
"""
if x == 0:
return 32
return (x & -x).bit_length() - 1
def bitwise_gcd(a, b):
"""
Computes the GCD of two non-negat... | from solution import bitwise_gcd, trailing_zero
def test_trailing_zero():
assert trailing_zero(0) == 32
assert trailing_zero(1) == 0
assert trailing_zero(2) == 1
assert trailing_zero(8) == 3
assert trailing_zero(16) == 4
def test_bitwise_gcd_basic():
assert bitwise_gcd(34, 17) == 17
assert... | [
{
"docstring": "Returns the number of trailing zero bits in x.\nFor example, trailing_zero(8) returns 3 because the binary representation of 8 is 1000.",
"function_declaration": "def trailing_zero(x):",
"function_name": "trailing_zero",
"parameter_list": "(x)"
},
{
"docstring": "Computes the... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bitwise_gcd(a: int, b: int) -> int:\n \"\"\"\n Calculate the greatest common divisor (GCD) of two non-negative integers using bitwise operations.\n ... | trial_gpt4o_2 | {
"original_instruction": "### Context\nAs part of a software system's performance optimization module, you are required to write a function that calculates the Greatest Common Divisor (GCD) using bitwise operations.\n\n### Task\nImplement a function `bitwise_gcd` that computes the GCD of two non-negative integers us... | 0.669437 | Data_Structure_16641 | C | [
"trailing_zero",
"bitwise_gcd"
] | 2 | [
[
"bitwise_gcd",
"trailing_zero"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1ae69ad293442f78894bb24826469ac9d3dad18d | c2fb3b31f6e9cfa30f76b2d11d0f991dc3ee03c3 | |||
v1.0 | complete | Data_Structure | Data_Structure_16157_C | from typing import Tuple
def solve_bezout(num1: int, num2: int) -> Tuple[int, int, int]:
"""
Computes the Bézout coefficients (s, t) and the greatest common divisor (g)
for the integers num1 and num2.
Parameters:
num1 (int): First integer.
num2 (int): Second integer.
Returns:
... | from typing import Tuple
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
"""
Uses the Extended Euclidean Algorithm to find the Bezout coefficients (s, t) and the
greatest common divisor (g) of the integers a and b.
"""
if b == 0:
return (1, 0, a)
else:
s, t, g = extend... | from solution import solve_bezout
def test_solve_bezout_standard():
assert solve_bezout(30, 12) == (1, -2, 6)
def test_solve_bezout_both_zero():
assert solve_bezout(0, 0) == (0, 0, 0)
def test_solve_bezout_num1_zero():
assert solve_bezout(0, 25) == (0, 1, 25)
def test_solve_bezout_num2_zero():
asser... | [
{
"docstring": "Uses the Extended Euclidean Algorithm to find the Bezout coefficients (s, t) and the\ngreatest common divisor (g) of the integers a and b.",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Solve... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def extended_gcd(a, b):\n if b == 0:\n return (1, 0, a) if a >= 0 else (-1, 0, -a)\n else:\n s, t, g = extended_gcd(b, a % b)\n ret... | trial_gpt4o_9 | {
"original_instruction": "You have been given two integers, `num1` and `num2`. Your task is to compute three values `s`, `t`, and `g` such that:\n\n```plaintext\nnum1 * s + num2 * t = g\n```\nwhere `g` is the Greatest Common Divisor (GCD) of `num1` and `num2`, and `s` and `t` are Bézout's coefficients.\n\nWrite a fu... | 0.646829 | Data_Structure_16157 | C | [
"extended_gcd",
"solve_bezout"
] | 2 | [
[
"solve_bezout",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 132d786d46ae743887f7147d3869ae528acba7d4 | feba48b39ca8b8bf36aff6e0083a48fef32d7804 | |||
v1.0 | complete | Data_Structure | Data_Structure_16761_C | from typing import List
def prime_reversal(numbers: List[int]) -> List[bool]:
"""Check if the reversed digit sequence of each number in the list is a prime number.
>>> prime_reversal([13, 17, 29, 31, 37, 97])
[True, True, False, True, True, True]
>>> prime_reversal([1, 10, 100003, 123456789])
... | from typing import List
def is_prime(n: int) -> bool:
"""Check if a number is a prime number."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return... | from solution import prime_reversal
def test_single_number():
assert prime_reversal([13]) == [True]
assert prime_reversal([17]) == [True]
assert prime_reversal([29]) == [False]
def test_multiple_numbers():
assert prime_reversal([13, 17, 29, 31, 37, 97]) == [True, True, False, True, True, True]
def te... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Check if the reversed digit sequence of each number in the list is a prime number.",
"function_declaration": "def pri... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ... | trial_gpt4o_2 | {
"original_instruction": "#### **Prime Number Reversal Game**\n\n**Context**: In the game of Prime Number Reversal, the player is provided with a list of integers. For each integer, the player needs to determine whether reversing the digits of the integer gives a prime number. The game judges the player's performanc... | 0.738252 | Data_Structure_16761 | C | [
"is_prime",
"prime_reversal"
] | 2 | [
[
"prime_reversal",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 753e1ed139d63dce48d336522907a870ef134515 | 0702277ef4d5e46616806b6125387edc1e258f68 | |||
v1.0 | complete | Data_Structure | Data_Structure_16414_C | def modified_bitonic_sort(arr, reverse=False):
""" Implement a Modified Bitonic Sort to handle arrays of any arbitrary length n.
You need to enhance and modify the existing implementation to handle arrays of any length.
When necessary, extend the array by padding with a very large number to make its length ... | def bitonic_compare_and_swap(arr, i, j, direction):
if direction == (arr[i] > arr[j]):
arr[i], arr[j] = arr[j], arr[i]
def bitonic_merge(arr, low, cnt, direction):
if cnt > 1:
k = cnt // 2
for i in range(low, low + k):
bitonic_compare_and_swap(arr, i, i + k, direction)
... | from solution import modified_bitonic_sort
def test_empty_array():
assert modified_bitonic_sort([]) == []
def test_single_element():
assert modified_bitonic_sort([42]) == [42]
def test_sorted_array():
assert modified_bitonic_sort([1, 2, 3]) == [1, 2, 3]
def test_reverse_sorted_array():
assert modifi... | [
{
"docstring": null,
"function_declaration": "def bitonic_compare_and_swap(arr, i, j, direction):",
"function_name": "bitonic_compare_and_swap",
"parameter_list": "(arr, i, j, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, low, cnt, direction):",
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def next_power_of_two(n):\n if n <= 0:\n return 1\n power = 1\n while power < n:\n power *= 2\n return power\n\ndef compare_and_swap... | trial_gpt4o_2 | {
"original_instruction": "Implement a Modified Bitonic Sort\nGiven the recursive sorting mechanism of **Bitonic Sort**, you are to **enhance and modify the existing implementation** to handle arrays of any arbitrary length \\(n\\). This involves:\n1. Extending and pre-processing the input array such that its length ... | 0.69504 | Data_Structure_16414 | C | [
"bitonic_compare_and_swap",
"bitonic_merge",
"bitonic_sort_recursive",
"next_power_of_two",
"modified_bitonic_sort"
] | 5 | [
[
"bitonic_merge",
"bitonic_compare_and_swap"
],
[
"bitonic_sort_recursive",
"bitonic_merge"
],
[
"modified_bitonic_sort",
"bitonic_sort_recursive"
],
[
"modified_bitonic_sort",
"next_power_of_two"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | dd62183675d997e2723e2b1f6bbdd5059be42e43 | 7e7fe689e79f5d13fe579c15d154583945c904b5 | |||
v1.0 | complete | Data_Structure | Data_Structure_15419_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_into_bst(root: TreeNode, val: int) -> TreeNode:
""" Helper function to insert a value into the BST """
pass
def construct_bst(nums: list[int]) -> TreeNode... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_into_bst(root, val):
if root is None:
return TreeNode(val)
if val < root.val:
root.left = insert_into_bst(root.left, val)
else:
... | import pytest
from solution import TreeNode, construct_bst, in_order_traversal
def test_construct_bst():
nums = [5, 3, 1, 4, 7, 6, 8]
root = construct_bst(nums)
assert root.val == 5
assert root.left.val == 3
assert root.left.left.val == 1
assert root.left.right.val == 4
assert root.right.va... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef in... | trial_gpt4o_1 | {
"original_instruction": "### Context:\nYou are tasked with implementing a function to construct a Binary Search Tree (BST) from a given list of integers. The BST should satisfy the properties of a Binary Search Tree where, for each node, all elements in its left subtree are less than the node's value and all elemen... | 0.545441 | Data_Structure_15419 | C | [
"insert_into_bst",
"construct_bst",
"in_order_traversal"
] | 3 | [
[
"construct_bst",
"insert_into_bst"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 1a9658dbb9d10f30b55424e7c286581540db1548 | b85b3ae1cdd8655b42791005e67c3c3e0cf2cd79 | |||
v1.0 | complete | Data_Structure | Data_Structure_15991_C | from collections import namedtuple
KDTreeNode = namedtuple('KDTreeNode', ['point', 'left', 'right'])
def build_kd_tree(points, depth=0):
"""
Build a KD-Tree from a set of points.
Parameters:
points (list of tuples): The points to build the KD-Tree from.
depth (int): The current depth of the t... | from collections import namedtuple
import math
KDTreeNode = namedtuple('KDTreeNode', ['point', 'left', 'right'])
def build_kd_tree(points, depth=0):
if not points:
return None
k = len(points[0]) # Assume all points have the same dimension
axis = depth % k
points.sort(key=lambda x: x... | from solution import build_kd_tree, kd_tree_nearest_neighbor
def test_kd_tree_construction():
points = [(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)]
kd_tree = build_kd_tree(points)
assert kd_tree.point == (7, 2)
def test_kd_tree_nearest_neighbor_basic():
points = [(2, 3), (5, 4), (9, 6), (4, 7), (8... | [
{
"docstring": null,
"function_declaration": "def build_kd_tree(points, depth=0):",
"function_name": "build_kd_tree",
"parameter_list": "(points, depth=0)"
},
{
"docstring": null,
"function_declaration": "def distance_squared(p1, p2):",
"function_name": "distance_squared",
"param... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import namedtuple\nimport math\n\nKDTreeNode = namedtuple('KDTreeNode', ['point', 'left', 'right'])\n\ndef build_kd_tree(points, depth=0):\n ... | trial_gpt4o_0 | {
"original_instruction": "You are tasked with improving the given nearest neighbor classifier by addressing some of its limitations and ensuring efficiency in high-dimensional data. Specifically, you should enhance the performance of the nearest neighbor search algorithm.\n\n### Task\nImplement a nearest neighbor se... | 0.606077 | Data_Structure_15991 | C | [
"build_kd_tree",
"distance_squared",
"kd_tree_nearest_neighbor"
] | 3 | [
[
"kd_tree_nearest_neighbor",
"distance_squared"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e8d8d3dc4a78926846b36d03018f0b1795315dd3 | e4827b569182e18712c55efae8a3e5d38cf32c73 | |||
v1.0 | complete | Data_Structure | Data_Structure_17055_C | from typing import List
def gcd(a: int, b: int) -> int:
"""
Calculates the Greatest Common Divisor (GCD) of two numbers using Euclid's algorithm.
>>> gcd(12, 15)
3
>>> gcd(100, 10)
10
"""
pass
def lcm(a: int, b: int) -> int:
"""
Calculates the Least Common Multiple (LCM) of tw... | import math
from functools import reduce
def gcd(a, b):
"""
Calculates the Greatest Common Divisor (GCD) of two numbers using Euclid's algorithm.
"""
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""
Calculates the Least Common Multiple (LCM) of two numbers using the relationshi... | from solution import lcm, gcd, lcm_array
import pytest
def test_gcd():
assert gcd(12, 15) == 3
assert gcd(100, 10) == 10
assert gcd(7, 13) == 1
assert gcd(0, 5) == 5
def test_lcm():
assert lcm(3, 4) == 12
assert lcm(5, 0) == 0
assert lcm(6, 8) == 24
assert lcm(7, 13) == 91
def test_lc... | [
{
"docstring": "Calculates the Greatest Common Divisor (GCD) of two numbers using Euclid's algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculates the Least Common Multiple (LCM) of two numbers using the relation... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\n\ndef gcd(a, b):\n \"\"\"\n Calculates the Greatest Common Divisor (GCD) of two numbers using Euclid's algori... | trial_gpt4o_0 | {
"original_instruction": "**Problem Statement**:\nYou have been tasked with implementing a function that calculates the Least Common Multiple (LCM) of an array of integers using a combination of Euclid's algorithm for GCD and the provided LCM formula. You must also handle various edge cases gracefully, such as non-i... | 0.718381 | Data_Structure_17055 | C | [
"gcd",
"lcm",
"lcm_array"
] | 3 | [
[
"lcm",
"gcd"
],
[
"lcm_array",
"lcm"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fca18f8c50a879834301fdba7f30bed52c04ade4 | aaeed79531528375d668c3ef9d58569263f33b93 | |||
v1.0 | complete | Data_Structure | Data_Structure_16095_C | from typing import Sequence, List
def kmp_search_with_validation(text: Sequence, pattern: Sequence) -> List[int]:
""" Enhanced version of the KMP string matching algorithm with validation.
Finds all occurrences of the pattern in the text.
If the text or pattern is empty, it returns an empty list.
If t... | from typing import Sequence, List
def compute_lps(pattern: Sequence) -> List[int]:
"""
Compute the longest prefix suffix (LPS) array used to
skip characters while matching.
"""
lps = [0] * len(pattern)
j = 0 # length of the previous longest prefix suffix
for i in range(1, len(pattern)):
... | import pytest
from solution import kmp_search_with_validation
def test_kmp_empty_text():
assert kmp_search_with_validation("", "a") == []
def test_kmp_empty_pattern():
assert kmp_search_with_validation("a", "") == []
def test_kmp_pattern_longer_than_text():
assert kmp_search_with_validation("a", "aa") ==... | [
{
"docstring": "Compute the longest prefix suffix (LPS) array used to\nskip characters while matching.",
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": "Enhanced version of the KMP string matching algorithm... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Sequence, List\n\ndef build_lps(pattern: Sequence) -> List[int]:\n \"\"\"\n Build the longest prefix that is also suffix array (LPS) ... | trial_gpt4o_1 | {
"original_instruction": "### String Matching with Enhanced Error Handling\n\nImplement an enhanced version of the Knuth-Morris-Pratt (KMP) string matching algorithm. Your task is to write a function `kmp_search_with_validation` that:\n\n1. Enhances the provided `knuth_morris_pratt` algorithm by handling additional ... | 0.541512 | Data_Structure_16095 | C | [
"compute_lps",
"kmp_search_with_validation"
] | 2 | [
[
"kmp_search_with_validation",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5cb1c9cab050f58f4c7782ae5b30dc31bd03956d | ca12dd54acc2917de770980b7ef5eba52a4e875d | |||
v1.0 | complete | Data_Structure | Data_Structure_16318_C | import math
def euclidean_distance(vec1, vec2):
"""
Computes the Euclidean distance between two vectors.
"""
pass
def recommend(user_vector: tuple, item_dict: dict) -> str:
"""
Recommends the closest item to the user vector from the item dictionary.
>>> recommend((1, 2, 3), {(2, 2, 2): 'I... | import math
def euclidean_distance(vec1, vec2):
"""
Computes the Euclidean distance between two vectors.
"""
return math.sqrt(sum((x - y) ** 2 for x, y in zip(vec1, vec2)))
def recommend(user_vector: tuple, item_dict: dict) -> str:
"""
Recommends the closest item to the user vector from the it... | from solution import recommend
def test_recommend_single_item():
user_vector = (1, 2, 3)
item_dict = {(1, 2, 3): 'Item A'}
assert recommend(user_vector, item_dict) == 'Item A'
def test_recommend_multiple_items():
user_vector = (1, 2, 3)
item_dict = {
(2, 2, 2): 'Item A',
(1, 2, 1):... | [
{
"docstring": "Computes the Euclidean distance between two vectors.",
"function_declaration": "def euclidean_distance(vec1, vec2):",
"function_name": "euclidean_distance",
"parameter_list": "(vec1, vec2)"
},
{
"docstring": "Recommends the closest item to the user vector from the item dictio... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef recommend(user_vector: tuple, item_dict: dict) -> str:\n \"\"\"\n Recommends the item closest to the user's preference vector from th... | trial_gpt4o_6 | {
"original_instruction": "### Scenario\nYou are given the task of developing a simple recommendation system. The recommendation system utilizes the nearest neighbor algorithm to recommend the most similar items to a user based on their preference vector.\n\n### Task\nImplement a function `recommend` that takes a use... | 0.532273 | Data_Structure_16318 | C | [
"euclidean_distance",
"recommend"
] | 2 | [
[
"recommend",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d4e5c41b1c9c4873a24ee31b4c405d2d983aeb8a | 819a642815a73d6e31379550f42bf8cc2cc4a3fc | |||
v1.0 | complete | Data_Structure | Data_Structure_16384_C | from typing import List, Tuple, Dict, Union
from fractions import Fraction
def add_polynomials(p1: List[Tuple[Dict[int, int], Union[int, float, Fraction]]],
p2: List[Tuple[Dict[int, int], Union[int, float, Fraction]]]) -> List[Tuple[Dict[int, int], Union[int, float, Fraction]]]:
""" Add two po... | from typing import List, Tuple, Dict, Union
from fractions import Fraction
from collections import defaultdict
def combine_monomials(monomials):
combined = defaultdict(Fraction)
for vars_exp, coeff in monomials:
vars_exp_tuple = tuple(sorted(vars_exp.items()))
combined[vars_exp_tuple] += Fracti... | from solution import add_polynomials, multiply_polynomials, evaluate_polynomial
from fractions import Fraction
def test_add_polynomials():
p1 = [({1: 1}, 3), ({2: 2}, 4)]
p2 = [({1: 1}, 2), ({2: 1}, 5)]
assert add_polynomials(p1, p2) == [({1: 1}, 5), ({2: 2}, 4), ({2: 1}, 5)]
def test_add_polynomials_with... | [
{
"docstring": null,
"function_declaration": "def combine_monomials(monomials):",
"function_name": "combine_monomials",
"parameter_list": "(monomials)"
},
{
"docstring": null,
"function_declaration": "def add_polynomials(p1, p2):",
"function_name": "add_polynomials",
"parameter_l... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from fractions import Fraction\nfrom collections import defaultdict\nfrom typing import List, Tuple, Dict, Union\n\ndef add_polynomials(p1: List[Tuple[Dict[in... | trial_gpt4o_2 | {
"original_instruction": "### Polynomial Addition, Multiplication, and Evaluation\n\nYou are given two classes, `Monomial` and `Polynomial`, which represent mathematical monomials and polynomials. Your task is to add a feature to handle the addition of polynomials and multiply them efficiently. Furthermore, you need... | 0.579805 | Data_Structure_16384 | C | [
"combine_monomials",
"add_polynomials",
"multiply_polynomials",
"evaluate_polynomial"
] | 4 | [
[
"add_polynomials",
"combine_monomials"
],
[
"multiply_polynomials",
"combine_monomials"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 61a188a492f5af9361eeba10115991719c411876 | 28d1be6d1dff29b17ec921aae2c34b6fc9463ff5 | |||
v1.0 | complete | Data_Structure | Data_Structure_17097_C | def crypto_simulation(n: int) -> Tuple[int, List[int]]:
"""Determine both the Euler's totient function and all primitive roots of a given integer `n`.
Args:
n (int): The integer to calculate the Euler's totient function and primitive roots for.
Returns:
Tuple[int, List[int]]: A tuple conta... | from typing import Tuple, List
def gcd(a: int, b: int) -> int:
while b != 0:
a, b = b, a % b
return a
def euler_totient(n: int) -> int:
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
... | from solution import crypto_simulation
def test_crypto_simulation_case_7():
result = crypto_simulation(7)
assert result == (6, [3, 5])
def test_crypto_simulation_case_10():
result = crypto_simulation(10)
assert result == (4, [])
def test_crypto_simulation_case_12():
result = crypto_simulation(12)... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": null,
... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef gcd(a: int, b: int) -> int:\n while b:\n a, b = b, a % b\n return a\n\ndef euler_totient(n: int) -> int:\n ... | trial_gpt4o_5 | {
"original_instruction": "### Problem Description\n\nYou are tasked with developing a small cryptographic protocol simulation. Your mission is to write a function that determines both the Euler's totient function and all primitive roots of a given integer \\( n \\).\n\n**Function Signature**\n```python\ndef crypto_s... | 0.536768 | Data_Structure_17097 | C | [
"gcd",
"euler_totient",
"powmod",
"find_primitive_roots",
"crypto_simulation"
] | 5 | [
[
"crypto_simulation",
"euler_totient"
],
[
"crypto_simulation",
"find_primitive_roots"
],
[
"find_primitive_roots",
"euler_totient"
],
[
"find_primitive_roots",
"gcd"
],
[
"find_primitive_roots",
"powmod"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 920d9e8cc026cde2be8fb67a69bc924f80adf32a | f607ff1612dc2b3fdd8d5965ce474d7ec6bfbb15 | |||
v1.0 | complete | Data_Structure | Data_Structure_16937_C | from typing import Tuple, Dict, Any
def nearest_neighbor(x: Tuple[float, ...], tSet: Dict[Tuple[float, ...], Any]) -> Any:
"""
Find the label of the closest vector to x in tSet using Euclidean distance.
Parameters:
x (Tuple[float, ...]): The input vector.
tSet (Dict[Tuple[float, ...], Any]): The t... | import math
from typing import Tuple, Dict, Any
def euclidean_distance(p: Tuple[float, ...], q: Tuple[float, ...]) -> float:
"""
Calculate the Euclidean distance between two points p and q.
"""
return math.sqrt(sum((pi - qi) ** 2 for pi, qi in zip(p, q)))
def nearest_neighbor(x: Tuple[float, ...], tSe... | from solution import nearest_neighbor
def test_nearest_neighbor_basic():
x = (1.0, 2.0)
tSet = {
(2.0, 3.0): "Class_A",
(3.0, 4.0): "Class_B",
(1.1, 2.1): "Class_C"
}
assert nearest_neighbor(x, tSet) == "Class_C"
def test_nearest_neighbor_single_element():
x = (1.0, 1.0)
... | [
{
"docstring": "Calculate the Euclidean distance between two points p and q.",
"function_declaration": "def euclidean_distance(p, q):",
"function_name": "euclidean_distance",
"parameter_list": "(p, q)"
},
{
"docstring": "Find the label of the closest vector to x in tSet using Euclidean dista... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import Tuple, Dict, Any\n\ndef euclidean_distance(v1: Tuple[float, ...], v2: Tuple[float, ...]) -> float:\n \"\"\"\n Calculate ... | trial_gpt4o_1 | {
"original_instruction": "You are tasked with implementing a classification system using the Nearest Neighbor algorithm. Given a vector \\(x\\) and a training set \\(tSet\\), your objective is to find the closest neighbor to \\(x\\) in \\(tSet\\) using Euclidean distance, and return the label associated with that ne... | 0.646861 | Data_Structure_16937 | C | [
"euclidean_distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a015bb7e3cc78a02f4587fd31de80124ad780810 | 0958fad9f5ac2ee2fb8831b4810fe3a6480f5567 | |||
v1.0 | complete | Data_Structure | Data_Structure_17305_C | class Node:
def __init__(self, value=None):
self.val = value
self.next = None
def find_intersection(headA: Node, headB: Node) -> Node:
""" Find the intersecting node of two singly linked lists.
Return the node at which the intersection occurs, or None.
>>> node1 = Node(1)
>>> n... | class Node:
def __init__(self, value=None):
self.val = value
self.next = None
def get_length(head):
length = 0
while head is not None:
head = head.next
length += 1
return length
def find_intersection(headA: Node, headB: Node) -> Node:
# Step 1: Get lengths of both l... | from solution import Node, find_intersection
def test_intersected_lists():
node1 = Node(1)
node3 = Node(3)
node5 = Node(5)
node7 = Node(7)
node9 = Node(9)
node11 = Node(11)
node2 = Node(2)
node4 = Node(4)
node6 = Node(6)
node1.next = node3
node3.next = node5
node5.... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, value=None):\n self.val = value\n self.next = None\n\ndef get_length(head):\n length = 0\n while head ... | trial_gpt4o_0 | {
"original_instruction": "### Linked List Intersection Detection\n\n**Problem Statement**:\n\nYou are given two singly linked lists that potentially share a common tail. Write a function `find_intersection(headA, headB)` which returns the intersected node. If the two linked lists have no intersection at all, return ... | 0.537451 | Data_Structure_17305 | C | [
"get_length",
"find_intersection"
] | 2 | [
[
"find_intersection",
"get_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | e81e93c411b8361a35c06a7671190c1448cb0684 | 0be91558591e9d954ee0dd5fe66ab6acb60bbeac | |||
v1.0 | complete | Data_Structure | Data_Structure_17288_C | from typing import List
def matrix_transform(matrix: List[List[int]], transformation: str) -> List[List[int]]:
"""Transforms the given matrix according to the specified transformation type.
Parameters:
matrix (List[List[int]]): The input square matrix.
transformation (str): The type of transformation ... | from typing import List
def rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:
N = len(matrix)
return [[matrix[N - j - 1][i] for j in range(N)] for i in range(N)]
def rotate_counterclockwise(matrix: List[List[int]]) -> List[List[int]]:
N = len(matrix)
return [[matrix[j][N - i - 1] for j in ... | from solution import matrix_transform
def test_rotate_clockwise():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
expected = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
assert matrix_transform(matrix, 'rotate_clockwise') == expected
def test_rotate_countercloc... | [
{
"docstring": null,
"function_declaration": "def rotate_clockwise(matrix):",
"function_name": "rotate_clockwise",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def rotate_counterclockwise(matrix):",
"function_name": "rotate_counterclockwise",
"par... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:\n N = len(matrix)\n return [[matrix[N - j - 1][i] for j in ... | trial_gpt4o_0 | {
"original_instruction": "### Question: Matrix Transformation Implementation\n\nYou have been provided with a matrix transformation module that consists of several functions to rotate and invert matrices.\n\nWrite a Python function `matrix_transform(matrix: List[List[int]], transformation: str) -> List[List[int]]` w... | 0.546513 | Data_Structure_17288 | C | [
"rotate_clockwise",
"rotate_counterclockwise",
"top_left_invert",
"bottom_left_invert",
"matrix_transform"
] | 5 | [
[
"matrix_transform",
"bottom_left_invert"
],
[
"matrix_transform",
"rotate_clockwise"
],
[
"matrix_transform",
"rotate_counterclockwise"
],
[
"matrix_transform",
"top_left_invert"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 7ebfffecfe26319ee799602df61c9502fd5ba8ef | c4c1f5c9dca91fe5fde19b05cfe4100b40773afb | |||
v1.0 | complete | Data_Structure | Data_Structure_17685_C | def maximum_flow_dfs(adjacency_matrix: list[list[int]]) -> int:
"""
Given an n x n adjacency matrix representing the capacities of the edges in a flow network,
return the maximum flow from the source node (node 0) to the sink node (node n-1).
Parameters:
adjacency_matrix (list[list[int]]): The adja... | def dfs(capacity, flow, source, sink, visited):
stack = [source]
parents_map = {source: None}
while stack:
current_node = stack.pop()
if current_node == sink:
break
for neighbor, cap in enumerate(capacity[current_node]):
if cap - flow[current_node, neighb... | from solution import maximum_flow_dfs
def test_basic_flow():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow_dfs(graph) == 23
def test_no_path():
... | [
{
"docstring": null,
"function_declaration": "def dfs(capacity, flow, source, sink, visited):",
"function_name": "dfs",
"parameter_list": "(capacity, flow, source, sink, visited)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_dfs(adjacency_matrix):",
"function_nam... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def dfs(capacity, flow, source, sink, visited):\n stack = [source]\n parents_map = {source: None}\n \n while stack:\n current_node = stack.... | trial_gpt4o_0 | {
"original_instruction": "### Maximum Flow Problem\n\n#### Background\nYou are given a network of pipes represented as a graph where:\n- Each node represents a junction.\n- Each edge represents a pipe with a certain capacity.\n- The first node (index 0) is the source from which water is sent.\n- The last node (index... | 0.588001 | Data_Structure_17685 | C | [
"dfs",
"maximum_flow_dfs"
] | 2 | [
[
"maximum_flow_dfs",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bad198d64ca7e34793037404804c5beb356acd65 | 33bddefba9134626b07517fd3d31fde30353ecf4 | |||
v1.0 | complete | Data_Structure | Data_Structure_15176_C | def merge_sort_and_count(arr):
"""
Sorts the array in ascending order and counts inversions.
:param arr: List[int] - a list of integers to be sorted.
:return: Tuple(List[int], int) - A tuple containing the sorted list
and the number of inversions.
"""
def m... | def merge_sort_and_count(arr):
"""
Sorts the array in ascending order and counts inversions.
:param arr: List[int] - a list of integers to be sorted.
:return: Tuple(List[int], int) - A tuple containing the sorted list
and the number of inversions.
"""
if len... | from solution import merge_sort_and_count
def test_merge_sort_and_count_empty():
assert merge_sort_and_count([]) == ([], 0)
def test_merge_sort_and_count_single_element():
assert merge_sort_and_count([1]) == ([1], 0)
def test_merge_sort_and_count_sorted_array():
assert merge_sort_and_count([1, 2, 3, 4, 5... | [
{
"docstring": "Sorts the array in ascending order and counts inversions.\n\n:param arr: List[int] - a list of integers to be sorted.\n:return: Tuple(List[int], int) - A tuple containing the sorted list \n and the number of inversions.",
"function_declaration": "def merge_sort... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort_and_count(arr):\n \"\"\"\n Sorts the array in ascending order and counts inversions.\n \n :param arr: List[int] - a list of integer... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Implementation and Count Inversions\n\n**Scenario**: You are implementing a sorting utility similar to what one might find in a standard library. However, in addition to sorting the array, you are tasked with calculating the number of inversions in the array. An inversion is ... | 0.624226 | Data_Structure_15176 | C | [
"merge_sort_and_count",
"merge_and_count"
] | 2 | [
[
"merge_sort_and_count",
"merge_and_count"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 99aeab181f44c00441317e4465d28582c46c2769 | 1195a75dfc3a7fb06123d98a89a768e3a1d12f95 | |||
v1.0 | complete | Data_Structure | Data_Structure_17381_C | from typing import List
def is_prime(n: int) -> bool:
"""
Helper function to check if a number is prime.
Args:
n: int - An integer.
Returns:
bool - True if 'n' is a prime number, False otherwise.
"""
pass
def count_primes(nums: List[int]) -> int:
"""
Count the number of prim... | from math import isqrt
from typing import List
def is_prime(n: int) -> bool:
"""
Helper function to check if a number is prime.
Args:
n: int - An integer.
Returns:
bool - True if 'n' is a prime number, False otherwise.
"""
if n <= 1:
return False
if n <= 3:
return ... | from solution import count_primes, is_prime
def test_is_prime():
assert not is_prime(1)
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(9)
assert is_prime(17)
assert not is_prime(18)
def test_count_primes_mixed_numbers():
assert c... | [
{
"docstring": "Helper function to check if a number is prime.\n\nArgs:\nn: int - An integer.\n\nReturns:\nbool - True if 'n' is a prime number, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Count the nu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(num: int) -> bool:\n \"\"\"\n Check if a number is a prime number.\n \n Args:\n num: int - The number t... | trial_gpt4o_1 | {
"original_instruction": "#### Problem Statement\nYou are given a list of integers and you need to determine how many of them are prime numbers. Implement a function that takes a list of integers and returns a count of the prime numbers in the list.\n\n#### Function Signature\n```python\ndef count_primes(nums: List[... | 0.78261 | Data_Structure_17381 | C | [
"is_prime",
"count_primes"
] | 2 | [
[
"count_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4ade3da6b0d1d05d3c692660164066bc6e5e0300 | 3a3daa4ba9cc2737896a0c2bbe095306ecc3c062 | |||
v1.0 | complete | Data_Structure | Data_Structure_17495_C | from typing import List
def interpolation_search(array: List[int], key: int) -> int:
low = 0
high = len(array) - 1
while low <= high and array[low] <= key <= array[high]:
if low == high:
if array[low] == key:
return low
return -1
pos = low + ((high ... | from typing import List
def interpolation_search(array: List[int], key: int) -> int:
low = 0
high = len(array) - 1
while low <= high and array[low] <= key <= array[high]:
if low == high:
if array[low] == key:
return low
return -1
pos = low + ((high ... | from solution import multi_interpolation_search
def test_search_present_keys():
array = [5, 10, 12, 14, 17, 20, 21]
search_keys = [10, 12]
assert multi_interpolation_search(array, search_keys) == [1, 2]
def test_search_absent_keys():
array = [5, 10, 12, 14, 17, 20, 21]
search_keys = [55, -5]
a... | [
{
"docstring": null,
"function_declaration": "def interpolation_search(array, key):",
"function_name": "interpolation_search",
"parameter_list": "(array, key)"
},
{
"docstring": null,
"function_declaration": "def multi_interpolation_search(array, search_keys):",
"function_name": "mul... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef interpolation_search(array: List[int], key: int) -> int:\n low = 0\n high = len(array) - 1\n\n while low <= high and a... | trial_gpt4o_0 | {
"original_instruction": "You have been given an implementation of the Interpolation Search algorithm. Your task is to implement a function that uses this algorithm to find multiple search keys in a sorted array. Specifically, you need to return a list of indices corresponding to each search key. If a search key is ... | 0.542907 | Data_Structure_17495 | C | [
"interpolation_search",
"multi_interpolation_search"
] | 2 | [
[
"multi_interpolation_search",
"interpolation_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5a6487e3b93fd4c6b126ec0391632bcf8dcae935 | fc7b4633591cdbbcb013f22e0d719ee03b22532b | |||
v1.0 | complete | Data_Structure | Data_Structure_17581_C | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Helper function to find the insertion point for `val` in `array`.
Uses binary search for efficiency.
>>> search_insert([1, 3, 5, 7], 4)
2
>>> search_insert([1, 3, 5, 7], 0)
0
>>> search_insert([1, 3, 5, 7... | def search_insert(array, val):
"""
Helper function to find the insertion point for `val` in `array`.
Uses binary search for efficiency.
"""
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
el... | from solution import search_insert, insert_and_sort
def test_search_insert_middle():
assert search_insert([1, 3, 5, 7], 4) == 2
def test_search_insert_smallest():
assert search_insert([1, 3, 5, 7], 0) == 0
def test_search_insert_largest():
assert search_insert([1, 3, 5, 7], 8) == 4
def test_search_inser... | [
{
"docstring": "Helper function to find the insertion point for `val` in `array`.\nUses binary search for efficiency.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "Inserts each value from `val... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(array, val):\n \"\"\"\n A helper function to find the index where the value should be inserted\n to maintain the sorted order.\n ... | trial_gpt4o_2 | {
"original_instruction": "You are tasked to write a function that employs the `search_insert` helper method to efficiently insert elements into an already sorted list such that the list remains sorted after each insertion. \n\n### Task Description\nWrite a function `insert_and_sort(sorted_list, values)` that takes a... | 0.630688 | Data_Structure_17581 | C | [
"search_insert",
"insert_and_sort"
] | 2 | [
[
"insert_and_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | da24e3e96a44725615b271db18f1d1c97aef822c | af1ca1ef7329a3d8f465489ebdb4a7bc9367c9fc | |||
v1.0 | complete | Data_Structure | Data_Structure_18092_C | def optimized_insertion_sort(arr: list) -> list:
"""
Implement an optimized version of the Insertion Sort algorithm that uses
binary search to find the insertion position, which handles large, nearly
sorted datasets efficiently.
Parameters:
arr (list): A list of integers that needs to be ... | def binary_search(arr, val, start, end):
# We need to use binary search to find the correct insertion position
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
start = mid + 1
else:
end = mid
return start
def optimized_insertion_sort(arr):
"... | from solution import optimized_insertion_sort
def test_sorted_array():
assert optimized_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert optimized_insertion_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_unsorted_array():
assert optimized_insertion_sort([5, 2,... | [
{
"docstring": null,
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "This function sorts an array using an optimized version of insertion sort.\nIt uses binary search to find t... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binary_search(arr, val, start, end):\n \"\"\"\n Helper function that uses binary search to find the position \n where 'val' should be inserted wi... | trial_gpt4o_2 | {
"original_instruction": "As a software engineer, your task is to create an optimized version of the Insertion Sort algorithm. You will improve the provided baseline insertion sort algorithm by implementing a feature that ensures the function handles large, nearly sorted datasets efficiently.\n\nImplement the functi... | 0.622438 | Data_Structure_18092 | C | [
"binary_search",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 56ba69fb145c249e0a738f164ee20a14c47e832c | e4699a5ba5197d2f2d989ef713de8c2f4192eb56 | |||
v1.0 | complete | Data_Structure | Data_Structure_17037_C | def custom_heap_sort(arr, simulation=False):
"""
Sorts an array using the Heap Sort algorithm with an optional simulation mode.
Parameters:
arr (List[int]): An array of integers that needs to be sorted.
simulation (bool): Optional boolean to output the state of the array at each iteration of t... | def heapify(arr, n, i, simulation):
smallest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[l] < arr[smallest]:
smallest = l
if r < n and arr[r] < arr[smallest]:
smallest = r
if smallest != i:
arr[i], arr[smallest] = arr[smallest], arr[i]
if simulation:
... | from solution import custom_heap_sort
def test_custom_heap_sort_empty():
assert custom_heap_sort([]) == []
def test_custom_heap_sort_single_element():
assert custom_heap_sort([1]) == [1]
def test_custom_heap_sort_sorted_array():
assert custom_heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_custom... | [
{
"docstring": null,
"function_declaration": "def heapify(arr, n, i, simulation):",
"function_name": "heapify",
"parameter_list": "(arr, n, i, simulation)"
},
{
"docstring": null,
"function_declaration": "def custom_heap_sort(arr, simulation=False):",
"function_name": "custom_heap_so... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def custom_heap_sort(arr, simulation=False):\n def heapify(arr, n, i):\n smallest = i\n left = 2 * i + 1\n right = 2 * i + 2\n ... | trial_gpt4o_1 | {
"original_instruction": "#### Question Prompt\n\nDesign and implement a function that sorts an array using the Heap Sort algorithm. Specifically, implement the heap sort using a modified version of the Min Heap data structure, but also allow an optional simulation mode that outputs the state of the array at each it... | 0.675208 | Data_Structure_17037 | C | [
"heapify",
"custom_heap_sort"
] | 2 | [
[
"custom_heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9bfb78575935bcec8d7ad2b14fe345b247094b8d | 4c96c4a2a5e1ce15da9f4007644919dddeb4d0d0 | |||
v1.0 | complete | Data_Structure | Data_Structure_17553_C | def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def find... | def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def find... | from solution import find_primes_in_range
def test_find_primes_in_range_small():
assert find_primes_in_range(1, 10) == [2, 3, 5, 7]
assert find_primes_in_range(10, 50) == [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
def test_find_primes_in_range_single_prime():
assert find_primes_in_range(29, 29) == [29]
... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers within the range [start, end].",
"function_declaration": "def find_primes_in_range(start, ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Determines if n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n ... | trial_gpt4o_2 | {
"original_instruction": "You are assigned to implement a prime-checking utility as part of a broader cryptographic application. A prime number is defined as a number that is greater than 1 and is not divisible by any number other than 1 and itself.\n\n#### Function Requirements\n\nYou need to implement the function... | 0.850258 | Data_Structure_17553 | C | [
"is_prime",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aee59e012789f8cf0050dc5cf245b2e1dde17b4d | 9ee89b47469c8f6ea40be55c412c956584017a04 | |||
v1.0 | complete | Data_Structure | Data_Structure_17871_C | from typing import List
def unique_subsets(nums: List[int]) -> List[List[int]]:
"""
Returns all unique subsets of a given list of integers, including handling duplicates.
>>> unique_subsets([1, 2, 2])
[[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
>>> unique_subsets([1, 2, 2, 3])
[[], [1],... | from typing import List
def unique_subsets(nums: List[int]) -> List[List[int]]:
"""
Returns all unique subsets of a given list of integers, including handling duplicates.
"""
nums.sort() # Sort the array to handle duplicates easily
result = []
backtrack(nums, 0, [], result)
return result
... | from solution import unique_subsets
def test_unique_subsets_empty_input():
assert unique_subsets([]) == [[]]
def test_unique_subsets_no_duplicates():
assert unique_subsets([1, 2, 3]) == [
[],
[1],
[1, 2],
[1, 2, 3],
[1, 3],
[2],
[2, 3],
[3]
]... | [
{
"docstring": "Returns all unique subsets of a given list of integers, including handling duplicates.",
"function_declaration": "def unique_subsets(nums):",
"function_name": "unique_subsets",
"parameter_list": "(nums)"
},
{
"docstring": null,
"function_declaration": "def backtrack(nums,... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef unique_subsets(nums: List[int]) -> List[List[int]]:\n \"\"\"\n Returns all unique subsets of the input list nums.\n \"... | trial_gpt4o_1 | {
"original_instruction": "### Scenario\nYou are provided a collection of integers that might contain duplicates. You need to generate all possible subsets (the power set) of these integers such that the solution set does not contain duplicate subsets.\n\nWrite a function `unique_subsets(nums: List[int]) -> List[List... | 0.625255 | Data_Structure_17871 | C | [
"unique_subsets",
"backtrack"
] | 2 | [
[
"unique_subsets",
"backtrack"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 75c6ea03847b7cb1dc9fea36f9763e93d41ad55b | 0dcfe6e1df238bf8e560e9611698024907be74a4 | |||
v1.0 | complete | Data_Structure | Data_Structure_17376_C | from typing import List
def optimized_invert_matrix(matrix: List[List[int]]) -> List[List[int]]:
""" Invert an n x n matrix using the optimized method.
The function takes a square matrix of size n x n with integer elements
and returns its inverse if it exists. If the matrix is not square or
is s... | from typing import List
def determinant(matrix: List[List[int]]) -> int:
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for c in range(n):
sub_matrix = [
[matrix[r][cc] for c... | from solution import optimized_invert_matrix
def test_invert_2x2_matrix():
matrix = [
[4, 7],
[2, 6]
]
expected_inverse = [
[0.6, -0.7],
[-0.2, 0.4]
]
assert optimized_invert_matrix(matrix) == expected_inverse
def test_invert_3x3_matrix():
matrix = [
[1,... | [
{
"docstring": null,
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def get_matrix_of_minors(matrix):",
"function_name": "get_matrix_of_minors",
"parameter_list": "(... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef get_cofactor(matrix, i, j):\n return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]\n\ndef determinant(matrix)... | trial_gpt4o_9 | {
"original_instruction": "As a data scientist, you are tasked to develop an application that requires matrix inversion for solving linear algebra problems. You are given a helper function to invert an n x n matrix which follows the cofactor method to find the inverse. Your objective is to optimize and ensure that th... | 0.539807 | Data_Structure_17376 | C | [
"determinant",
"get_matrix_of_minors",
"transpose",
"get_cofactor_matrix",
"optimized_invert_matrix"
] | 5 | [
[
"get_cofactor_matrix",
"get_matrix_of_minors"
],
[
"get_matrix_of_minors",
"determinant"
],
[
"optimized_invert_matrix",
"determinant"
],
[
"optimized_invert_matrix",
"get_cofactor_matrix"
],
[
"optimized_invert_matrix",
"transpose"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 6bbce80b80631823ef995ae78a522d38d27241f5 | 866c2346c66da044d478aacbc813702aafa0817c | |||
v1.0 | complete | Data_Structure | Data_Structure_17809_C | def optimized_quick_sort(arr):
"""
Implement Quick Sort with the median-of-three rule and switch to Insertion Sort for small subarrays to optimize performance.
Input:
arr (List[int]): An unsorted list of integers
Output:
List[int]: A sorted list of integers
Example:
>>> optimized_qui... | def insertion_sort(arr, left, right):
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def median_of_three(arr, low, high):
mid = (low + high) // 2
if arr[low] > ... | from solution import optimized_quick_sort
def test_optimized_quick_sort_sorted_array():
arr = [1, 2, 3, 4, 5]
assert optimized_quick_sort(arr) == [1, 2, 3, 4, 5]
def test_optimized_quick_sort_reverse_sorted_array():
arr = [5, 4, 3, 2, 1]
assert optimized_quick_sort(arr) == [1, 2, 3, 4, 5]
def test_op... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insertion_sort(arr, left, right):\n for i in range(left + 1, right + 1):\n key = arr[i]\n j = i - 1\n while j >= left and arr[j] >... | trial_gpt4o_2 | {
"original_instruction": "**Scenario**:\nYou have been hired by a tech company to optimize their database sorting functionality. The database primarily stores numerical records which need to be sorted frequently for reporting purposes. The current implementation uses Quick Sort but exhibits poor performance with cer... | 0.590722 | Data_Structure_17809 | C | [
"insertion_sort",
"median_of_three",
"partition",
"quick_sort",
"optimized_quick_sort"
] | 5 | [
[
"optimized_quick_sort",
"quick_sort"
],
[
"partition",
"median_of_three"
],
[
"quick_sort",
"insertion_sort"
],
[
"quick_sort",
"partition"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | cda236b8a929351081de720cfd7572588ca3d21b | 9259231077b0a5e3b1299bf3616b5dd92053091f | |||
v1.0 | complete | Data_Structure | Data_Structure_17718_C | from typing import List
def next_sort(arr: List[float]) -> List[float]:
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def bucket_sort(arr: List[float]) -> List[fl... | from typing import List
# This function simulates the sorting mechanism within each bucket.
# In this example, let's use a simple insertion sort for sorting the buckets.
def next_sort(arr: List[float]) -> List[float]:
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key ... | from solution import bucket_sort
def test_bucket_sort_sample1():
arr = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]
expected = [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
assert bucket_sort(arr) == expected
def test_bucket_sort_sample2():
arr = [0.4, 0.1, 0.2, 0.3]
... | [
{
"docstring": null,
"function_declaration": "def next_sort(arr):",
"function_name": "next_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def bucket_sort(arr):",
"function_name": "bucket_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef next_sort(bucket: List[float]) -> List[float]:\n \"\"\"\n A simple insertion sort implementation to sort individual bucke... | trial_gpt4o_2 | {
"original_instruction": "You are given a list of floating-point numbers with values uniformly distributed in the range [0, 1). Your task is to implement the `bucket_sort` algorithm as described, using the `next_sort` function for sorting individual buckets. This question aims to evaluate your understanding of the b... | 0.626483 | Data_Structure_17718 | C | [
"next_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"next_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 26167db80d30c8172e3d9cceaa9b0a7a4a4bf326 | 6be626e5e137695076d8052f768a90ba3b8836fe | |||
v1.0 | complete | Data_Structure | Data_Structure_17345_C | def reconstruct_inorder(preorder: list, postorder: list) -> list:
""" Reconstruct the full binary tree from its preorder and postorder traversal lists and return the inorder traversal of the tree.
>>> reconstruct_inorder([1, 2, 4, 5, 3, 6, 7], [4, 5, 2, 6, 7, 3, 1])
[4, 2, 5, 1, 6, 3, 7]
>>> reconstruct... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(preorder, postorder):
if not preorder or not postorder:
return None
root_val = preorder.pop(0)
root = TreeNode(root_val)
if pr... | def test_reconstruct_inorder_case_1():
preorder = [1, 2, 4, 5, 3, 6, 7]
postorder = [4, 5, 2, 6, 7, 3, 1]
assert reconstruct_inorder(preorder, postorder) == [4, 2, 5, 1, 6, 3, 7]
def test_reconstruct_inorder_single_node():
preorder = [1]
postorder = [1]
assert reconstruct_inorder(preorder, post... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n... | trial_gpt4o_2 | {
"original_instruction": "### Question: Reconstructing a Full Binary Tree from Preorder and Postorder Traversals\n\n**Context**:\nYou are a software engineer tasked with restoring the original structure of a full binary tree from given traversal data. You've been provided two sequences that represent the preorder an... | 0.52699 | Data_Structure_17345 | C | [
"buildTree",
"inorderTraversal",
"reconstruct_inorder"
] | 3 | [
[
"reconstruct_inorder",
"buildTree"
],
[
"reconstruct_inorder",
"inorderTraversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | false | [] | true | f8238b816a769c0ac5b083236ca966eb181099db | ef100c976e95f2a49d93bfd8ffe6f658f970a43a | |||
v1.0 | complete | Data_Structure | Data_Structure_17371_C | def trailing_zero_count(x):
""" Calculate the number of trailing zeros in the binary representation of x.
>>> trailing_zero_count(0) 32
>>> trailing_zero_count(1) 0
>>> trailing_zero_count(2) 1
>>> trailing_zero_count(3) 0
>>> trailing_zero_count(4) 2
>>> trailing_zero_count(40) 3
"""
... | def trailing_zero_count(x):
"""
Calculate the number of trailing zeros in the binary representation of x.
"""
if x == 0:
return 32 # Assuming 32-bit integer for zero handling
count = 0
while (x & 1) == 0:
x >>= 1
count += 1
return count
def gcd_bitwise(a, b):
""... | from solution import trailing_zero_count, gcd_bitwise, lcm
def test_trailing_zero_count():
assert trailing_zero_count(0) == 32
assert trailing_zero_count(1) == 0
assert trailing_zero_count(2) == 1
assert trailing_zero_count(3) == 0
assert trailing_zero_count(4) == 2
assert trailing_zero_count(4... | [
{
"docstring": "Calculate the number of trailing zeros in the binary representation of x.",
"function_declaration": "def trailing_zero_count(x):",
"function_name": "trailing_zero_count",
"parameter_list": "(x)"
},
{
"docstring": "Calculate the GCD of a and b using bitwise operations.",
"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def trailing_zero_count(x):\n \"\"\"\n Calculate the number of trailing zeros in the binary representation of x.\n \"\"\"\n if x == 0:\n re... | trial_gpt4o_0 | {
"original_instruction": "### Coding Challenge: Advanced GCD and Binary Algorithms\n\n#### Scenario:\nYour task is to implement a combined function to compute both the Greatest Common Divisor (GCD) and the Least Common Multiple (LCM) of two non-negative integers using efficient algorithms. Additionally, provide a fu... | 0.657878 | Data_Structure_17371 | C | [
"trailing_zero_count",
"gcd_bitwise",
"lcm"
] | 3 | [
[
"gcd_bitwise",
"trailing_zero_count"
],
[
"lcm",
"gcd_bitwise"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 762a8fa9cba323a66b7dbd68743cebff2b737b22 | d8433fb93de21fa32dad88e6700456a202c82466 | |||
v1.0 | complete | Data_Structure | Data_Structure_17278_C | def efficient_nearest_neighbor(x, tSet):
"""
Returns the label of the nearest neighbor to the point `x` in the training set `tSet`.
Parameters:
x (tuple): The input point.
tSet (dict): The training set where keys are tuples (points) and values are labels.
Returns:
Any: The label of the nea... | import math
def euclidean_distance(p1, p2):
return math.sqrt(sum((a-b)**2 for a, b in zip(p1, p2)))
def efficient_nearest_neighbor(x, tSet):
"""
Returns the label of the nearest neighbor to the point `x` in the training set `tSet`.
Parameters:
x (tuple): The input point.
tSet (dict): The ... | from solution import efficient_nearest_neighbor
def test_efficient_nearest_neighbor_basic():
x = (1, 2)
tSet = { (2, 3): 'A', (1, 1): 'B', (4, 5): 'C' }
assert efficient_nearest_neighbor(x, tSet) == 'B'
def test_efficient_nearest_neighbor_empty_set():
x = (1, 2)
tSet = {}
assert efficient_near... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(p1, p2):",
"function_name": "euclidean_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": "Returns the label of the nearest neighbor to the point `x` in the training set `tSet`.\n\nParameters:\nx (tuple): The input p... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef efficient_nearest_neighbor(x, tSet):\n \"\"\"\n Finds the label of the closest point in the training set to the input point using Euc... | trial_gpt4o_1 | {
"original_instruction": "### Question: Implement an Efficient Nearest Neighbor Algorithm\n\n**Context:**\n\nYou are working on a machine learning problem where you need to classify points based on their nearest neighbors in a training set. The current implementation calculates the Euclidean distance to each point i... | 0.643298 | Data_Structure_17278 | C | [
"euclidean_distance",
"efficient_nearest_neighbor"
] | 2 | [
[
"efficient_nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 75230e02a5412eb5eac55489d0c887bc7b1b2a5e | 4a34d496b8e40014cb01f6fe8f456a48cbf7bc18 | |||
v1.0 | complete | Data_Structure | Data_Structure_16007_C | from typing import List
def optimized_max_flow(capacity: List[List[int]], source: int, sink: int) -> int:
""" Optimize the network flow in an urban transportation system.
Given a directed graph representing the transportation network with nodes as junctions and edges as roads with certain capacities, comp... | from typing import List
def bfs(capacity, source, sink, parent):
visited = [False] * len(capacity)
queue = []
queue.append(source)
visited[source] = True
while queue:
u = queue.pop(0)
for idx, val in enumerate(capacity[u]):
if visited[idx] == False and val > 0:
... | from solution import optimized_max_flow
def test_optimized_max_flow_example1():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert opti... | [
{
"docstring": null,
"function_declaration": "def bfs(capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def optimized_max_flow(capacity, source, sink):",
"function_name": "o... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bfs(capacity, source, sink, parent):\n visited = [False] * len(capacity)\n queue = []\n queue.append(source)\n visi... | trial_gpt4o_0 | {
"original_instruction": "### Question: Maximum Flow Network Optimization\n\nYou are tasked with optimizing a network flow in an urban transportation system. Given a directed graph representing the transportation network with nodes as junctions and edges as roads with certain capacities, you are required to compute ... | 0.631991 | Data_Structure_16007 | C | [
"bfs",
"optimized_max_flow"
] | 2 | [
[
"optimized_max_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7e71761202fcdf572a7029f5ce2d772023e3eb24 | 9ee2d74066165a6a07c649f8a144891b2d200b74 | |||
v1.0 | complete | Data_Structure | Data_Structure_18647_C | def fibonacci_matrix(n: int) -> int:
"""
Compute the nth Fibonacci number using matrix exponentiation.
The result should be returned modulo 10^9 + 7.
>>> fibonacci_matrix(0)
0
>>> fibonacci_matrix(1)
1
>>> fibonacci_matrix(10)
55
>>> fibonacci_matrix(100) == 354224848179261... | def matrix_multiply(A, B, mod):
"""
Multiplies two 2x2 matrices A and B under modulo `mod`.
"""
return [
[(A[0][0] * B[0][0] + A[0][1] * B[1][0]) % mod, (A[0][0] * B[0][1] + A[0][1] * B[1][1]) % mod],
[(A[1][0] * B[0][0] + A[1][1] * B[1][0]) % mod, (A[1][0] * B[0][1] + A[1][1] * B[1][1])... | import pytest
from solution import fibonacci_matrix
def test_fibonacci_matrix_base_cases():
assert fibonacci_matrix(0) == 0
assert fibonacci_matrix(1) == 1
def test_fibonacci_matrix_small_numbers():
assert fibonacci_matrix(2) == 1
assert fibonacci_matrix(3) == 2
assert fibonacci_matrix(4) == 3
... | [
{
"docstring": "Multiplies two 2x2 matrices A and B under modulo `mod`.",
"function_declaration": "def matrix_multiply(A, B, mod):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B, mod)"
},
{
"docstring": "Computes the n-th power of a 2x2 matrix under modulo `mod`.",
"funct... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fibonacci_matrix(n: int) -> int:\n MOD = 10**9 + 7\n\n def matrix_mult(A, B):\n \"\"\"Multiplies two 2x2 matrices A and B under modulo.\"\"\"... | trial_gpt4o_8 | {
"original_instruction": "Write a Python function `fibonacci_matrix(n: int) -> int` to compute the nth Fibonacci number using matrix exponentiation. \n\n### Input:\n* A single integer \\( n \\) (0 ≤ n ≤ 10^18)\n\n### Output:\n* The nth Fibonacci number.\n\n### Constraints:\n* The result should be returned modulo \\(... | 0.762755 | Data_Structure_18647 | C | [
"matrix_multiply",
"matrix_power",
"fibonacci_matrix"
] | 3 | [
[
"fibonacci_matrix",
"matrix_power"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d0d43a7013946669cf3617911e59e862a2e86d95 | dff50535b5603e00619d7e2de9262a66d70f6d6d | |||
v1.0 | complete | Data_Structure | Data_Structure_17451_C | def miller_rabin_test(n: int, k: int = 40) -> bool:
""" Miller-Rabin Primality Test to check if a number is prime.
>>> miller_rabin_test(11)
True
>>> miller_rabin_test(2)
True
>>> miller_rabin_test(1)
False
>>> miller_rabin_test(15)
False
"""
pass
def modular_inverse(a: int,... | import random
# Miller-Rabin Primality Test for secure primality check
def miller_rabin_test(n, k=40):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
r, s = 0, n - 1
while s % 2 == 0:
r += 1
s //= 2
for _ in range(k):
... | def test_miller_rabin_test():
assert miller_rabin_test(11) == True
assert miller_rabin_test(2) == True
assert miller_rabin_test(1) == False
assert miller_rabin_test(15) == False
def test_enhanced_diffie_hellman_key_exchange():
p = 99999989 # A large pseudo prime
a = 2
shared_key = enhanced... | [
{
"docstring": null,
"function_declaration": "def miller_rabin_test(n, k=40):",
"function_name": "miller_rabin_test",
"parameter_list": "(n, k=40)"
},
{
"docstring": null,
"function_declaration": "def modular_inverse(a, m):",
"function_name": "modular_inverse",
"parameter_list": ... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\n# Miller-Rabin Primality Test for secure primality check\ndef miller_rabin_test(n, k=40):\n if n <= 1:\n return False\n if n <= ... | trial_gpt4o_0 | {
"original_instruction": "### Diffie-Hellman Key Exchange Enhancement\n\nDue to the reliance on the security of the Diffie-Hellman key exchange algorithm, it's essential to handle large primes and ensure efficient calculations. Given the snippets above, your task is to implement an enhanced version of the Diffie-Hel... | 0.528058 | Data_Structure_17451 | C | [
"miller_rabin_test",
"modular_inverse",
"pollards_rho_order",
"enhanced_diffie_hellman_key_exchange"
] | 4 | [
[
"enhanced_diffie_hellman_key_exchange",
"miller_rabin_test"
],
[
"enhanced_diffie_hellman_key_exchange",
"pollards_rho_order"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | e0eb7a5828f572e89bac4dde123cf81621e51b8e | cab4bc7aa007be1c417046028de27a43071bb804 | |||
v1.0 | complete | Data_Structure | Data_Structure_17859_C | class Node:
def __init__(self, val: int):
self.val = val
self.next = None
def intersection(h1: Node, h2: Node) -> Optional[Node]:
""" Find the intersection node of two singly linked lists, if it exists.
>>> a1 = Node(1)
>>> b1 = Node(3)
>>> c1 = Node(5)
>>> d = Node(7)
>>> e... | class Node:
def __init__(self, val: int):
self.val = val
self.next = None
def get_length_and_tail(node: Node) -> tuple:
length = 0
while node:
length += 1
if not node.next:
return length, node
node = node.next
return length, None
def intersection(h1:... | def test_intersection():
from solution import Node, intersection
# Test case 1: Intersecting lists
a1 = Node(1)
b1 = Node(3)
c1 = Node(5)
d = Node(7)
e = Node(9)
f = Node(11)
a2 = Node(2)
b2 = Node(4)
c2 = Node(6)
a1.next = b1
b1.next = c1
c1.next = d
d... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Optional\n\nclass Node:\n def __init__(self, val: int):\n self.val = val\n self.next = None\n\ndef intersection(h1: Node, ... | trial_gpt4o_2 | {
"original_instruction": "#### Job Requirements\nImplement a function `def intersection(h1: Node, h2: Node) -> Optional[Node]:` which takes two singly linked lists and returns the node where they intersect. If the two linked lists do not intersect, return `None`. \n\nTo help you understand the problem, consider the ... | 0.541242 | Data_Structure_17859 | C | [
"get_length_and_tail",
"intersection"
] | 2 | [
[
"intersection",
"get_length_and_tail"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | dbf4ffffc9266de7d77fc054920c1bb7ab368248 | 776f594a2040bcf79578448d18b6371d59bc3608 | |||
v1.0 | complete | Data_Structure | Data_Structure_17592_C | def generate_key(bits: int, seed: int = None) -> Tuple[int, int, int]:
""" Generate RSA keys.
:param bits: Number of bits in the modulus n.
:param seed: Seed for random number generation.
:return: Tuple (n, e, d) representing modulus, public exponent, and private exponent.
>>> n, e, d = generate_key... | import random
from sympy import isprime, mod_inverse
def generate_prime(bits, rng):
while True:
candidate = rng.getrandbits(bits)
if isprime(candidate):
return candidate
def generate_key(bits, seed=None):
rng = random.Random(seed)
p = generate_prime(bits // 2, rng)
q = gene... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_encrypt_decrypt_small_data():
n, e, d = generate_key(16, seed=42)
data = 20
encrypted_data... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bits, rng):",
"function_name": "generate_prime",
"parameter_list": "(bits, rng)"
},
{
"docstring": null,
"function_declaration": "def generate_key(bits, seed=None):",
"function_name": "generate_key",
"parameter_list... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_key(bits, seed=None):\n \"\"\"\n Generates RSA keys of specified bit length.\n ... | trial_gpt4o_2 | {
"original_instruction": "### RSA Implementation and Encryption/Decryption\n\nImplement the RSA algorithm by completing the three functions: `generate_key(bits, seed)`, `encrypt(data, e, n)`, and `decrypt(data, d, n)`. You will follow the principles of RSA encryption/decryption as described.\n\n**Function Specificat... | 0.746234 | Data_Structure_17592 | C | [
"generate_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 8efbfa11bf3542d4642afc4342426817ccbba3f0 | f55f68fe16dc4aa5b0eb91eb404ec32527b56af3 | |||
v1.0 | complete | Data_Structure | Data_Structure_17973_C | from typing import List
import random
def bogo_sort_binary_strings(binary_strings: List[str], simulation: bool = False) -> List[str]:
""" Applies Bogo Sort algorithm to sort a list of binary strings in lexicographical order.
prints the state of the list after each shuffle iteration if simulation is True.
... | import random
from typing import List
def is_sorted(binary_strings: List[str]) -> bool:
for i in range(len(binary_strings) - 1):
if binary_strings[i] > binary_strings[i + 1]:
return False
return True
def bogo_sort_binary_strings(binary_strings: List[str], simulation: bool = False) -> List[... | from solution import bogo_sort_binary_strings
def test_bogo_sort_already_sorted():
assert bogo_sort_binary_strings(["001", "010", "011"]) == ["001", "010", "011"]
def test_bogo_sort_unsorted():
assert bogo_sort_binary_strings(["110", "101", "111", "100"]) == ["100", "101", "110", "111"]
def test_bogo_sort_re... | [
{
"docstring": null,
"function_declaration": "def is_sorted(binary_strings):",
"function_name": "is_sorted",
"parameter_list": "(binary_strings)"
},
{
"docstring": null,
"function_declaration": "def bogo_sort_binary_strings(binary_strings, simulation=False):",
"function_name": "bogo_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport random\n\ndef is_sorted(binary_strings: List[str]) -> bool:\n \"\"\"\n Checks if the list of binary strings is sorted.\n... | trial_gpt4o_2 | {
"original_instruction": "### Bogo Sort Reimagined for Binary Strings\n\nAs an exercise in understanding inefficient algorithms, we are going to use an impractical sorting method called Bogo Sort on a collection of binary strings. A binary string is a string consisting only of characters '0' and '1'.\n\nYour task is... | 0.64617 | Data_Structure_17973 | C | [
"is_sorted",
"bogo_sort_binary_strings"
] | 2 | [
[
"bogo_sort_binary_strings",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b16e44476fae48a1229e62a3b7015ad14fd90c0f | 16aac776f9643b00237f17697686002019389e35 | |||
v1.0 | complete | Data_Structure | Data_Structure_18670_C | from typing import List, Dict
def generate_word_squares(words: List[str]) -> List[List[str]]:
""" Produce all possible word squares that can be built from the given list of words.
>>> generate_word_squares(["area", "lead", "wall", "lady", "ball"])
[["wall", "area", "lead", "lady"],
["ball", "area", "l... | from typing import List, Dict
def build_prefix_dict(words: List[str]) -> Dict[str, List[str]]:
prefix_dict = {}
for word in words:
for i in range(len(word)):
prefix = word[:i]
if prefix in prefix_dict:
prefix_dict[prefix].append(word)
else:
... | import pytest
from solution import generate_word_squares
def test_generate_word_squares_example1():
words = ["area","lead","wall","lady","ball"]
expected_output = [
["wall", "area", "lead", "lady"],
["ball", "area", "lead", "lady"]
]
assert generate_word_squares(words) == expected_outpu... | [
{
"docstring": null,
"function_declaration": "def build_prefix_dict(words):",
"function_name": "build_prefix_dict",
"parameter_list": "(words)"
},
{
"docstring": null,
"function_declaration": "def backtrack(index, word_square, results, prefix_dict):",
"function_name": "backtrack",
... | [
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, Dict\n\ndef build_prefix_dict(words: List[str]) -> Dict[str, List[str]]:\n prefix_dict = {}\n for word in words:\n for i... | trial_gpt4o_0 | {
"original_instruction": "### Word Squares Generation with Prefix-based Backtracking \n\nYou are given a list of unique words. A word square is a sequence of words such that the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).\n\nWrite a function `generate_word_squares(words)` t... | 0.602408 | Data_Structure_18670 | C | [
"build_prefix_dict",
"backtrack",
"generate_word_squares"
] | 3 | [
[
"generate_word_squares",
"backtrack"
],
[
"generate_word_squares",
"build_prefix_dict"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3780712547ac962cf39e2281ff1e2c07114a025c | 064d298a13842b51f97e644aebca7cf3ec93b7e7 | |||
v1.0 | complete | Data_Structure | Data_Structure_17429_C | import random
from typing import Tuple, Optional
def is_prime(n: int, k: int = 5) -> bool:
""" Determine if a number is a prime using the Miller-Rabin Primality Test.
"""
# Implementation of primality test here
pass
def gen_prime(bit_length: int) -> int:
""" Generate a prime number of specified bi... | import random
def is_prime(n, k=5): # Miller-Rabin primality test
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
r, s = 0, n - 1
while s % 2 == 0:
r += 1
s //= 2
for _ in range(k):
a = random.randint(2, n - 2)
... | from solution import generate_key_enhanced, is_prime, gen_prime, egcd, modinv
def test_is_prime():
assert is_prime(2)
assert is_prime(11)
assert not is_prime(1)
assert not is_prime(4)
assert is_prime(7919) # Large prime for a quick check
def test_gen_prime():
prime_16 = gen_prime(16)
asse... | [
{
"docstring": null,
"function_declaration": "def is_prime(n, k=5):",
"function_name": "is_prime",
"parameter_list": "(n, k=5)"
},
{
"docstring": null,
"function_declaration": "def gen_prime(bit_length):",
"function_name": "gen_prime",
"parameter_list": "(bit_length)"
},
{
... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, gcd\nimport sympy\n\ndef modinv(a, m):\n \"\"\"\n Returns the modular inverse of a under modulo m using the Ex... | trial_gpt4o_9 | {
"original_instruction": "### RSA Encryption Enhancement\n\nThe provided RSA encryption implementation has a modular exponentiation mechanism in place but can be inefficient, especially in generating prime numbers and finding modular inverses. To assess your understanding of RSA and algorithm optimization, enhance t... | 0.625752 | Data_Structure_17429 | C | [
"is_prime",
"gen_prime",
"egcd",
"modinv",
"generate_key_enhanced"
] | 5 | [
[
"gen_prime",
"is_prime"
],
[
"generate_key_enhanced",
"gen_prime"
],
[
"generate_key_enhanced",
"modinv"
],
[
"modinv",
"egcd"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 24f8c5d4ede38e70fef79110f5168a941cde2432 | ba1695ba640571192dc9887cad8002ca69bccee2 | |||
v1.0 | complete | Data_Structure | Data_Structure_17955_C | def optimized_radix_sort(arr):
"""
Sorts a list of non-negative integers using an optimized radix sort algorithm.
Parameters:
arr (List[int]): A list of non-negative integers
Returns:
List[int]: A list of integers sorted in ascending order
>>> optimized_radix_sort([170, 45, 75... | def optimized_radix_sort(arr):
"""
Sorts a list of non-negative integers using an optimized radix sort algorithm.
Parameters:
arr (List[int]): A list of non-negative integers
Returns:
List[int]: A list of integers sorted in ascending order
"""
if len(arr) == 0:
return [... | from solution import optimized_radix_sort
def test_optimized_radix_sort_regular_cases():
assert optimized_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_optimized_radix_sort_empty_list():
assert optimized_radix_sort([]) == []
def test_optimized_radix_sort_single_e... | [
{
"docstring": "Sorts a list of non-negative integers using an optimized radix sort algorithm.\n\nParameters:\narr (List[int]): A list of non-negative integers\n\nReturns:\nList[int]: A list of integers sorted in ascending order",
"function_declaration": "def optimized_radix_sort(arr):",
"function_name"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_radix_sort(arr):\n \"\"\"\n Sorts a list of non-negative integers using an optimized radix sort algorithm.\n \n Parameters:\n arr... | trial_gpt4o_2 | {
"original_instruction": "### Radix Sort Challenge\n\n#### Scenario\nYou're part of a team working on optimizing the performance of the database of a retail application. Your task is to efficiently sort large sets of transaction IDs consisting of positive integers. The radix sort algorithm has been recommended for t... | 0.664013 | Data_Structure_17955 | C | [
"optimized_radix_sort",
"counting_sort_by_digit"
] | 2 | [
[
"optimized_radix_sort",
"counting_sort_by_digit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 64d5496bd8984d16fbed2e6b650de15b47ac0eea | 45ae75054802dba6f0a37ff3e721c9f11e876554 | |||
v1.0 | complete | Data_Structure | Data_Structure_18644_C | from typing import Tuple
def generate_key(k: int) -> Tuple[int, int, int]:
"""
Generates RSA key pair — public key (n, e) and private key d.
"""
pass
def encrypt(data: int, e: int, n: int) -> int:
"""
Encrypts the given data using the public key.
"""
pass
def decrypt(data: int, d: int... | import random
from sympy import isprime, mod_inverse
from typing import Tuple
def generate_prime_candidate(length):
# Generates an odd integer randomly in the range from 2^(length-1) to 2^length.
p = random.getrandbits(length)
# Apply a mask to set MSB and LSB to 1 to ensure prime candidate of length 'leng... | from solution import generate_key, encrypt, decrypt
def test_generate_key_length():
n, e, d = generate_key(16)
assert len(bin(n)) - 2 == 16, "Modulus length should be 16 bits"
def test_encrypt_decrypt_small_data():
k = 16
data = 20
n, e, d = generate_key(k)
encrypted_data = encrypt(data, e, n)... | [
{
"docstring": null,
"function_declaration": "def generate_prime_candidate(length):",
"function_name": "generate_prime_candidate",
"parameter_list": "(length)"
},
{
"docstring": null,
"function_declaration": "def generate_prime_number(length):",
"function_name": "generate_prime_numbe... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom math import gcd\n\ndef generate_prime(bits):\n \"\"\" Generates a prime number of specified bit length. \"\"\"\n while True:\n ... | trial_gpt4o_1 | {
"original_instruction": "### RSA Encryption and Decryption\n\nYou are required to implement a key pair generation function and utilize it to carry out encryption and decryption using the RSA algorithm. \n\n\n**Function Specs**:\n\n1. **generate_key(k: int) -> Tuple[int, int, int]**\n - Generates and returns an RS... | 0.725731 | Data_Structure_18644 | C | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 72aa8210680fc8fb22cce723b993acfcfd5c3651 | b8531d6b2a0d9c78d0791b80d0fe54f546cd7bb0 | |||
v1.0 | complete | Data_Structure | Data_Structure_18814_C | def custom_pancake_sort(arr, threshold):
""" Custom pancake sort variant. Elements greater than the threshold
are sorted first, followed by the sorted remaining elements.
>>> custom_pancake_sort([3, 6, 4, 7, 2, 5], 4)
[5, 6, 7, 2, 3, 4]
>>> custom_pancake_sort([10, 9, 1, 2, 15, 20], 12)
[1... | def flip(arr, k):
"""Helper function to flip the first k elements of the list."""
arr[:k] = arr[:k][::-1]
def pancake_sort(arr, indices):
"""Pancake sort the elements of arr specified by the indices."""
n = len(indices)
for i in range(n, 1, -1):
# Index of the maximum element in the unsorte... | def test_custom_pancake_sort():
assert custom_pancake_sort([3, 6, 4, 7, 2, 5], 4) == [5, 6, 7, 2, 3, 4]
assert custom_pancake_sort([10, 9, 1, 2, 15, 20], 12) == [15, 20, 1, 2, 9, 10]
assert custom_pancake_sort([8, 4, 6, 2, 3, 5, 1], 5) == [6, 8, 1, 2, 3, 4, 5]
assert custom_pancake_sort([], 5) == []
... | [
{
"docstring": "Helper function to flip the first k elements of the list.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Pancake sort the elements of arr specified by the indices.",
"function_declaration": "def panc... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def flip(arr, k):\n \"\"\"\n Reverses the order of the first k elements of the array.\n \"\"\"\n start = 0\n while start < k:\n arr[star... | trial_gpt4o_9 | {
"original_instruction": "### Question: Implement a Custom Pancake Sort Variant\nAs a software development challenge, you are tasked with implementing a customized variant of the Pancake Sort algorithm. This variant should additionally include a feature where a predefined threshold value splits the sorting process. ... | 0.712111 | Data_Structure_18814 | C | [
"flip",
"pancake_sort",
"custom_pancake_sort"
] | 3 | [
[
"custom_pancake_sort",
"pancake_sort"
],
[
"pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 9f0f1f5398c390985317f791a1d8b2404da6388b | 0c72436cd17ec883d717594349365d4abafecea9 | |||
v1.0 | complete | Data_Structure | Data_Structure_18539_C | def efficient_bogo_sort(arr: [int]) -> [int]:
""" Attempts to improve upon the Bogo Sort algorithm by recognizing sorted subarrays
and only shuffling the unsorted parts of the array until the whole array is sorted.
>>> efficient_bogo_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6,... | import random
def is_sorted(arr):
"""
Helper function to check if an array is sorted.
"""
return all(arr[i] <= arr[i+1] for i in range(len(arr) - 1))
def efficient_bogo_sort(arr):
"""
Attempts to improve upon the Bogo Sort algorithm by recognizing sorted subarrays
and only shuffling the u... | from solution import efficient_bogo_sort
def test_sorted_array():
assert efficient_bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert efficient_bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_duplicate_elements():
assert efficient_bogo_sort([3, 1, 4, 1, 5, 9, 2, ... | [
{
"docstring": "Helper function to check if an array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Attempts to improve upon the Bogo Sort algorithm by recognizing sorted subarrays \nand only shuffling th... | [
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 is_sorted(arr):\n \"\"\"\n Helper function to check if the array is sorted.\n \"\"\"\n for i in range(len(arr) - 1):\n ... | trial_gpt4o_8 | {
"original_instruction": "**Objective**: Demonstrate understanding of sorting algorithms and their efficiency.\n\n**Context**:\nBogo Sort is an intentionally inefficient sorting algorithm that works by repeatedly shuffling the array until it happens to be in order. Despite its inefficiency, it provides a good educat... | 0.615607 | Data_Structure_18539 | C | [
"is_sorted",
"efficient_bogo_sort"
] | 2 | [
[
"efficient_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6b55d50ace88547e3bf32a6ab104cf123198ce30 | a4bf9bf9869626d2a21e2b14ff86610185cbf3ac | |||
v1.0 | complete | Data_Structure | Data_Structure_18421_C | def probable_prime(n: int, k: int) -> bool:
""" Determines if the given integer `n` is probably prime using the Rabin-Miller primality test.
Parameters:
n (int): The number to be tested (n >= 5).
k (int): The number of testing rounds to reduce the probability of error.
Returns:
bool: T... | import random
def modular_exponentiation(base, exp, mod):
result = 1
while exp > 0:
if exp % 2 == 1:
result = (result * base) % mod
base = (base * base) % mod
exp //= 2
return result
def rabin_miller_test(n, d, r):
a = random.randint(2, n - 2)
x = modular_expone... | from solution import probable_prime
def test_probable_prime_with_small_primes():
assert probable_prime(5, 5) == True
assert probable_prime(7, 10) == True
assert probable_prime(11, 5) == True
def test_probable_prime_with_small_composites():
assert probable_prime(6, 5) == False
assert probable_prime... | [
{
"docstring": null,
"function_declaration": "def modular_exponentiation(base, exp, mod):",
"function_name": "modular_exponentiation",
"parameter_list": "(base, exp, mod)"
},
{
"docstring": null,
"function_declaration": "def rabin_miller_test(n, d, r):",
"function_name": "rabin_mille... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef modular_exponentiation(base, exp, mod):\n result = 1\n while exp > 0:\n if exp % 2 == 1:\n result = (result * bas... | trial_gpt4o_0 | {
"original_instruction": "You are designing a system that needs to handle large prime numbers. One way to ascertain whether a number is prime is through a probabilistic algorithm known as the Rabin-Miller primality test. \n\nWrite a function `probable_prime(n: int, k: int) -> bool` that determines if the given integ... | 0.746874 | Data_Structure_18421 | C | [
"modular_exponentiation",
"rabin_miller_test",
"probable_prime"
] | 3 | [
[
"probable_prime",
"rabin_miller_test"
],
[
"rabin_miller_test",
"modular_exponentiation"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6653d55579f1714d7d5fbc468e6376ba5a9b396a | 345357b4240e1491fdc6f9b0ed5d357ebc678480 | |||
v1.0 | complete | Data_Structure | Data_Structure_18784_C | def matrix_power(A: list, n: int) -> list:
"""Compute the matrix A raised to the power of n (A^n) efficiently.
Args:
A (list): A square matrix represented as a list of lists.
n (int): The power to which the matrix A needs to be raised.
Returns:
list: The resultant matrix after ... | def matrix_multiply(A, B):
# Matrix multiplication of A and B
dim = len(A)
C = [[0] * dim for _ in range(dim)]
for i in range(dim):
for j in range(dim):
C[i][j] = sum(A[i][k] * B[k][j] for k in range(dim))
return C
def identity_matrix(dim):
# Create an identity matrix of dim... | from solution import matrix_power
def test_identity_power():
A = [
[1, 2],
[3, 4]
]
n = 0
expected = [
[1, 0],
[0, 1]
]
assert matrix_power(A, n) == expected
def test_power_one():
A = [
[1, 2],
[3, 4]
]
n = 1
expected = A
asse... | [
{
"docstring": null,
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def identity_matrix(dim):",
"function_name": "identity_matrix",
"parameter_list": "(dim)"
}... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_multiply(A, B):\n # Matrix multiplication of A and B\n dim = len(A)\n C = [[0] * dim for _ in range(dim)]\n for i in range(dim):\n ... | trial_gpt4o_0 | {
"original_instruction": "### Matrix Power Calculation\nYou are given a square matrix `A` of dimensions `d x d` and an integer `n`. Your task is to compute the matrix `A` raised to the power of `n` (A^n) efficiently.\n\nWrite a function `matrix_power(A: list, n: int) -> list` that takes a list of lists `A` represent... | 0.525721 | Data_Structure_18784 | C | [
"matrix_multiply",
"identity_matrix",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity_matrix"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3f7a309d8c6b6ff1522837c6c8bcd35c01e22246 | 0cbd1e9f75686b6d59cfa54634f6dbe4fa52453d | |||
v1.0 | complete | Data_Structure | Data_Structure_17342_C | from typing import List
def optimized_quick_sort(arr: List[int], simulation: bool = False) -> List[int]:
""" Sort an array of integers in ascending order using Quick Sort algorithm with optimizations.
- Implements median-of-three pivot selection.
- Uses tail call optimization for efficient recursion handli... | from typing import List
def median_of_three(arr, low, high):
mid = (low + high) // 2
pivot_candidates = [(arr[low], low), (arr[mid], mid), (arr[high], high)]
pivot_candidates.sort()
return pivot_candidates[1][1]
def partition(arr, low, high):
pivot_index = median_of_three(arr, low, high)
arr[h... | from solution import optimized_quick_sort
def test_sorted_array():
assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert optimized_quick_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_random_array():
assert optimized_quick_sort([3, 1, 4, 1, 5, 9, 2, 6,... | [
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef optimized_quick_sort(arr: List[int], simulation: bool = False) -> List[int]:\n def quick_sort(arr, low, high, simulation, de... | trial_gpt4o_1 | {
"original_instruction": "### Coding Challenge\n\nYou are given an array of integers that needs to be sorted in ascending order. Implement a function `optimized_quick_sort` that sorts the array using the Quick Sort algorithm. Your implementation should include:\n- The core quick sort mechanism.\n- A pivot selection ... | 0.556071 | Data_Structure_17342 | C | [
"median_of_three",
"partition",
"quick_sort_helper",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"quick_sort_helper"
],
[
"partition",
"median_of_three"
],
[
"quick_sort_helper",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | f01354b4c3fc684f15198913ca49d2af6242f14b | 7707fd454dcf18cb2a0ef8c15f36e498daab4378 | |||
v1.0 | complete | Data_Structure | Data_Structure_18988_C | from typing import List
def radix_sort_with_negatives(arr: List[int], simulation: bool = False) -> List[int]:
"""Sort a list of integers in ascending order using Radix Sort with handling for negative numbers.
Args:
arr (List[int]): List of integers which may include negative numbers.
simulation (b... | def counting_sort(arr, exp, simulation):
n = len(arr)
output = [0] * n
count = [0] * 10
# Count occurrences
for i in range(n):
index = abs(arr[i]) // exp
count[index % 10] += 1
# Compute cumulative count
for i in range(1, 10):
count[i] += count[i - 1]
# Build o... | def test_radix_sort_with_negatives():
from solution import radix_sort_with_negatives
# Test with mixed values including negatives
assert radix_sort_with_negatives([170, 45, 75, -45, -75, 90, -802, 24, 2, 66], simulation=False) == [-802, -75, -45, 2, 24, 45, 66, 75, 90, 170]
# Test with no values
as... | [
{
"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_with_negatives(arr, simulation=False):",
"function_nam... | [
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 counting_sort(arr, exp, simulation):\n \"\"\" A function to do counting sort of arr[] according to the digit represented by exp. \"\"\"\n n = len(ar... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement Radix Sort with Handling for Negative Numbers\n\nGiven a list of integers, write a function `radix_sort_with_negatives` to sort the list in ascending order using Radix Sort. The standard Radix Sort works well for non-negative integers, but your implementation should ... | 0.665857 | Data_Structure_18988 | C | [
"counting_sort",
"radix_sort_with_negatives"
] | 2 | [
[
"radix_sort_with_negatives",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5dcfaa9a9cc42d8bc99ba2d12f66377558b47618 | a8d7efd349002fa67c574f8018db3fd096b1a887 | |||
v1.0 | complete | Data_Structure | Data_Structure_17313_C | class DirectedGraph:
def __init__(self, graph_dict=None):
self.graph_dict = graph_dict if graph_dict else {}
def add_node(self, node):
if node not in self.graph_dict:
self.graph_dict[node] = []
def add_edge(self, from_node, to_node):
if from_node in self.graph_dict:
... | class DirectedGraph:
def __init__(self, graph_dict=None):
self.graph_dict = graph_dict if graph_dict else {}
def add_node(self, node):
if node not in self.graph_dict:
self.graph_dict[node] = []
def add_edge(self, from_node, to_node):
if from_node in self.graph_dict:
... | from solution import DirectedGraph, is_path
def test_path_exists():
graph_dict = {
"A": ["B", "C"],
"B": ["C", "D"],
"C": ["E"],
"D": [],
"E": ["B"],
"F": ["C"]
}
graph = DirectedGraph(graph_dict)
assert is_path(graph, "A", "E") == True
def test_path_doe... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class DirectedGraph:\n def __init__(self, graph_dict=None):\n \"\"\"\n Initializes the DirectedGraph with an optional adjacency list.\n ... | trial_gpt4o_1 | {
"original_instruction": "You are given a directed graph data structure that supports adding nodes and edges. Using this structure, implement a function to check if there is a **path** between two given nodes in the graph.\n\n### Function Signature:\n```python\ndef is_path(graph, start_node, end_node):\n \"\"\"\n... | 0.580398 | Data_Structure_17313 | C | [
"is_path",
"dfs"
] | 2 | [
[
"is_path",
"dfs"
]
] | 1 | [] | false | [
"DirectedGraph"
] | true | pytest | true | [] | true | d79e6a2dfd2d4900c0ae3ec1d61ce08d4a7c4733 | 101e658e9c4a3660c9c85a639604979ee8973acc | |||
v1.0 | complete | Data_Structure | Data_Structure_19217_C | from typing import List
def custom_bucket_sort(ages: List[int], buckets_range: int) -> List[int]:
""" Sort a list of ages using a custom bucket sort algorithm.
Each bucket will contain ages within a certain range, and insertion sort is used to sort each bucket.
>>> custom_bucket_sort([23, 45, 22, 18, 35, 1... | from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def custom_bucket_sort(ages: List[int], buc... | from solution import custom_bucket_sort
def test_custom_bucket_sort_example():
assert custom_bucket_sort([23, 45, 22, 18, 35, 13, 67], 10) == [13, 18, 22, 23, 35, 45, 67]
def test_custom_bucket_sort_empty():
assert custom_bucket_sort([], 10) == []
def test_custom_bucket_sort_single_element():
assert cust... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def custom_bucket_sort(ages, buckets_range):",
"function_name": "custom_bucket_sort",
"parameter_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(bucket: List[int]) -> List[int]:\n \"\"\"\n Perform insertion sort on the given bucket.\n \"\"\"\n f... | trial_gpt4o_2 | {
"original_instruction": "#### Scenario\nSuppose you have been given a dataset of integer values representing ages of people in a population. The ages are in the range [0, 100). Due to some analysis needs, you are required to sort these ages using a custom bucket sort algorithm. Each bucket will contain ages within ... | 0.585283 | Data_Structure_19217 | C | [
"insertion_sort",
"custom_bucket_sort"
] | 2 | [
[
"custom_bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ad6a4b2ffd56f1147c59a902c81b6c459cd21831 | 9e183f4289c76bdd70e30108235f2467f07780e8 | |||
v1.0 | complete | Data_Structure | Data_Structure_18618_C | from typing import List
def prime_check(n: int) -> bool:
"""
Determines if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
... | from typing import List
def prime_check(n: int) -> bool:
"""
Determines if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
... | from solution import find_primes_in_range
def test_find_primes_in_range_basic():
assert find_primes_in_range(10, 20) == [11, 13, 17, 19]
def test_find_primes_in_range_single_prime():
assert find_primes_in_range(2, 2) == [2]
def test_find_primes_in_range_no_primes():
assert find_primes_in_range(14, 16) ==... | [
{
"docstring": "Determines if a number is prime.",
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers in the range [start, end].",
"function_declaration": "def find_primes_in_range(star... | [
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 prime_check(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_2 | {
"original_instruction": "### Prime Number Range Finder\n\nYou are given a function, `prime_check(n)`, which correctly identifies whether a number `n` is prime or not. Your task is to use this to implement a new function `find_primes_in_range(start, end)` that will find all prime numbers in a given inclusive range `... | 0.759443 | Data_Structure_18618 | C | [
"prime_check",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a623021157ff14b60f47e2ae312418e323698cb4 | 6451f8abb1f495710fff570da97cd43fc5ba56d1 | |||
v1.0 | complete | Data_Structure | Data_Structure_17641_C | from typing import List, Any
def maximum_flow_bfs(adjacency_matrix: List[List[int]]) -> int:
""" Calculate the maximum flow in a given flow network using the Edmonds-Karp algorithm.
Args:
adjacency_matrix (List[List[int]]): A 2D list where adjacency_matrix[i][j] represents the capacity of the edge
... | from collections import deque
def bfs(residual_graph, source, sink, parent):
visited = [False] * len(residual_graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(residual_graph[u]):
if not visited[... | from solution import maximum_flow_bfs
def test_example_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow_bfs(graph) == 23
def test_no_flow_case... | [
{
"docstring": null,
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(adjacency_matrix):",
"function_name"... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(residual_graph, source, sink, parent):\n \"\"\"\n Performs BFS on the residual graph to find if there's an augm... | trial_gpt4o_2 | {
"original_instruction": "#### Context\nYou are given a graph representing a network of water pipes, where each pipe has a specified capacity. The objective is to determine the maximum amount of water that can flow from the source (starting point) to the sink (ending point) by implementing the Edmonds-Karp algorithm... | 0.586925 | Data_Structure_17641 | C | [
"bfs",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7563457bf5c3424c8d8f1a925a59601e70e28729 | 792a076484b83d945f93bc175dbc794e0788596f | |||
v1.0 | complete | Data_Structure | Data_Structure_16982_C | import random
from typing import Tuple, Optional
def generate_key_pair(k: int, seed: Optional[int] = None) -> Tuple[int, int, int]:
"""
Generates RSA key pair for the specified bit length `k`. The optional `seed` parameter helps in generating reproducible prime numbers.
Parameters:
k (int): Bit le... | import random
from typing import Tuple, Optional
from sympy import isprime, gcd
def generate_prime(bit_length: int, seed: Optional[int] = None) -> int:
if seed is not None:
random.seed(seed)
while True:
prime_candidate = random.getrandbits(bit_length)
if isprime(prime_candidate):
... | from solution import generate_key_pair, rsa_encrypt, rsa_decrypt
def test_key_generation():
n, e, d = generate_key_pair(16, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_rsa_encryption_decryption():
n, e, d = generate_key_pair(16, seed=42)
... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bit_length, seed=None):",
"function_name": "generate_prime",
"parameter_list": "(bit_length, seed=None)"
},
{
"docstring": null,
"function_declaration": "def generate_key_pair(k, seed=None):",
"function_name": "generate... | [
0,
0,
0,
0,
1,
1,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, gcd\nfrom typing import Tuple\n\ndef generate_prime_candidate(k):\n # Generate random number of k bits\n candi... | trial_gpt4o_6 | {
"original_instruction": "### RSA Encryption Implementation \n\nAs part of your cryptography coursework, you are required to implement a secure communication mechanism using the RSA algorithm. Your task is to complete the following two functions for RSA encryption and decryption.\n\n#### Requirements:\n\n1. **Functi... | 0.744496 | Data_Structure_16982 | C | [
"generate_prime",
"generate_key_pair",
"rsa_encrypt",
"rsa_decrypt"
] | 4 | [
[
"generate_key_pair",
"generate_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | f4632f01da99f887c519f840bee83ce81b1ee122 | 5f5f0c5971c83e14fd195eaf9a5b1cb20441fcbb | |||
v1.0 | complete | Data_Structure | Data_Structure_19133_C | def enhanced_interpolation_search(array: List[int], search_key: int) -> int:
"""
:param array: The array to be searched (must be sorted in ascending order).
:param search_key: The key to be searched in the array.
:returns: Index of search_key in array if found, else -1.
Enhancements:
- Check f... | def fallback_binary_search(array, search_key, low, high):
while low <= high:
mid = (low + high) // 2
if array[mid] == search_key:
return mid
elif array[mid] < search_key:
low = mid + 1
else:
high = mid - 1
return -1
def enhanced_interpolation_... | from solution import enhanced_interpolation_search
def test_enhanced_interpolation_search_found():
array = [-25, -12, -1, 10, 12, 15, 20, 41, 55]
assert enhanced_interpolation_search(array, -1) == 2
def test_enhanced_interpolation_search_not_found():
array = [5, 10, 12, 14, 17, 20, 21]
assert enhanced... | [
{
"docstring": null,
"function_declaration": "def fallback_binary_search(array, search_key, low, high):",
"function_name": "fallback_binary_search",
"parameter_list": "(array, search_key, low, high)"
},
{
"docstring": null,
"function_declaration": "def enhanced_interpolation_search(array... | [
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 fallback_binary_search(array, search_key, low, high):\n while low <= high:\n mid = (low + high) // 2\n if array[mid] == search_key:\n ... | trial_gpt4o_0 | {
"original_instruction": "### Interpolation Search Enhancement\n\nThe existing implementation of the interpolation search performs well on uniformly distributed data. However, it can be enhanced by adding additional checks to handle non-uniformly distributed arrays better and avoid potential performance pitfalls.\n\... | 0.48343 | Data_Structure_19133 | C | [
"fallback_binary_search",
"enhanced_interpolation_search"
] | 2 | [
[
"enhanced_interpolation_search",
"fallback_binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 21839fd969eab3038292938203de66e120ea1f6e | 1c703e369c4eb6d5dcfd7f356e5ece80a2be67c6 | |||
v1.0 | complete | Data_Structure | Data_Structure_18989_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def construct_inorder(pre, post):
"""
Construct a full binary tree from the given preorder and postorder traversals,
and return the inorder traversal of the tre... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def construct_tree(pre, post):
if not pre or not post:
return None
root_val = pre[0]
root = TreeNode(root_val)
if len(pre) == 1:
ret... | from solution import construct_inorder
def test_construct_inorder_basic():
pre = [1, 2, 4, 8, 9, 5, 3, 6, 7]
post = [8, 9, 4, 5, 2, 6, 7, 3, 1]
expected_inorder = [8, 4, 9, 2, 5, 1, 6, 3, 7]
assert construct_inorder(pre, post) == expected_inorder
def test_construct_inorder_single_node():
pre = [1]... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef cons... | trial_gpt4o_1 | {
"original_instruction": "### Question: Full Binary Tree Construction and Inorder Traversal\n\n#### Problem Statement:\nYou are required to construct a full binary tree from the given preorder and postorder traversals. A full binary tree is defined as a tree where every node has either zero or two children. Once the... | 0.537363 | Data_Structure_18989 | C | [
"construct_tree",
"inorder_traversal",
"construct_inorder"
] | 3 | [
[
"construct_inorder",
"construct_tree"
],
[
"construct_inorder",
"inorder_traversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 968ee3040ef8989fd9f02d615a84faa7ace196cb | 0d4e62ad22e0555ba0720dd7751d5230df633563 | |||
v1.0 | complete | Data_Structure | Data_Structure_19218_C | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort_simulation(arr: list, max_shuffles: int, simulation=False) -> (list, int, bool):
"""
A... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort_simulation(arr, max_shuffles, simulation=False):
"""
Attempts to sort an array using t... | from solution import bogo_sort_simulation
def test_bogo_sort_empty_list():
assert bogo_sort_simulation([], 100) == ([], 0, True)
def test_bogo_sort_single_element():
assert bogo_sort_simulation([1], 100) == ([1], 0, True)
def test_bogo_sort_already_sorted():
assert bogo_sort_simulation([1, 2, 3], 100) ==... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Attempts to sort an array using the bogo sort algorithm.\n\nParameters:\narr (list): The list of number... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n for i in range(len(arr) - 1):\n if arr[i] > arr[i + 1]:\n return False\n return True\n\ndef bog... | trial_gpt4o_2 | {
"original_instruction": "### Scenario:\nYou have recently taken a class where various sorting algorithms were discussed. One of the algorithms discussed was Bogo Sort, a highly inefficient and academic sorting method. To illustrate its inefficiency, you are to implement this algorithm but also create a function to ... | 0.646221 | Data_Structure_19218 | C | [
"is_sorted",
"bogo_sort_simulation"
] | 2 | [
[
"bogo_sort_simulation",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 40f2af0e4b7e19f7b3dd55b321834d2326ba1f3f | 56bd1d48b48225e5bf201d4d680baadeaca60baf | |||
v1.0 | complete | Data_Structure | Data_Structure_17643_C | def insert_one_bit(num: int, bit: int, pos: int) -> int:
"""
Insert a single bit at the specified position of the number.
"""
pass
def insert_mult_bits(num: int, bits: int, length: int, pos: int) -> int:
"""
Insert multiple bits at the specified position of the number.
"""
pass
def bit... | def insert_one_bit(num: int, bit: int, pos: int) -> int:
"""
Insert a single bit at the specified position of the number.
"""
mask = 1 << pos
return (num & ~mask) | ((bit & 1) << pos)
def insert_mult_bits(num: int, bits: int, length: int, pos: int) -> int:
"""
Insert multiple bits at the sp... | from solution import insert_one_bit, insert_mult_bits, bit_insertion_handler
def test_insert_one_bit():
assert insert_one_bit(21, 1, 2) == 21 | (1 << 2)
assert insert_one_bit(21, 0, 2) == 21 & ~(1 << 2)
assert insert_one_bit(0, 1, 0) == 1
assert insert_one_bit(0, 0, 0) == 0
assert insert_one_bit(1,... | [
{
"docstring": "Insert a single bit at the specified position of the number.",
"function_declaration": "def insert_one_bit(num, bit, pos):",
"function_name": "insert_one_bit",
"parameter_list": "(num, bit, pos)"
},
{
"docstring": "Insert multiple bits at the specified position of the number.... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insert_one_bit(num: int, bit: int, pos: int) -> int:\n \"\"\"\n Inserts a single bit into the number at the specified position.\n \n Parameter... | trial_gpt4o_2 | {
"original_instruction": "### Question: Bit Insertion Challenge\n\nYou are given two functions `insert_one_bit` and `insert_mult_bits` that manipulate bits within a number. Your task is to extend and improve these functions to handle various scenarios and then write a function `bit_insertion_handler`.\n\n### Functio... | 0.611227 | Data_Structure_17643 | C | [
"insert_one_bit",
"insert_mult_bits",
"bit_insertion_handler"
] | 3 | [
[
"bit_insertion_handler",
"insert_mult_bits"
],
[
"bit_insertion_handler",
"insert_one_bit"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 61ddde6c8b20c61692d39c2da1d96daefb4963fa | d2828f01f5e035a0b7b0870e3168636a3c46a2c2 | |||
v1.0 | complete | Data_Structure | Data_Structure_19298_C | def max_flow(capacity: List[List[int]], source: int, sink: int) -> int:
""" Compute the maximum flow from the source to the sink using Dinic's algorithm.
Args:
capacity: A 2D list of integers representing the capacity of edges between nodes.
source: The index of the source node.
sink: The index... | from collections import deque
def dinic_bfs(capacity, flow, level, source, sink):
vertices = len(capacity)
queue = deque([source])
level[source] = 0
while queue:
front = queue.popleft()
for nxt in range(vertices):
if level[nxt] == -1 and flow[front][nxt] < capacity[front][nx... | def test_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_no_flow():
... | [
{
"docstring": null,
"function_declaration": "def dinic_bfs(capacity, flow, level, source, sink):",
"function_name": "dinic_bfs",
"parameter_list": "(capacity, flow, level, source, sink)"
},
{
"docstring": null,
"function_declaration": "def dinic_dfs(capacity, flow, level, idx, sink, ptr... | [
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 queue import Queue\n\ndef dinic_bfs(capacity, flow, level, source, sink):\n vertices = len(capacity)\n queue = Queue()\n queue.put(source)\n ... | trial_gpt4o_1 | {
"original_instruction": "### Context\nA company uses a road network to transport goods between warehouses and retail stores. The network is modeled as a directed graph where nodes represent warehouses and stores, while edges represent roads with specific capacities. Your task is to compute the maximum transportatio... | 0.553543 | Data_Structure_19298 | C | [
"dinic_bfs",
"dinic_dfs",
"max_flow"
] | 3 | [
[
"max_flow",
"dinic_bfs"
],
[
"max_flow",
"dinic_dfs"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 08462250bff367fedcf492ad672cd1795efb8d89 | fabe7860e6370815db997dec587436dca16355f4 | |||
v1.0 | complete | Data_Structure | Data_Structure_19106_C | from typing import List
def max_heap_sort(arr: List[int], simulation: bool = False) -> List[int]:
""" Sort an array in ascending order using max heap sort algorithm.
Args:
arr (List[int]): list of integers to be sorted.
simulation (bool): Optional; if True, print the state of the array at each signific... | from typing import List
def max_heapify(arr: List[int], n: int, i: int, simulation: bool = False):
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
... | from solution import max_heap_sort, min_heap_sort
def test_max_heap_sort():
assert max_heap_sort([3, 19, 1, 14, 8, 7]) == [1, 3, 7, 8, 14, 19]
assert max_heap_sort([4, 10, 3, 5, 1]) == [1, 3, 4, 5, 10]
assert max_heap_sort([12, 11, 13, 5, 6, 7]) == [5, 6, 7, 11, 12, 13]
assert max_heap_sort([38, 27, 43... | [
{
"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(arr, simulation=False):",
"function_name"... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_heapify(arr, n, i, simulation):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n and arr[i] < arr[left]:\n larg... | trial_gpt4o_2 | {
"original_instruction": "### Heap Sort Implementation\n\nHeap Sort is a comparison-based sorting algorithm that uses a binary heap data structure to sort elements. You are required to implement two variants of the heap sort algorithm:\n\n1. **max_heap_sort**: Use this to sort an array in ascending order by repeated... | 0.657203 | Data_Structure_19106 | 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 | 0f069497d318749d736b8b496ca72cb0e2a98af6 | f4b3492ecbd58ba45ec36bf525e40123a6361d27 | |||
v1.0 | complete | Data_Structure | Data_Structure_18439_C | def secure_diffie_hellman(p: int, a: int, verbose: bool = False) -> bool:
"""
Determine if p is a prime number and a is its primitive root.
Perform Diffie-Hellman key exchange if validation passes.
:param p: int - The prime number to validate and use in key exchange.
:param a: int - The primitive ... | def is_prime(n):
"""Check if the input 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 True... | def test_secure_diffie_hellman_valid_inputs():
assert secure_diffie_hellman(23, 5, verbose=True) == True
def test_secure_diffie_hellman_invalid_generator():
assert secure_diffie_hellman(23, 10) == False
def test_secure_diffie_hellman_large_prime_valid_primitive_root():
assert secure_diffie_hellman(97, 5) ... | [
{
"docstring": "Check if the input number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find a primitive root for prime p.",
"function_declaration": "def find_primitive_root(p):",
"function_name": "fi... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime\n\ndef find_order(a, p):\n \"\"\"\n Find the order of a modulo p.\n \"\"\"\n for k in range(1, p):\n ... | trial_gpt4o_1 | {
"original_instruction": "Alice and Bob want to establish a secret key using the Diffie-Hellman key exchange protocol. However, they need to ensure that the prime number p and the generator a they use are valid to guarantee the security of their key exchange.\n\nWrite a function `secure_diffie_hellman(p, a, verbose=... | 0.544683 | Data_Structure_18439 | C | [
"is_prime",
"find_primitive_root",
"find_prime_factors",
"secure_diffie_hellman"
] | 4 | [
[
"find_primitive_root",
"find_prime_factors"
],
[
"find_primitive_root",
"is_prime"
],
[
"secure_diffie_hellman",
"find_primitive_root"
],
[
"secure_diffie_hellman",
"is_prime"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 49ca3d4e4d05dfa57cce1e5965b613fe559c1923 | 96acb60d7b62baabbdc950aee6b5c93e793e40d8 | |||
v1.0 | complete | Data_Structure | Data_Structure_18778_C | def extended_radix_sort(arr):
""" Sorts an array of integers, including negative integers, using the radix sort algorithm.
>>> extended_radix_sort([170, 45, 75, -90, 802, 24, 2, 66, -10, -802])
[-802, -90, -10, 2, 24, 45, 66, 75, 170, 802]
>>> extended_radix_sort([])
[]
>>> extended_radix_sort... | def counting_sort(arr, exp):
"""
A helper function to perform counting sort based on the digit represented by exp (10^i).
"""
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = abs(arr[i]) // exp
count[index % 10] += 1
for i in range(1, 10... | from solution import extended_radix_sort
def test_empty_list():
assert extended_radix_sort([]) == []
def test_single_element():
assert extended_radix_sort([5]) == [5]
assert extended_radix_sort([-5]) == [-5]
def test_all_positive_numbers():
assert extended_radix_sort([170, 45, 75, 802, 24, 2, 66]) ==... | [
{
"docstring": "A helper function to perform counting sort based on the digit represented by exp (10^i).",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "A helper function to perform radix sort on an... | [
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 counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # Store count occurrences in count[]\n for i in range(n):... | trial_gpt4o_4 | {
"original_instruction": "### Question\n\nYou work for a data processing company that frequently sorts large datasets of integers. Your task is to implement the radix sort algorithm for the company. However, you need to modify the radix sort algorithm provided in the code snippet to handle negative integers as well.... | 0.669849 | Data_Structure_18778 | C | [
"counting_sort",
"radix_sort",
"extended_radix_sort"
] | 3 | [
[
"extended_radix_sort",
"radix_sort"
],
[
"radix_sort",
"counting_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 146f43a9f3c62114d5e91c494dc92f41c7ed46bb | 273030d18784cb0e1c61ee768522bd522b51023b | |||
v1.0 | complete | Data_Structure | Data_Structure_19355_C | def gcd(a: int, b: int) -> int:
"""
Compute the Greatest Common Divisor (GCD) of two numbers using Euclid's Algorithm.
>>> gcd(54, 24) # Output: 6
>>> gcd(48, 18) # Output: 6
>>> gcd(0, 5) # Output: 5
"""
pass
def lcm(a: int, b: int) -> int:
"""
Compute the Lowest Common Multiple (L... | def gcd(a: int, b: int) -> int:
"""
Compute the Greatest Common Divisor (GCD) of two numbers using Euclid's Algorithm.
"""
while b:
a, b = b, a % b
return a
def lcm(a: int, b: int) -> int:
"""
Compute the Lowest Common Multiple (LCM) of two numbers.
"""
if a == 0 or b == 0:
... | from solution import gcd, lcm, trailing_zero
# Tests for GCD function
def test_gcd_simple():
assert gcd(54, 24) == 6
assert gcd(48, 18) == 6
def test_gcd_edge_cases():
assert gcd(0, 5) == 5
assert gcd(5, 0) == 5
assert gcd(0, 0) == 0
assert gcd(7, 1) == 1
assert gcd(1, 7) == 1
def test_gc... | [
{
"docstring": "Compute the Greatest Common Divisor (GCD) of two numbers using Euclid's Algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Compute the Lowest Common Multiple (LCM) of two numbers.",
"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 gcd(a: int, b: int) -> int:\n \"\"\"\n Computes the Greatest Common Divisor (GCD) of two integers using Euclid's Algorithm.\n \"\"\"\n while b... | trial_gpt4o_2 | {
"original_instruction": "### GCD, LCM, and Trailing Zeros Analysis and Implementation\n\n#### Scenario:\nYou are tasked with developing a basic math utility library for a software application. Your utility should be able to compute the Greatest Common Divisor (GCD), the Lowest Common Multiple (LCM) of two integers,... | 0.715631 | Data_Structure_19355 | C | [
"gcd",
"lcm",
"trailing_zero"
] | 3 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d6df85195b518cbfdfb62ff176a8d33601997517 | ee97c9f614a8de4bf52bd8b42740ba15a1793b4e | |||
v1.0 | complete | Data_Structure | Data_Structure_19184_C | def fib_hybrid(n: int) -> int:
"""
Computes the n-th Fibonacci number by selecting the optimal algorithm.
Arguments:
n: int -- the index of the Fibonacci number to compute
Returns:
int -- the n-th Fibonacci number
Raises:
ValueError -- if n is a negative integer
E... | def fib_recursive(n):
if n <= 1:
return n
return fib_recursive(n-1) + fib_recursive(n-2)
def fib_dynamic(n):
if n == 0:
return 0
fib_list = [0, 1]
for i in range(2, n + 1):
fib_list.append(fib_list[-1] + fib_list[-2])
return fib_list[n]
def fib_iterative(n):
if n ==... | import pytest
from solution import fib_hybrid
def test_fib_recursive():
for i in range(10):
assert fib_hybrid(i) == fib_recursive(i)
def test_fib_dynamic():
for i in range(10, 51):
assert fib_hybrid(i) == fib_dynamic(i)
def test_fib_iterative():
large_values = [51, 100, 500, 1000, 5000, 1... | [
{
"docstring": null,
"function_declaration": "def fib_recursive(n):",
"function_name": "fib_recursive",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def fib_dynamic(n):",
"function_name": "fib_dynamic",
"parameter_list": "(n)"
},
{
"docstring":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fib_recursive(n):\n if n <= 1:\n return n\n return fib_recursive(n-1) + fib_recursive(n-2)\n\ndef fib_dynamic(n):\n if n == 0:\n re... | trial_gpt4o_0 | {
"original_instruction": "### Problem: Optimize Fibonacci Calculation\n\nYou are given three methods to compute the n-th Fibonacci number: recursive, list-based dynamic programming, and iterative. Each method has different performance characteristics. Your task is to combine these methods into a hybrid solution that... | 0.763752 | Data_Structure_19184 | C | [
"fib_recursive",
"fib_dynamic",
"fib_iterative",
"fib_hybrid"
] | 4 | [
[
"fib_hybrid",
"fib_dynamic"
],
[
"fib_hybrid",
"fib_iterative"
],
[
"fib_hybrid",
"fib_recursive"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 65e22952d1a1145b01f0c26bb45200d9bb7001ca | bdc6d42a235eb0660ed9633f117ebce259546b34 | |||
v1.0 | complete | Data_Structure | Data_Structure_19067_C | from typing import List
def max_flow_dinics(capacity: List[List[int]], source: int, sink: int) -> int:
""" Compute the maximum flow in a network using Dinic's algorithm.
Args:
capacity : List[List[int]] - A two-dimensional list representing the capacity of each edge in the network.
source : int - ... | from typing import List
from collections import deque
def bfs_level_graph(capacity, level, source, sink):
queue = deque([source])
level[source] = 0
while queue:
u = queue.popleft()
for v in range(len(capacity)):
if level[v] < 0 and capacity[u][v] > 0:
level[... | from solution import max_flow_dinics
def test_max_flow_example_case():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert max_flow_dini... | [
{
"docstring": null,
"function_declaration": "def bfs_level_graph(capacity, level, source, sink):",
"function_name": "bfs_level_graph",
"parameter_list": "(capacity, level, source, sink)"
},
{
"docstring": null,
"function_declaration": "def send_flow(u, flow, sink, level, capacity, start... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List\n\ndef max_flow_dinics(capacity: List[List[int]], source: int, sink: int) -> int:\n n = len(capacity... | trial_gpt4o_1 | {
"original_instruction": "### Maximum Network Flow Challenge\n\n#### Context\nYou are working as a network engineer and have been tasked with optimizing the transportation of goods over a network of pipelines. Each pipeline has a maximum capacity indicating the maximum flow of goods it can handle per unit time. Your... | 0.537084 | Data_Structure_19067 | C | [
"bfs_level_graph",
"send_flow",
"max_flow_dinics"
] | 3 | [
[
"max_flow_dinics",
"bfs_level_graph"
],
[
"max_flow_dinics",
"send_flow"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 786a391952053d21f75a17baeed68a47ba9d723a | def279617ea1eef3b92724e5679638912f56bb71 | |||
v1.0 | complete | Data_Structure | Data_Structure_19369_C | from typing import List
def rotate_180(matrix: List[List[int]]) -> List[List[int]]:
"""Rotate a 2D matrix 180 degrees utilizing two intermediate 90-degree rotations performed in succession.
>>> rotate_180([
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]
... ])
[[9, 8, 7],
[6, ... | from typing import List
def rotate_90(matrix: List[List[int]]) -> List[List[int]]:
"""Rotate the matrix 90 degrees clockwise"""
# Transpose the matrix and then reverse each row
return [list(reversed(col)) for col in zip(*matrix)]
def rotate_180(matrix: List[List[int]]) -> List[List[int]]:
"""Rotate th... | import pytest
from solution import rotate_180
def test_rotate_180_3x3():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
expected = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
assert rotate_180(matrix) == expected
def test_rotate_180_2x2():
matrix = [
... | [
{
"docstring": "Rotate the matrix 90 degrees clockwise",
"function_declaration": "def rotate_90(matrix):",
"function_name": "rotate_90",
"parameter_list": "(matrix)"
},
{
"docstring": "Rotate the matrix 180 degrees",
"function_declaration": "def rotate_180(matrix):",
"function_name":... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rotate_180(matrix: List[List[int]]) -> List[List[int]]:\n def rotate_90(matrix: List[List[int]]) -> List[List[int]]:\n ... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with creating a function to rotate a 2D matrix 180 degrees utilizing two intermediate 90-degree rotations performed in succession.\n\n### Function Signature\n\n```python\ndef rotate_180(matrix: List[List[int]]) -> List[List[int]]:\n pass\n```\n\n### Input\n\n* **`matrix`**... | 0.599849 | Data_Structure_19369 | C | [
"rotate_90",
"rotate_180"
] | 2 | [
[
"rotate_180",
"rotate_90"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f2ee4be1db2552b21798acbf4716b1092b30bce8 | 244156eb8f59e9e1ed7c6d83ae0667344c07b395 | |||
v1.0 | complete | Data_Structure | Data_Structure_18933_C | class DirectedGraph:
def __init__(self, adjacency_list):
self.adjacency_list = adjacency_list
def has_cycle(graph: DirectedGraph) -> bool:
"""
Detects if there's a cycle in the directed graph.
:param graph: DirectedGraph - The directed graph instance to check for cycles.
:return: bool ... | class DirectedGraph:
def __init__(self, adjacency_list):
self.adjacency_list = adjacency_list
def _dfs(vertex, visited, rec_stack, graph):
visited.add(vertex)
rec_stack.add(vertex)
for neighbor in graph.adjacency_list.get(vertex, []):
if neighbor not in visited:
if _dfs(nei... | from solution import has_cycle, DirectedGraph
def test_cycle_present():
graph_data = {
'A': ['B'],
'B': ['C'],
'C': ['A']
}
graph = DirectedGraph(graph_data)
assert has_cycle(graph) == True
def test_no_cycle():
graph_data = {
'A': ['B'],
'B': ['C'],
... | [] | [
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 DirectedGraph:\n def __init__(self, graph_data):\n \"\"\"\n Initializes the directed graph with given adjacency list.\n :param g... | trial_gpt4o_2 | {
"original_instruction": "You need to implement a function to detect cycles in a directed graph. A cycle in a directed graph is a path that starts and ends at the same vertex and has at least one edge.\n\n### Function Signature\n```python\ndef has_cycle(graph: DirectedGraph) -> bool:\n \"\"\"\n :param graph: D... | 0.579711 | Data_Structure_18933 | C | [
"_dfs",
"has_cycle"
] | 2 | [
[
"has_cycle",
"_dfs"
]
] | 1 | [] | false | [
"DirectedGraph"
] | true | pytest | true | [] | true | 7393b695c9da2d83316158e5f53408e295bd40d6 | f567197dc96d48a301266ccb1618b4d06cfb127d | |||
v1.0 | complete | Data_Structure | Data_Structure_19193_C | import random
from sympy import isprime, primerange
def is_primitive_root(a, p):
"""Check if a is a primitive root of prime p or not."""
if not isprime(p):
return False
required_set = set(num for num in range(1, p))
actual_set = {pow(a, d, p) for d in range(1, p)}
return required_set == act... | import random
from sympy import isprime, primerange
def is_primitive_root(a, p):
"""
Check if a is a primitive root of prime p or not.
"""
if not isprime(p):
return False
required_set = set(num for num in range(1, p))
actual_set = {pow(a, d, p) for d in range(1, p)}
return requir... | from solution import secure_diffie_hellman # Ensure to name your file appropriately or adjust the import here
def test_valid_prime_and_primitive_root():
p = 23
a = 5
assert secure_diffie_hellman(p, a) == True
def test_invalid_prime():
p = 24
a = 5
assert secure_diffie_hellman(p, a) == None
d... | [
{
"docstring": "Check if a is a primitive root of prime p or not.",
"function_declaration": "def is_primitive_root(a, p):",
"function_name": "is_primitive_root",
"parameter_list": "(a, p)"
},
{
"docstring": null,
"function_declaration": "def secure_diffie_hellman(p, a):",
"function_n... | [
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\n\ndef is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n ... | trial_gpt4o_2 | {
"original_instruction": "### Key Exchange with Enhanced Security\n\nAlice and Bob want to share a secret key through an insecure channel by leveraging the Diffie-Hellman key exchange method. Implement a function `secure_diffie_hellman(p, a)` that verifies if the given `p` is a prime and `a` is a primitive root of `... | 0.523322 | Data_Structure_19193 | C | [
"is_primitive_root",
"secure_diffie_hellman"
] | 2 | [
[
"secure_diffie_hellman",
"is_primitive_root"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 01f7f197a7bb7b0cb78719daa50514287013933c | fa174b427819ad0c63d405c3d0a2c525f6e55656 | |||
v1.0 | complete | Data_Structure | Data_Structure_18074_C | class Node:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def inorder_traversal(root, level, levels):
"""
Helper method to perform inorder traversal.
"""
pass
def level_wise_inorder_traversal(root: Node) -> List[L... | class Node:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def inorder_traversal(root, level, levels):
"""
Helper method to perform inorder traversal.
"""
if root is None:
return
# Ensure the current le... | from solution import Node, level_wise_inorder_traversal
def test_level_wise_inorder_traversal_singleton():
root = Node(1)
assert level_wise_inorder_traversal(root) == [[1]]
def test_level_wise_inorder_traversal_basic():
root = Node(1, Node(2), Node(3))
assert level_wise_inorder_traversal(root) == [[1]... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef level_... | trial_gpt4o_2 | {
"original_instruction": "You are given a binary tree with integer values in its nodes, and you need to traverse and return the values in the in-order manner, but this time, you need to return a list which represents the level-wise in-order traversal, i.e., For each level of the tree, you will perform an in-order tr... | 0.511002 | Data_Structure_18074 | C | [
"inorder_traversal",
"level_wise_inorder_traversal"
] | 2 | [
[
"level_wise_inorder_traversal",
"inorder_traversal"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | be11ab4cd87900697ebc6ad61b2d3a3f22152e12 | acb8401cdb04d5314b98b579feb33652deef2a7a | |||
v1.0 | complete | Data_Structure | Data_Structure_19221_C | def merge_sort(arr):
"""
Sorts the array using the merge sort algorithm.
Parameters:
arr (list): List of integers to be sorted.
Returns:
list: New list with elements sorted in non-decreasing order.
"""
pass
def merge(left, right):
"""
Merges two sorted lists into one s... | def merge_sort(arr):
"""
Sorts the array using the merge sort algorithm.
Parameters:
arr (list): List of integers to be sorted.
Returns:
list: New list with elements sorted in non-decreasing order.
"""
# Base case: if the list is empty or has one element, return it
if len(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_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_list():
assert merg... | [
{
"docstring": "Sorts the array using the merge sort algorithm.\n\nParameters:\narr (list): List of integers to be sorted.\n\nReturns:\nlist: New list with elements sorted in non-decreasing order.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(ar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Performs the merge sort on the input list and returns a sorted list.\n \n :param arr: list of integers to be sorte... | trial_gpt4o_2 | {
"original_instruction": "### Question Statement\nYou are working on a large data processing application that needs to frequently sort datasets of varying sizes. To ensure robust and efficient sorting, you will implement a classic sorting algorithm known as Merge Sort. \n\n### Task\nWrite a function `merge_sort(arr)... | 0.660897 | Data_Structure_19221 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 55fee1ab1449aa40485642ecbe834dcad16edbdf | d6ca270855fe0ccc129e7255ff580860ccf85724 | |||
v1.0 | complete | Data_Structure | Data_Structure_18962_C | from typing import List
def filter_primes(number_list: List[int]) -> List[int]:
"""
Given a list of integers, return a new list containing only the prime numbers.
:param number_list: List[int] - A list containing integer numbers.
:return: List[int] - A list containing only the prime numbers from numbe... | from typing import List
def is_prime(n: int) -> bool:
"""
Efficient prime-checking algorithm to determine if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
limit = int(n**0.5) + 1
for i in range(3, limit, 2):
... | from solution import filter_primes
def test_filter_primes_simple():
assert filter_primes([10, 15, 2, 3, 5, 30, 31, 37, 0, -7, 101]) == [2, 3, 5, 31, 37, 101]
def test_filter_primes_empty():
assert filter_primes([]) == []
def test_filter_primes_no_primes():
assert filter_primes([4, 6, 8, 10, 12, 14]) == [... | [
{
"docstring": "Efficient prime-checking algorithm to determine if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given a list of integers, return a new list containing only the prime numbers.",
"fu... | [
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 is_prime(n: int) -> bool:\n \"\"\"\n Check if the given number n is a prime number.\n \n Args:\n n (int): Number... | trial_gpt4o_1 | {
"original_instruction": "### Prime Number Filter\n\nYou are given a list of integers and your task is to filter out the prime numbers using the provided efficient prime-checking algorithm.\n\n#### Function Signature\n```python\ndef filter_primes(number_list: List[int]) -> List[int]:\n \"\"\"\n Given a list of... | 0.790184 | Data_Structure_18962 | C | [
"is_prime",
"filter_primes"
] | 2 | [
[
"filter_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d5d1e23ed785cdfa9a9bfd16b3a1a635d84073af | d3d267c6cb88bfa6672b42ecbd2d8ffe367760bc | |||
v1.0 | complete | Data_Structure | Data_Structure_19437_C | def toggle_heap_sort(arr, use_max_heap=True, simulation=False):
"""
Sorts an array in ascending order using either max-heap or min-heap.
Parameters:
- arr (List[int]): The input array to be sorted.
- use_max_heap (bool): A flag to toggle between max-heap (True) and min-heap (False).
- simu... | def max_heapify(arr, n, i, simulation):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
... | from solution import toggle_heap_sort
def test_toggle_heap_sort_max_heap():
assert toggle_heap_sort([4, 10, 3, 5, 1], use_max_heap=True) == [1, 3, 4, 5, 10]
def test_toggle_heap_sort_min_heap():
assert toggle_heap_sort([4, 10, 3, 5, 1], use_max_heap=False) == [1, 3, 4, 5, 10]
def test_toggle_heap_sort_single... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, simulation):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, simulation)"
},
{
"docstring": null,
"function_declaration": "def min_heapify(arr, n, i, simulation):",
"function_name": "min_heapify... | [
0,
0,
0,
0,
0,
1,
0,
1,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def heapify(arr, n, i, use_max_heap=True, simulation=False):\n if use_max_heap:\n largest = i # Initialize largest as root for max-heap\n lef... | trial_gpt4o_8 | {
"original_instruction": "### Heap Sort Toggle Implementation\n\n**Objective**: Write a function `toggle_heap_sort` that can switch between using a max-heap and min-heap for sorting an array.\n\n**Context**: You are given the tasks to sort an array using Heap Sort, and depending on user preference, you need to choos... | 0.642195 | Data_Structure_19437 | C | [
"max_heapify",
"min_heapify",
"heap_sort",
"toggle_heap_sort"
] | 4 | [
[
"heap_sort",
"max_heapify"
],
[
"heap_sort",
"min_heapify"
],
[
"toggle_heap_sort",
"heap_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | f4d684226cdd0b1955ae3fa5e363d29e1b9b7ea8 | df810af9509126c0bd4e8ddb37e4c9aeb505f4a0 | |||
v1.0 | complete | Data_Structure | Data_Structure_18741_C | from typing import List
def optimized_chinese_remainder(nums: List[int], rems: List[int]) -> int:
"""
Solve the system of linear congruences using the Chinese Remainder Theorem.
Given lists of pairwise coprime positive integers nums and corresponding remainders rems,
returns the smallest positive ... | from typing import List, Tuple
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
"""
Returns a tuple (g, x, y), where g is the greatest common divisor of a and b, and
x and y are the coefficients of Bézout's identity, i.e., a*x + b*y = g
"""
if a == 0:
return (b, 0, 1)
else:
... | from solution import optimized_chinese_remainder
def test_optimized_chinese_remainder_basic():
assert optimized_chinese_remainder([3, 5, 7], [2, 3, 2]) == 23
def test_optimized_chinese_remainder_single_congruence():
assert optimized_chinese_remainder([5], [3]) == 3
def test_optimized_chinese_remainder_pairwi... | [
{
"docstring": "Returns a tuple (g, x, y), where g is the greatest common divisor of a and b, and \nx and y are the coefficients of Bézout's identity, i.e., a*x + b*y = g",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"do... | [
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 extended_gcd(a: int, b: int) -> Tuple[int, int, int]:\n \"\"\"\n Returns a tuple (g, x, y), where g is the greates... | trial_gpt4o_0 | {
"original_instruction": "You are given a list of pairwise coprime positive integers `nums` and a list of corresponding remainders `rems`. Your task is to implement an optimized function to solve the system of congruences using the Chinese Remainder Theorem (CRT).\n\n#### Function Signature\n```python\ndef optimized... | 0.574946 | Data_Structure_18741 | C | [
"extended_gcd",
"optimized_chinese_remainder"
] | 2 | [
[
"optimized_chinese_remainder",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9c2e868dcc19d43523dd1fea8a4a34a296301c1d | db3000fe89ee76c653abf477ab15b43e42028eaf | |||
v1.0 | complete | Data_Structure | Data_Structure_17569_C | from collections import deque
def bi_directional_search(graph: dict, start: int, target: int) -> list:
""" Perform a bi-directional search to find the shortest path in an undirected graph.
Args:
graph (dict): The graph represented as an adjacency list, where keys are nodes,
a... | from collections import deque
def bi_directional_search(graph, start, target):
"""
Performs a bi-directional BFS to find the shortest path from start to target.
"""
if start == target:
return [start]
# Initialize BFS queues for forward and backward search
forward_queue = deque([start])... | import pytest
from solution import bi_directional_search
def test_simple_graph():
graph = {
1: [2, 3],
2: [1, 4],
3: [1, 4],
4: [2, 3, 5],
5: [4]
}
assert bi_directional_search(graph, 1, 5) == [1, 2, 4, 5] or bi_directional_search(graph, 1, 5) == [1, 3, 4, 5]
def te... | [
{
"docstring": "Performs a bi-directional BFS to find the shortest path from start to target.",
"function_declaration": "def bi_directional_search(graph, start, target):",
"function_name": "bi_directional_search",
"parameter_list": "(graph, start, target)"
},
{
"docstring": null,
"functi... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bi_directional_search(graph, start, target):\n if start == target:\n return [start]\n \n # Initialize two... | trial_gpt4o_1 | {
"original_instruction": "### Advanced Graph Traversal: Bi-Directional Search\n\n#### Context:\nYou are given an undirected graph and need to find the shortest path from a starting node to a target node. While traditional BFS ensures finding the shortest path in unweighted graphs, for very large graphs, it can be mo... | 0.516091 | Data_Structure_17569 | C | [
"bi_directional_search",
"found_path",
"reconstruct_path"
] | 3 | [
[
"bi_directional_search",
"found_path"
],
[
"bi_directional_search",
"reconstruct_path"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 99f2601c67743481f0d560979324b429d6cd1434 | 8e563926d79081b143835605dbed5242a7c7c8c9 | |||
v1.0 | complete | Data_Structure | Data_Structure_19363_C | from typing import Tuple, Dict, Any
def nearest_neighbor_classification(x: Tuple[float, ...], tSet: Dict[Tuple[float, ...], Any]) -> Any:
"""
Determine the label of the nearest training vector to x using the Nearest Neighbor Algorithm with Euclidean distance.
Parameters:
x (tuple): A numeric tuple... | import math
def euclidean_distance(v1, v2):
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def nearest_neighbor_classification(x, tSet):
"""
Returns the label of the nearest training vector to x using Euclidean distance.
Parameters:
x (tuple): A numeric tuple representing the vec... | from solution import nearest_neighbor_classification
def test_nearest_neighbor_classification_standard():
x = (1.0, 2.0)
tSet = {
(1.1, 2.1): 'A',
(1.2, 3.1): 'B',
(0.9, 1.9): 'C'
}
assert nearest_neighbor_classification(x, tSet) == 'C'
def test_nearest_neighbor_classification_... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(v1, v2):",
"function_name": "euclidean_distance",
"parameter_list": "(v1, v2)"
},
{
"docstring": "Returns the label of the nearest training vector to x using Euclidean distance.\n\nParameters:\nx (tuple): A numeric tuple re... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Tuple, Dict, Any\nimport math\n\ndef euclidean_distance(v1: Tuple[float, ...], v2: Tuple[float, ...]) -> float:\n return math.sqrt(sum((... | trial_gpt4o_2 | {
"original_instruction": "You are given a set of labeled vectors (training set) and an unknown vector for which you need to determine the label using the Nearest Neighbor Algorithm.\n\n**Functional Requirements**:\n- Implement a function `nearest_neighbor_classification(x, tSet)` where:\n - `x`: A tuple of numerica... | 0.654577 | Data_Structure_19363 | C | [
"euclidean_distance",
"nearest_neighbor_classification"
] | 2 | [
[
"nearest_neighbor_classification",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e78998ab2088007dcf9ad4a788ebb82506caeea0 | 4e3f500077e7fa6f5700ca3cd84d2339892c021f | |||
v1.0 | complete | Data_Structure | Data_Structure_19609_C | from typing import Tuple
def generate_key(k: int) -> Tuple[int, int, int]:
"""Generate RSA keys of bit length k.
>>> n, e, d = generate_key(16)
>>> isinstance(n, int)
True
>>> isinstance(e, int)
True
>>> isinstance(d, int)
True
"""
def encrypt(data: int, e: int, n: int) -> int:
... | import random
from typing import Tuple
from sympy import isprime
from sympy.ntheory.generate import nextprime
def generate_key(k: int) -> Tuple[int, int, int]:
"""
Generate RSA keys of bit length k.
"""
assert k > 1, "Key length k should be greater than 1."
# Generate two large random prime nu... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert n > 0
assert e > 0
assert d > 0
def test_encrypt_decrypt():
n, e, d = generate_key(16)
data =... | [
{
"docstring": "Generate RSA keys of bit length k.",
"function_declaration": "def generate_key(k):",
"function_name": "generate_key",
"parameter_list": "(k)"
},
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\nfrom typing import Tuple\n\ndef generate_prime_candidate(length):\n \"\"\"\n Generate an odd inte... | trial_gpt4o_1 | {
"original_instruction": "### RSA Encryption Challenge\n\nYou are required to implement an RSA encryption and decryption system. The task involves generating RSA keys, encrypting a message, and decrypting it back to the original message using the provided keys.\n\n#### Function Signature\n```python\ndef generate_key... | 0.716891 | Data_Structure_19609 | C | [
"generate_key",
"gcd",
"modinv",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"modinv"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 2f82c32bea3e1d2ad575186da5d1304ed5604129 | e10360a9a73ecf113f588314390ba8adece8c6dc | |||
v1.0 | complete | Data_Structure | Data_Structure_19080_C | def generate_key(k, seed=None):
""" Generate RSA public and private keys.
Args:
- k (int): Number of bits for the modulus n.
- seed (optional int): Seed for random generation.
Returns:
- (n, e, d): Tuple of RSA modulus n, public exponent e, and private exponent d.
"""
pass
def... | import random
from math import gcd
from sympy import isprime
def generate_prime(bits):
"""Generate a prime number with the given number of bits."""
while True:
p = random.getrandbits(bits)
if isprime(p):
return p
def modinv(a, m):
"""Return the modular inverse of a modulo m."""... | from solution import generate_key, encrypt, decrypt
def test_rsa_key_generation():
n, e, d = generate_key(512, seed=42)
assert n.bit_length() == 512
assert e > 1
assert d > 1
def test_rsa_encryption_decryption():
n, e, d = generate_key(512, seed=42)
data = 12345
encrypted_data = encrypt(da... | [
{
"docstring": "Generate a prime number with the given number of bits.",
"function_declaration": "def generate_prime(bits):",
"function_name": "generate_prime",
"parameter_list": "(bits)"
},
{
"docstring": "Return the modular inverse of a modulo m.",
"function_declaration": "def modinv(a... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_large_prime(bits, seed=None):\n if seed is not None:\n random.seed(seed)\n ... | trial_gpt4o_9 | {
"original_instruction": "**RSA Key Generation and Encryption-Decryption**\n\n**Objective**: Implement the missing part of the RSA encryption-decryption system and ensure correct functionality by generating RSA keys, and using them to encrypt and decrypt data.\n\n**Scenario**:\nYou are developing a system for secure... | 0.767084 | Data_Structure_19080 | C | [
"generate_prime",
"modinv",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_prime"
],
[
"generate_key",
"modinv"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 0fb5ce51ecb36617c1e007301c45dafe066ccd9a | d0a70f7f1f6539f89147d3c16ae57300f535fe79 | |||
v1.0 | complete | Data_Structure | Data_Structure_18682_C | import random
def is_prime(n: int) -> bool:
"""Check if a number is prime."""
pass
def find_primitive_root(p: int) -> int:
"""Find a primitive root of p."""
pass
def secure_communication(a: int, p: int) -> tuple:
"""Implement a secure communication system using Diffie-Hellman Key Exchange.
... | import random
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return... | from solution import secure_communication, is_prime, find_primitive_root
def test_secure_communication():
a, p = 5, 23
alice_shared_key, bob_shared_key = secure_communication(a, p)
assert alice_shared_key == bob_shared_key
def test_invalid_prime():
a, p = 5, 22
try:
secure_communication(a,... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find a primitive root of p.",
"function_declaration": "def find_primitive_root(p):",
"function_name": "find_primitive_root... | [
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 prime.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n ... | trial_gpt4o_0 | {
"original_instruction": "You are tasked with implementing a secure communication system between two parties (Alice and Bob) using Diffie-Hellman Key Exchange. The system should ensure that both parties can share a common secret key securely over an insecure channel.\n\nWrite a function `secure_communication(a: int,... | 0.561595 | Data_Structure_18682 | C | [
"is_prime",
"find_primitive_root",
"secure_communication"
] | 3 | [
[
"secure_communication",
"find_primitive_root"
],
[
"secure_communication",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 05186dc1dbb55dd117c4b4b565493b748c155997 | 152251f63b12116e7fd9731dbfd33729d13c6e48 | |||
v1.0 | complete | Data_Structure | Data_Structure_19480_C | from typing import List
def advanced_bucket_sort(arr: List[float]) -> List[float]:
""" Implement an enhanced bucket sort that optimizes performance for various data distributions.
Instead of using fixed bucket sizes, dynamically size each bucket to balance the load more effectively.
Use merge sort within e... | from typing import List
def merge_sort(arr: List[float]) -> List[float]:
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i]... | from solution import advanced_bucket_sort
def test_empty_list():
assert advanced_bucket_sort([]) == []
def test_single_element_list():
assert advanced_bucket_sort([0.42]) == [0.42]
def test_uniformly_distributed_list():
arr = [0.78, 0.32, 0.54, 0.01, 0.95, 0.12]
assert advanced_bucket_sort(arr) == [0... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def advanced_bucket_sort(arr):",
"function_name": "advanced_bucket_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[float]) -> List[float]:\n if len(arr) <= 1:\n return arr\n\n def merge(left: List[float], rig... | trial_gpt4o_2 | {
"original_instruction": "## Problem Statement\n\nImplement an enhanced bucket sort that optimizes performance for various data distributions. Instead of using fixed bucket sizes, dynamically size each bucket to balance the load more effectively. Use merge sort within each bucket for improved efficiency.\n\n### Func... | 0.578161 | Data_Structure_19480 | C | [
"merge_sort",
"advanced_bucket_sort"
] | 2 | [
[
"advanced_bucket_sort",
"merge_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4c94a556c05bbd816d6fc5c1d914dd1dfcadc68e | 252d884f3a1bf92570fbc25812ae37c984f89248 | |||
v1.0 | complete | Data_Structure | Data_Structure_19870_C | def comb_sort(arr: List[int]) -> List[int]:
"""
Function to perform comb sort on the provided array.
"""
pass
def sort_and_remove_duplicates(arr: List[int]) -> List[int]:
"""
Function to sort the array in ascending order and remove duplicates.
>>> sort_and_remove_duplicates([4, 6, 2, 4, 3, ... | def comb_sort(arr):
"""
Function to perform comb sort on the provided array.
"""
gap = len(arr)
shrink = 1.3
sorted = False
while not sorted:
gap = int(gap / shrink)
if gap <= 1:
gap = 1
sorted = True
i = 0
while i + gap < len... | from solution import comb_sort, sort_and_remove_duplicates
def test_comb_sort_unsorted():
assert comb_sort([4, 6, 2, 4, 3, 2, 1]) == [1, 2, 2, 3, 4, 4, 6]
def test_comb_sort_sorted():
assert comb_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_comb_sort_reverse_sorted():
assert comb_sort([5, 4, 3, 2, 1... | [
{
"docstring": "Function to perform comb sort on the provided array.",
"function_declaration": "def comb_sort(arr):",
"function_name": "comb_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Function to sort the array in ascending order and remove duplicates.",
"function_declaration": ... | [
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 sort_and_remove_duplicates(arr):\n \"\"\"\n Sorts the given list arr of integers in ascending order and removes any duplicates.\n \"\"\"\n def... | trial_gpt4o_1 | {
"original_instruction": "**Question: Efficiently Sort and Remove Duplicates**\n\nYou work for a software firm where it's common to handle large lists of unsorted numbers. Often, you need to sort these lists and remove any duplicate entries. As the datasets can get quite large, a bubble sort is inefficient. Instead,... | 0.66673 | Data_Structure_19870 | C | [
"comb_sort",
"sort_and_remove_duplicates"
] | 2 | [
[
"sort_and_remove_duplicates",
"comb_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 15e1315a09336592bfb33ba7d17ac31e13121058 | c20982c6effd28fc3be49dfc7f0e2370746386f9 | |||
v1.0 | complete | Data_Structure | Data_Structure_19862_C | from typing import List
def optimized_gnome_sort(arr: List[int], threshold: int = 20) -> List[int]:
""" Sort an array using Gnome Sort for small arrays and an optimized sorting algorithm for larger arrays.
>>> optimized_gnome_sort([34, 2, 10, -9])
[-9, 2, 10, 34]
>>> optimized_gnome_sort([1, 2, 3, 4, 5... | from typing import List
def gnome_sort(arr: List[int]) -> List[int]:
n = len(arr)
pos = 0
while pos < n:
if pos == 0 or arr[pos] >= arr[pos - 1]:
pos += 1
else:
arr[pos], arr[pos - 1] = arr[pos - 1], arr[pos]
pos -= 1
return arr
def optimized_gnome_s... | from solution import optimized_gnome_sort
def test_optimized_gnome_sort_small_array():
assert optimized_gnome_sort([34, 2, 10, -9]) == [-9, 2, 10, 34]
assert optimized_gnome_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
assert optimized_gnome_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
assert optimized_gnome_s... | [
{
"docstring": null,
"function_declaration": "def gnome_sort(arr):",
"function_name": "gnome_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def optimized_gnome_sort(arr, threshold=20):",
"function_name": "optimized_gnome_sort",
"parameter_list":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef gnome_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Gnome Sort algorithm implementation for small datasets.\n \"\"\"\n... | trial_gpt4o_2 | {
"original_instruction": "### Gnome Sorting Challenge\n\nYou have been hired as a software engineer to help improve and implement robust functionalities in sorting arrays. One of the tasks is to implement the Gnome Sort algorithm and then optimize it. Implement the Gnome Sort algorithm adhering to the typical operat... | 0.628717 | Data_Structure_19862 | C | [
"gnome_sort",
"optimized_gnome_sort"
] | 2 | [
[
"optimized_gnome_sort",
"gnome_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 98d1f72c7ee96ec2d7f417294dd3d7257c096124 | 2de931c1fb62bce6f622baeee1a5a4656d218820 | |||
v1.0 | complete | Data_Structure | Data_Structure_19948_C | from typing import List
def findWordSquares(words: List[str]) -> List[List[str]]:
""" Find all possible word squares from a list of words.
Each word must be of the same length, and a word square is a matrix of words where
the k-th row and k-th column read the same.
Args:
words : List[str] : A... | from typing import List, Dict
from collections import defaultdict
def build_prefix_hash(words: List[str]) -> Dict[str, List[str]]:
"""
Builds a prefix hash map for quick prefix-based lookups.
"""
prefix_dict = defaultdict(list)
for word in words:
for i in range(len(word)):
prefi... | from solution import findWordSquares
def test_example_case():
words = ["area", "lead", "wall", "lady", "ball"]
squares = findWordSquares(words)
expected_squares = [
["wall", "area", "lead", "lady"],
["ball", "area", "lead", "lady"]
]
assert sorted(squares) == sorted(expected_squares... | [
{
"docstring": "Builds a prefix hash map for quick prefix-based lookups.",
"function_declaration": "def build_prefix_hash(words):",
"function_name": "build_prefix_hash",
"parameter_list": "(words)"
},
{
"docstring": null,
"function_declaration": "def findWordSquares(words):",
"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": "from typing import List, Dict\nfrom collections import defaultdict\n\ndef build_prefix_hash(words: List[str]) -> Dict[str, List[str]]:\n \"\"\"\n Builds... | trial_gpt4o_0 | {
"original_instruction": "You are given a list of unique words, each of the same length, and your task is to form all possible word squares where each row and each column of the square reads the same word.\n\nA word square is defined as a sequence of words of the same length that forms a valid word square such that ... | 0.624507 | Data_Structure_19948 | C | [
"build_prefix_hash",
"findWordSquares"
] | 2 | [
[
"findWordSquares",
"build_prefix_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f049da7a0de477fbe6dc6735c436d8d73c7bedab | f3299494080523e494587651b05c8c147ab93f41 | |||
v1.0 | complete | Data_Structure | Data_Structure_19955_C | def compute_gcd(a, b):
"""
Compute the greatest common divisor (GCD) using the Euclidean algorithm.
>>> compute_gcd(12, 18)
6
>>> compute_gcd(100, 25)
25
"""
# Euclidean Algorithm implementation
def compute_gcd_bitwise(a, b):
"""
Compute the GCD using bitwise operations.
>>>... | def compute_gcd(a, b):
"""
Compute the greatest common divisor (GCD) using the Euclidean algorithm.
"""
while b:
a, b = b, a % b
return a
def compute_gcd_bitwise(a, b):
"""
Compute the GCD using bitwise operations.
"""
if a == 0: return b
if b == 0: return a
# Find ... | from solution import compute_gcd, compute_gcd_bitwise, compute_lcm, count_trailing_zeros
def test_compute_gcd():
assert compute_gcd(12, 18) == 6
assert compute_gcd(100, 25) == 25
assert compute_gcd(7, 1) == 1
assert compute_gcd(27, 18) == 9
def test_compute_gcd_bitwise():
assert compute_gcd_bitwis... | [
{
"docstring": "Compute the greatest common divisor (GCD) using the Euclidean algorithm.",
"function_declaration": "def compute_gcd(a, b):",
"function_name": "compute_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Compute the GCD using bitwise operations.",
"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": "def compute_gcd(a, b):\n \"\"\"\n Compute the greatest common divisor (GCD) using the Euclidean algorithm.\n \"\"\"\n while b:\n a, b = b, ... | trial_gpt4o_0 | {
"original_instruction": "### Integer Pair Analysis for GCD and LCM Computation\n\n#### Objective:\nImplement functions to analyze pairs of integers by computing the greatest common divisor (GCD) and least common multiple (LCM) both conventionally and using bitwise operations. Additionally, include a feature to coun... | 0.722957 | Data_Structure_19955 | C | [
"compute_gcd",
"compute_gcd_bitwise",
"compute_lcm",
"count_trailing_zeros"
] | 4 | [
[
"compute_lcm",
"compute_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f5cce36413d021ffe7ee6f80ce8c02011e49dcec | 67890481322b9fd5cf5eb6f762793dc7baf31626 | |||
v1.0 | complete | Data_Structure | Data_Structure_19512_C | def bucket_sort(arr: List[int]) -> List[int]:
"""Implement Bucket Sort algorithm using Merge Sort for the secondary sorting of elements within each bucket.
Args:
- arr (List[int]): List of integers to be sorted.
Returns:
- List[int]: Sorted list of integers.
Example:
>>> bucket_sort([... | 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]:
result = []
i = j = ... | from solution import bucket_sort
def test_empty_array():
assert bucket_sort([]) == []
def test_single_element():
assert bucket_sort([5]) == [5]
def test_sorted_array():
assert bucket_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert bucket_sort([5, 4, 3, 2, 1]) == [1, ... | [
{
"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)"
},
{
"docst... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left = ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement Bucket Sort with Improved Secondary Sorting\n\n#### Context\nYou are working as a software engineer at a company that deals with large datasets. The datasets contain numerical information which needs to be sorted efficiently. Bucket Sort is one of the algorithms you ... | 0.545603 | Data_Structure_19512 | C | [
"merge_sort",
"merge",
"bucket_sort"
] | 3 | [
[
"bucket_sort",
"merge_sort"
],
[
"merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 64d1b24e951aa5a2d11a2b892e15ba7a8966be7e | 206364b025d3722c8ab87cc0b0de653b42f1956d | |||
v1.0 | complete | Data_Structure | Data_Structure_19888_C | def hailstone_sequence(n: int) -> list:
"""
Generates the Hailstone sequence starting from integer n.
>>> hailstone_sequence(1) [1]
>>> hailstone_sequence(2) [2, 1]
>>> hailstone_sequence(3) [3, 10, 5, 16, 8, 4, 2, 1]
>>> hailstone_sequence(5) [5, 16, 8, 4, 2, 1]
"""
def longest_hailsto... | def hailstone_sequence(n: int) -> list:
"""
Generates the Hailstone sequence starting from integer n.
"""
sequence = []
while n != 1:
sequence.append(n)
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
sequence.append(1)
return sequence
def longe... | from solution import hailstone_sequence, longest_hailstone_sequence
def test_hailstone_sequence():
assert hailstone_sequence(1) == [1]
assert hailstone_sequence(2) == [2, 1]
assert hailstone_sequence(3) == [3, 10, 5, 16, 8, 4, 2, 1]
assert hailstone_sequence(5) == [5, 16, 8, 4, 2, 1]
def test_longest_... | [
{
"docstring": "Generates the Hailstone sequence starting from integer n.",
"function_declaration": "def hailstone_sequence(n):",
"function_name": "hailstone_sequence",
"parameter_list": "(n)"
},
{
"docstring": "Finds the starting number (1 ≤ n ≤ m) which produces the longest Hailstone seque... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def hailstone_sequence(n):\n \"\"\"\n Generates the Hailstone sequence for a given starting number n.\n \"\"\"\n sequence = []\n while n != 1:\... | trial_gpt4o_2 | {
"original_instruction": "### Hailstone Problem\n\nConsider the following Hailstone sequence generation process:\n1. Start with any positive integer `n`.\n2. If `n` is 1, stop the process.\n3. If `n` is even, the next number in the sequence is `n/2`.\n4. If `n` is odd, the next number in the sequence is `3n + 1`.\n5... | 0.582493 | Data_Structure_19888 | C | [
"hailstone_sequence",
"longest_hailstone_sequence"
] | 2 | [
[
"longest_hailstone_sequence",
"hailstone_sequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2d62472a7ca44843b44d11238dee84c22af86b4b | e4d824810dbf2d66753a94e7621ea317d805a851 | |||
v1.0 | complete | Data_Structure | Data_Structure_19710_C | from collections import deque
def int_to_bytes_big_endian(num: int) -> bytes:
"""
Converts an integer to its byte representation in big-endian format.
>>> int_to_bytes_big_endian(305419896) b'\\x12\\x34\\x56\\x78'
>>> int_to_bytes_big_endian(0) b'\\x00'
"""
# Your implementation here
pass
... | from collections import deque
def int_to_bytes_big_endian(num: int) -> bytes:
"""
Converts an integer to its byte representation in big-endian format.
"""
if num == 0:
return b'\x00'
result = deque()
while num:
result.appendleft(num & 0xff)
num >>= 8
return bytes(res... | def test_int_to_bytes_big_endian():
assert int_to_bytes_big_endian(305419896) == b'\x12\x34\x56\x78'
assert int_to_bytes_big_endian(0) == b'\x00'
assert int_to_bytes_big_endian(255) == b'\xff'
assert int_to_bytes_big_endian(256) == b'\x01\x00'
def test_int_to_bytes_little_endian():
assert int_to_by... | [
{
"docstring": "Converts an integer to its byte representation in big-endian format.",
"function_declaration": "def int_to_bytes_big_endian(num):",
"function_name": "int_to_bytes_big_endian",
"parameter_list": "(num)"
},
{
"docstring": "Converts an integer to its byte representation in littl... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def int_to_bytes_big_endian(num: int) -> bytes:\n \"\"\"\n Convert an integer to bytes using big-endian format.\n \"\"\"\n if num == 0:\n r... | trial_gpt4o_2 | {
"original_instruction": "You are required to write a function that converts an integer to bytes representation in both big-endian and little-endian formats, and vice versa. Then you must verify that converting from integer to bytes and back to integers yields the original value in both endian formats.\n\n**Objectiv... | 0.566877 | Data_Structure_19710 | C | [
"int_to_bytes_big_endian",
"int_to_bytes_little_endian",
"bytes_big_endian_to_int",
"bytes_little_endian_to_int",
"verify_conversion"
] | 5 | [
[
"verify_conversion",
"bytes_big_endian_to_int"
],
[
"verify_conversion",
"bytes_little_endian_to_int"
],
[
"verify_conversion",
"int_to_bytes_big_endian"
],
[
"verify_conversion",
"int_to_bytes_little_endian"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 60ee1d4b1e2ebc54c3325667f4d0c94636dd7ac3 | 822055c49ab841824f3ebc9b019ef1d57092c9ee | |||
v1.0 | complete | Data_Structure | Data_Structure_20164_C | def reverse_hailstone(n: int) -> list:
""" Generate the Hailstone sequence for a given starting integer n
and return the sequence in reverse order, from 1 to n.
>>> reverse_hailstone(5)
[1, 2, 4, 8, 16, 5]
>>> reverse_hailstone(1)
[1]
""" | def hailstone(n: int) -> list:
sequence = []
while n != 1:
sequence.append(n)
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
sequence.append(1)
return sequence
def reverse_hailstone(n: int) -> list:
sequence = hailstone(n)
return sequence[::-1] | from solution import reverse_hailstone
def test_reverse_hailstone_base_case():
assert reverse_hailstone(1) == [1]
def test_reverse_hailstone_small_number():
assert reverse_hailstone(5) == [1, 2, 4, 8, 16, 5]
def test_reverse_hailstone_large_number():
# Expected sequence for 10: [10, 5, 16, 8, 4, 2, 1]
... | [
{
"docstring": null,
"function_declaration": "def hailstone(n):",
"function_name": "hailstone",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def reverse_hailstone(n):",
"function_name": "reverse_hailstone",
"parameter_list": "(n)"
}
] | [
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def reverse_hailstone(n: int) -> list:\n \"\"\"Generates the reverse Hailstone sequence starting from 1 up to n.\"\"\"\n def hailstone_sequence(n: int) ... | trial_gpt4o_9 | {
"original_instruction": "Generate Reverse Hailstone Sequence\n\n#### Context\nYou are given the task to generate a Hailstone sequence starting from a given number `n`, but as an additional challenge, you must generate and return the sequence in reverse order, starting from 1 and ending at `n`. This requires you to ... | 0.543647 | Data_Structure_20164 | C | [
"hailstone",
"reverse_hailstone"
] | 2 | [
[
"reverse_hailstone",
"hailstone"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | abaece2e82889fc311fb16e5f67b2421841ee2da | 625437fc59df854ebb845c733455553c7dbe7908 | |||
v1.0 | complete | Data_Structure | Data_Structure_19443_C | def insertion_sort(arr):
"""
A utility function to perform insertion sort on the input array.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def optimized_comb_sor... | def insertion_sort(arr):
"""
A utility function to perform insertion sort on the input array.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def optimized_comb_sor... | from solution import optimized_comb_sort
def test_empty_array():
assert optimized_comb_sort([]) == []
def test_single_element_array():
assert optimized_comb_sort([1]) == [1]
def test_sorted_array():
assert optimized_comb_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_array():
assert optim... | [
{
"docstring": "A utility function to perform insertion sort on the input array.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts an array of integers using an optimized version of the Comb Sort algori... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insertion_sort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while j >= 0 and arr[j] > key:\n arr[j... | trial_gpt4o_2 | {
"original_instruction": "Write a function, `optimized_comb_sort`, that sorts an array of integers using an optimized version of the Comb Sort algorithm. The optimization should involve using a different shrink factor and handling small arrays more efficiently.\n\n### Input:\n- An array of integers `arr` of length `... | 0.631815 | Data_Structure_19443 | C | [
"insertion_sort",
"optimized_comb_sort"
] | 2 | [
[
"optimized_comb_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 487b023395f8da16726b453bc7b8d4b295436d75 | ff0865624ff11b4c86392d729914e9b602867c71 | |||
v1.0 | complete | Data_Structure | Data_Structure_19475_C | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool) -> List[int]:
pass
def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
""" Implement radix sort to sort a list of non-negative integers.
If simulation mode is enabled, print each iteration result.
... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool) -> 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... | from solution import radix_sort
def test_radix_sort_example_case():
arr = [170, 45, 75, 90, 802, 24, 2, 66]
sorted_arr = [2, 24, 45, 66, 75, 90, 170, 802]
assert radix_sort(arr) == sorted_arr
def test_radix_sort_with_duplicates():
arr = [3, 6, 3, 1, 9, 6, 3, 2]
sorted_arr = [1, 2, 3, 3, 3, 6, 6, 9... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0... | trial_gpt4o_0 | {
"original_instruction": "### Radix Sort Implementation and Stress Test\n\n#### Objective:\nWrite a function to implement radix sort and apply it to sort a list of non-negative integers. Additionally, enhance the algorithm to handle a large dataset efficiently and ensure it performs within acceptable limits.\n\n####... | 0.643183 | Data_Structure_19475 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fbb2502735322bb404bb9b4d279bc3ba7a04412f | 29f0b0e7438bd8bc3dbce833f2b55f690fd7e080 | |||
v1.0 | complete | Data_Structure | Data_Structure_20027_C | import random
from typing import Tuple
def generate_key(k: int, seed: int = None) -> Tuple[int, int, int]:
"""
Generate RSA public and private keys.
k: The number of bits in n.
seed: An optional seed for repeatable random number generation.
Returns a tuple of three integers (n, e, d) whe... | import random
def gcd(a, b):
while b:
a, b = b, a % b
return a
def multiplicative_inverse(e, phi):
def egcd(a, b):
if a == 0:
return (b, 0, 1)
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
g, x, y = egcd(e, phi)
if g != 1:
raise Except... | from solution import generate_key, encrypt, decrypt
def test_key_generation():
n, e, d = generate_key(16, seed=42)
assert n > 0
assert e > 0
assert d > 0
def test_encryption_decryption():
n, e, d = generate_key(16, seed=42)
data = 12345
encrypted = encrypt(data, e, n)
decrypted = decry... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def multiplicative_inverse(e, phi):",
"function_name": "multiplicative_inverse",
"parameter_list": "(e, phi)"
},
... | [
0,
0,
0,
1,
0,
0,
1,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime\n\ndef generate_key(k: int, seed: int = None) -> tuple:\n if seed is not None:\n random.seed(seed)\n \n ... | trial_gpt4o_7 | {
"original_instruction": "### RSA Key Generation and Encryption\n\n**Objective:**\n\nImplement the RSA encryption algorithm by generating the public and private keys, encrypting a given message with the public key, and then decrypting it with the private key.\n\n**Task:**\n\n1. **Key Generation:**\n Implement an e... | 0.772335 | Data_Structure_20027 | C | [
"gcd",
"multiplicative_inverse",
"is_prime",
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt"
] | 8 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"generate_prime_number"
],
[
"generate_key",
"multiplicative_inverse"
],
[
"generate_prime_number",
"generate_prime_candidate"
],
[
"generate_prime_number",
"is_prime"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 617a8bb7b765e4d1744bc19232271c924c8cba63 | f658d7b672f2ecd7a78845e140c337b96908e97d | |||
v1.0 | complete | Data_Structure | Data_Structure_20414_C | def search_insert(array, val):
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def binary_insertion_sort(array):
""" Sort the given list in ascending ord... | def search_insert(array, val):
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def binary_insertion_sort(array):
for i in range(1, len(array)):
k... | from solution import binary_insertion_sort
def test_empty_array():
array = []
binary_insertion_sort(array)
assert array == []
def test_single_element_array():
array = [1]
binary_insertion_sort(array)
assert array == [1]
def test_sorted_array():
array = [1, 2, 3, 4, 5]
binary_insertion... | [
{
"docstring": null,
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": null,
"function_declaration": "def binary_insertion_sort(array):",
"function_name": "binary_insertion_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": "def search_insert(array, val):\n low = 0\n high = len(array) - 1\n while low <= high:\n mid = low + (high - low) // 2\n if val > array[... | trial_gpt4o_2 | {
"original_instruction": "#### Context:\nYou are tasked with implementing an enhanced Insertion Sort algorithm that uses binary search to locate the insertion point efficiently. This should help in reducing the number of comparisons required to find the correct position for each element in the partially sorted array... | 0.602385 | Data_Structure_20414 | C | [
"search_insert",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dc5e4b32e0bbe0cbbaddba36550a716a21f33f63 | a10f3b18e97c8216a2c737b501384d85aebbc76d | |||
v1.0 | complete | Data_Structure | Data_Structure_20459_C | def secure_key_exchange(p: int, a: int, debug: bool = False) -> int:
""" Employs Diffie-Hellman key exchange protocol to generate a shared secret key between two parties, Alice and Bob.
The function includes steps from prime validation to the final key exchange.
Parameters:
p (int): A large prime n... | def prime_check(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def find_primitive_root(p):
if not prim... | from solution import secure_key_exchange
def test_valid_parameters():
p = 23
a = 5
assert secure_key_exchange(p, a) != "Error: Shared secret key mismatch"
def test_invalid_prime():
p = 22
a = 5
assert secure_key_exchange(p, a) == "Error: 22 is not a prime number"
def test_invalid_primitive_ro... | [
{
"docstring": null,
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def find_primitive_root(p):",
"function_name": "find_primitive_root",
"parameter_list": "(p)"
},
{
... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def prime_check(n):\n 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 ... | trial_gpt4o_0 | {
"original_instruction": "Design a function `secure_key_exchange` that employs Diffie-Hellman key exchange protocol to generate a shared secret key between two parties, Alice and Bob. Your implementation should include all necessary steps from prime validation to the final key exchange. \n\n### Input\n- A large prim... | 0.536443 | Data_Structure_20459 | C | [
"prime_check",
"find_primitive_root",
"secure_key_exchange"
] | 3 | [
[
"find_primitive_root",
"prime_check"
],
[
"secure_key_exchange",
"find_primitive_root"
],
[
"secure_key_exchange",
"prime_check"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 5e953dfe35d0032d13ec189c629d67b557fbd81b | 11b975c9ccb495f356a6120e71903457f2863ec6 | |||
v1.0 | complete | Data_Structure | Data_Structure_19525_C | import random
def is_prime(n, k=40):
""" Return True if n is a probable prime using the Miller-Rabin test. """
...
def generate_prime_candidate(length):
""" Generate an odd integer randomly """
...
def generate_prime_number(length):
""" Return a prime number candidate of the specified length """
... | import random
def is_prime(n, k=40):
""" Return True if n is a probable prime using the Miller-Rabin test. """
if n in (2, 3):
return True
if n % 2 == 0 or n == 1:
return False
# Write (n - 1) as 2^r * d
r, d = 0, n - 1
while d % 2 == 0:
r += 1
d //= 2
... | from solution import generate_key, is_prime
def test_is_prime_small_primes():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(5) == True
assert is_prime(7) == True
def test_is_prime_small_non_primes():
assert is_prime(1) == False
assert is_prime(4) == False
assert is_... | [
{
"docstring": "Return True if n is a probable prime using the Miller-Rabin test. ",
"function_declaration": "def is_prime(n, k=40):",
"function_name": "is_prime",
"parameter_list": "(n, k=40)"
},
{
"docstring": "Generate an odd integer randomly ",
"function_declaration": "def generate_p... | [
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 miller_rabin_primality_test(n, k=40):\n # Helper function to perform the Miller-Rabin primality test\n if n == 2 or n == 3:\n ... | trial_gpt4o_2 | {
"original_instruction": "## Coding Task: Enhanced RSA Key Generation with Optimized Primality Test\n\n### Objective\nImplement an optimized RSA key generation function with improved primality testing using the Miller-Rabin algorithm.\n\n### Scenario\nThe current `generate_key` function can be time-consuming due to ... | 0.587455 | Data_Structure_19525 | C | [
"is_prime",
"generate_prime_candidate",
"generate_prime_number",
"gcd",
"modinv",
"generate_key"
] | 6 | [
[
"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 | 4c9c4258e6eae874e89869681c1d799e0be191bc | 44c7a5fceb89605f4922ef195e8546733a76e5ad | |||
v1.0 | complete | Data_Structure | Data_Structure_20473_C | import re
from collections import deque
def clean_string(s):
"""
Remove non-alphanumeric characters and convert to lowercase.
"""
# Implement this function to clean the input string
pass
def advanced_is_palindrome(s: str, method: str) -> bool:
"""
Check if the given string is a palindrome ... | import re
from collections import deque
def clean_string(s):
"""
Remove non-alphanumeric characters and convert to lowercase.
"""
return re.sub(r'[^A-Za-z0-9]', '', s).lower()
def advanced_is_palindrome(s: str, method: str) -> bool:
"""
Check if the given string is a palindrome using the speci... | from solution import advanced_is_palindrome
def test_advanced_is_palindrome_reverse():
assert advanced_is_palindrome("A man, a plan, a canal: Panama", "reverse") == True
assert advanced_is_palindrome("race a car", "reverse") == False
assert advanced_is_palindrome(" ", "reverse") == True
assert advanced... | [
{
"docstring": "Remove non-alphanumeric characters and convert to lowercase.",
"function_declaration": "def clean_string(s):",
"function_name": "clean_string",
"parameter_list": "(s)"
},
{
"docstring": "Check if the given string is a palindrome using the specified method.",
"function_dec... | [
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 collections\nimport re\n\ndef advanced_is_palindrome(s: str, method: str) -> bool:\n \"\"\"\n :param s: The input string to check.\n :param me... | trial_gpt4o_2 | {
"original_instruction": "### Palindrome Verification Using Various Techniques\n\n#### Context\nYou've been hired to develop a reliable system to validate whether given strings are palindromes. Considering potential variations in the input data, such as the presence of non-alphanumeric characters and different cases... | 0.809943 | Data_Structure_20473 | C | [
"clean_string",
"advanced_is_palindrome"
] | 2 | [
[
"advanced_is_palindrome",
"clean_string"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b45d6f0259c9c851c9dd8cbb17624273c61474e8 | 87fe3d2468239fc055110647d0d24bfd5fac58a7 | |||
v1.0 | complete | Data_Structure | Data_Structure_20204_C | import random
from typing import Tuple
def generate_prime_candidate(length: int) -> int:
""" Generate an odd integer randomly """
p = random.getrandbits(length)
# Ensure p is odd
if p % 2 == 0:
p += 1
return p
def generate_prime_number(length: int) -> int:
""" Generate a prime number o... | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(length):
""" Generate an odd integer randomly """
p = random.getrandbits(length)
# Ensure p is odd
if p % 2 == 0:
p += 1
return p
def generate_prime_number(length):
""" Generate a prime number of length `... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_encrypt_decrypt():
n, e, d = generate_key(16)
data = 42
encrypted = encrypt(data, e, n)
dec... | [
{
"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 `length` ",
"function_declaration": "def gen... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime(bits: int, seed: int = None) -> int:\n if seed is not None:\n random.see... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement RSA Encryption and Decryption\n\nYou are tasked with implementing a simplified version of the RSA encryption algorithm. The goal is to practice the key aspects of RSA, including key generation, encryption, and decryption. You need to create functions for these tasks ... | 0.643968 | Data_Structure_20204 | C | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | e5bd492dce7302c8bdec6c0a1a38e244628c461a | aaa0df84010fff2ee94ffa42cc8db7e377705cbc | |||
v1.0 | complete | Data_Structure | Data_Structure_20595_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
""" Sorts the input list `arr` in ascending order using merge sort algorithm.
The implementation must handle typical edge cases and aim for minimal auxiliary space usage.
Ensure the algorithm is robust and efficient for large datasets.
... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts the input list `arr` in ascending order using merge sort algorithm.
"""
if len(arr) <= 1:
return arr
# Split the array into two halves
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_two_elements_sorted():
assert merge_sort([1, 2]) == [1, 2]
def test_merge_sort_two_elements_unsorted():
assert merge_s... | [
{
"docstring": "Sorts the input list `arr` in ascending order using merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted sublists (`left` and `right`) into one sorted list.",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Function to sort an array using the Merge Sort algorithm.\n \"\"\"... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement an enhanced Merge Sort\n\n#### Objective\nYou are given an array of integers and need to sort it in ascending order using the merge sort algorithm. The implementation should consider typical edge cases and aim for minimal auxiliary space usage.\n\n#### Function Signa... | 0.638783 | Data_Structure_20595 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 72d5ed18964e53c82413ac3e03e7db81f6e2cbb1 | d4b8200a221adb8d0e4b13e5f57a46fa1e13c820 | |||
v1.0 | complete | Data_Structure | Data_Structure_19674_C | def batch_square_root(numbers: list, epsilon: float = 0.001) -> list:
""" Approximates the square roots of a list of positive integers using the Babylonian method.
Ensure that each calculated square root has a maximum absolute error of epsilon.
Args:
numbers (list): List of positive integers to fin... | def babylonian_sqrt(N, epsilon=0.001):
guess = N / 2.0
while True:
next_guess = (guess + N / guess) / 2.0
if abs(next_guess - guess) < epsilon:
return next_guess
guess = next_guess
def batch_square_root(numbers, epsilon=0.001):
return [babylonian_sqrt(num, epsilon) for n... | from solution import batch_square_root, babylonian_sqrt
def test_single_number():
result = batch_square_root([4])
assert len(result) == 1
assert abs(result[0] - 2.0) < 0.001
def test_multiple_numbers():
result = batch_square_root([4, 16, 25, 100])
expected_results = [2.0, 4.0, 5.0, 10.0]
for r... | [
{
"docstring": null,
"function_declaration": "def babylonian_sqrt(N, epsilon=0.001):",
"function_name": "babylonian_sqrt",
"parameter_list": "(N, epsilon=0.001)"
},
{
"docstring": null,
"function_declaration": "def batch_square_root(numbers, epsilon=0.001):",
"function_name": "batch_... | [
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 approximate_square_root(n: int, epsilon: float) -> float:\n \"\"\"\n Approximates the square root of a positive integer n using the Babylonian metho... | trial_gpt4o_2 | {
"original_instruction": "You have been provided with a function that approximates the square root of a positive integer \\( N \\) using the Babylonian method. Your task is to extend this function to handle a list of numbers and return their respective square root approximations, each with a maximum absolute error \... | 0.627126 | Data_Structure_19674 | C | [
"babylonian_sqrt",
"batch_square_root"
] | 2 | [
[
"batch_square_root",
"babylonian_sqrt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0fa0d55b1d10b5140b627cd73394715183fd2f7c | 37e2bb3e054fe46c6bcdad4892d07ac8428152cc | |||
v1.0 | complete | Data_Structure | Data_Structure_20596_C | from typing import List
def improved_sort(arr: List[int]) -> List[int]:
""" Sorts an array of integers in ascending order using an optimized sorting algorithm.
>>> improved_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
>>> improved_sort([10, -1, 3, 7, 8])
[-1, 3, 7,... | from typing import List
def improved_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers in ascending order using the Merge Sort algorithm.
Merge Sort is a divide-and-conquer algorithm that provides an average and worst-case time complexity of O(n log n).
"""
if len(arr) <= 1:
... | from solution import improved_sort
def test_improved_sort_example_1():
assert improved_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
def test_improved_sort_example_2():
assert improved_sort([10, -1, 3, 7, 8]) == [-1, 3, 7, 8, 10]
def test_improved_sort_empty_list():
assert ... | [
{
"docstring": "Sorts an array of integers in ascending order using the Merge Sort algorithm.\n\nMerge Sort is a divide-and-conquer algorithm that provides an average and worst-case time complexity of O(n log n).",
"function_declaration": "def improved_sort(arr):",
"function_name": "improved_sort",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef improved_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of integers in ascending order using the merge sort a... | trial_gpt4o_2 | {
"original_instruction": "Implement a function `improved_sort(arr)` that sorts an array of integers in ascending order. Your task is to enhance the given exchange sort algorithm based on its limitations and performance bottlenecks. You may consider some form of optimization or choose an entirely different sorting al... | 0.707239 | Data_Structure_20596 | C | [
"improved_sort",
"merge"
] | 2 | [
[
"improved_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 01cdd2074ea51059ec1ea678f0f248f95332a6b8 | c39afa00f7e46d6111bc61090f1959e1123c82b8 | |||
v1.0 | complete | Data_Structure | Data_Structure_20415_C | from typing import List
def invert_matrix(m: List[List[float]]) -> List[List[float]]:
"""
Invert a given square matrix of size n x n. Handle edge cases for non-square and singular matrices.
Parameters:
m (List[List[float]]): 2D list representing the matrix to be inverted.
Returns:
List[List[f... | from typing import List
def determinant(matrix: List[List[float]]) -> float:
"""Calculate the determinant of a square matrix."""
if len(matrix) == 1:
return matrix[0][0]
if len(matrix) == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for c in ... | from solution import invert_matrix
def test_invert_simple_matrix():
assert invert_matrix([[1, 2], [3, 4]]) == [[-2.0, 1.0], [1.5, -0.5]]
def test_invert_singular_matrix():
assert invert_matrix([[0, 0], [0, 0]]) == [-2]
def test_invert_non_square_matrix():
assert invert_matrix([[1, 2, 3], [4, 5, 6]]) == [... | [
{
"docstring": "Calculate the determinant of a square matrix.",
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": "Return the Minor of the matrix excluding the i-th row and j-th column.",
"function_declarati... | [
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 get_minor(matrix: List[List[float]], i: int, j: int) -> List[List[float]]:\n minor = [\n [matrix[x][y] for y in range... | trial_gpt4o_1 | {
"original_instruction": "### Matrix Inversion Challenge\n\nYou are required to implement a function to invert a given square matrix. The function should handle matrices of size n x n and account for various edge cases such as non-invertible matrices.\n\n#### Function Signature\n```python\ndef invert_matrix(m: List[... | 0.576747 | Data_Structure_20415 | C | [
"determinant",
"minor",
"transpose",
"cofactor",
"invert_matrix"
] | 5 | [
[
"cofactor",
"determinant"
],
[
"cofactor",
"minor"
],
[
"determinant",
"minor"
],
[
"invert_matrix",
"cofactor"
],
[
"invert_matrix",
"determinant"
],
[
"invert_matrix",
"transpose"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | 96996ab554047df2a0f3a8f4f805c51037c735d1 | 9f4b4fc88487c031081a76049adcd428435b1a19 | |||
v1.0 | complete | Data_Structure | Data_Structure_19626_C | import random
from typing import Dict, List
def next_state(chain: Dict[str, Dict[str, float]], current_state: str) -> str:
"""
Given a Markov-Chain, randomly chooses the next state given the current state.
Handles edge cases where the current state has no defined transitions.
Parameters:
... | import random
def next_state(chain, current_state):
"""
Given a Markov-Chain, randomly chooses the next state given the current state.
Handles edge cases where the current state has no defined transitions.
Parameters:
chain (dict): The Markov Chain represented as a dictionary.
cur... | from solution import next_state, simulate_chain
def test_next_state_valid_transitions():
chain = {
'A': {'B': 0.5, 'C': 0.5},
'B': {'A': 1.0},
'C': {'C': 1.0}
}
assert next_state(chain, 'A') in ['B', 'C']
assert next_state(chain, 'B') == 'A'
assert next_state(chain, 'C') == ... | [
{
"docstring": "Given a Markov-Chain, randomly chooses the next state given the current state.\n\nHandles edge cases where the current state has no defined transitions.\n\nParameters:\n chain (dict): The Markov Chain represented as a dictionary.\n current_state (str): The current state.\n\nReturns:\n 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": "import random\n\ndef __choose_state(next_state_map):\n \"\"\"\n Chooses a state based on the transition probabilities.\n \n Parameters:\n n... | trial_gpt4o_1 | {
"original_instruction": "### Question: Implement and Extend a Markov Chain\n\nGiven the partial implementation of a Markov Chain, complete the following tasks:\n\n1. **`simulate_chain` Function**:\n Write a function `simulate_chain` that simulates the Markov Chain for a given number of steps and returns the seque... | 0.543446 | Data_Structure_19626 | C | [
"next_state",
"__choose_state",
"simulate_chain"
] | 3 | [
[
"next_state",
"__choose_state"
],
[
"simulate_chain",
"next_state"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 775383ae0c1ad98f5ea8d18cab716fa62dfb5576 | 905d551e91df03cbe50af67f0ae892793ce728f5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.