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
instruct
Data_Structure
Data_Structure_2338_I
### Question: Implement Enhanced RSA Encryption Key Generation #### Context: RSA encryption is a fundamental algorithm in modern cryptography. It ensures the secure transmission of data over an insecure network. This question focuses on generating RSA keys with a more efficient prime number testing algorithm and handl...
import random def is_probably_prime(num, k): """ Uses the Miller-Rabin primality test to check if a number is a probable prime. Parameters: num (int): The number to test for primality. k (int): The number of iterations for the Miller-Rabin test (higher k increases the accuracy). Returns: ...
from solution import is_probably_prime, generate_key def test_is_probably_prime_small_primes(): assert is_probably_prime(2, 5) assert is_probably_prime(3, 5) assert is_probably_prime(5, 5) assert is_probably_prime(7, 5) assert is_probably_prime(11, 5) assert is_probably_prime(13, 5) def test_i...
[ { "docstring": "Uses the Miller-Rabin primality test to check if a number is a probable prime.\nParameters:\nnum (int): The number to test for primality.\nk (int): The number of iterations for the Miller-Rabin test (higher k increases the accuracy).\nReturns: \nbool: True if num is probably prime, otherwise Fal...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_probably_prime(num, k):\n \"\"\" \n Uses the Miller-Rabin primality test to check if a number is a probable prime.\n Paramete...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00002338", "row_id": 2338, "seed_ids": "[154]" }
0.530538
Data_Structure_2338
I
[ "is_probably_prime", "generate_key" ]
2
[ [ "generate_key", "is_probably_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
547ac29acbcb3df6b2767179faf9acc0ea89bbe1
0d89054d2df80be8c126949e9e6413c858c322a6
v1.0
instruct
Data_Structure
Data_Structure_2348_I
**Task: Implement an Enhanced Version of Comb Sort** **Objective**: Improve the comb sort algorithm to handle larger arrays more efficiently. Implement an optimized version of comb sort which switches to insertion sort when the gap size becomes small. **Specifications**: * **Function**: `enhanced_comb_sort(arr: List...
from typing import List def insertion_sort(arr: List[int], start: int, end: int) -> None: for i in range(start + 1, end + 1): key = arr[i] j = i - 1 while j >= start and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def enhanced_comb_sort(arr: Li...
from solution import enhanced_comb_sort def test_enhanced_comb_sort_empty(): assert enhanced_comb_sort([]) == [] def test_enhanced_comb_sort_single_element(): assert enhanced_comb_sort([1]) == [1] def test_enhanced_comb_sort_sorted_array(): assert enhanced_comb_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] d...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr, start, end):", "function_name": "insertion_sort", "parameter_list": "(arr, start, end)" }, { "docstring": null, "function_declaration": "def enhanced_comb_sort(arr):", "function_name": "enhanced_comb_sort", "pa...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef insertion_sort(arr: List[int], start: int, end: int):\n \"\"\"\n A helper function that sorts a list using insertion sort...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00002348", "row_id": 2348, "seed_ids": "[21]" }
0.611236
Data_Structure_2348
I
[ "insertion_sort", "enhanced_comb_sort" ]
2
[ [ "enhanced_comb_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f4f007fec7ad997e24aa2d74e344d852e4c57390
9deaa7e613cb9a9b29be59d37632c2eba6757aec
v1.0
instruct
Data_Structure
Data_Structure_2382_I
Implement a Secure Diffie-Hellman Key Exchange You have been given the task to implement a secure key exchange protocol using the Diffie-Hellman algorithm. The objective is to generate a shared secret key between two parties (Alice and Bob) over an unsecured communication channel. ### Requirements 1. **Prime Number ...
import random from math import gcd from sympy import isprime def is_prime(n: int) -> bool: """ Check if a number n is a prime number. Time Complexity: O(sqrt(n)) """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 ...
def test_is_prime(): assert is_prime(2) assert is_prime(3) assert not is_prime(4) assert is_prime(13) assert is_prime(17) assert not is_prime(0) assert not is_prime(1) assert not is_prime(18) assert is_prime(19) def test_find_primitive_root(): assert find_primitive_root(23) in [...
[ { "docstring": "Check if a number n is a prime number.\nTime Complexity: O(sqrt(n))", "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(...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom math import gcd\nfrom sympy import isprime\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Check if a number n is a prime number.\n T...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00002382", "row_id": 2382, "seed_ids": "[146]" }
0.483788
Data_Structure_2382
I
[ "is_prime", "find_primitive_root", "generate_private_key", "generate_public_key", "compute_shared_key", "diffie_hellman_key_exchange" ]
6
[ [ "diffie_hellman_key_exchange", "compute_shared_key" ], [ "diffie_hellman_key_exchange", "generate_private_key" ], [ "diffie_hellman_key_exchange", "generate_public_key" ], [ "find_primitive_root", "is_prime" ] ]
4
[]
false
[]
false
pytest
false
[ "sympy" ]
false
350ac0924be33394f1e172f4f6092ba435f52b18
c785cf0b84104e144474d7c9edc68ff358002ccb
v1.0
instruct
Data_Structure
Data_Structure_2449_I
You are developing a tool that requires the computation of greatest common divisors and least common multiples for pairs of numbers. To ensure robust and efficient implementations, you are asked to: 1. Implement the `gcd` function using the Euclidean algorithm. 2. Implement the `lcm` function leveraging your `gcd` fun...
def gcd(a, b): """ Computes the greatest common divisor of integers a and b using Euclid's Algorithm. """ if not isinstance(a, int) or not isinstance(b, int): raise ValueError("Both a and b must be integers") if a == 0 and b == 0: raise ValueError("Both a and b cannot be zero") ...
from solution import gcd, lcm, gcd_bit import pytest def test_gcd(): assert gcd(48, 18) == 6 assert gcd(0, 18) == 18 assert gcd(48, 0) == 48 assert gcd(-48, 18) == 6 assert gcd(48, -18) == 6 assert gcd(17, 31) == 1 with pytest.raises(ValueError): gcd(0, 0) with pytest.raise...
[ { "docstring": "Computes the greatest common divisor of integers a and b using Euclid's Algorithm.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Computes the least common multiple of integers a and b using gcd function.", ...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def gcd(a, b):\n \"\"\"\n Computes the greatest common divisor of integers a and b using Euclid's Algorithm.\n \"\"\"\n if not isinstance(a, int) ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00002449", "row_id": 2449, "seed_ids": "[166]" }
0.761702
Data_Structure_2449
I
[ "gcd", "lcm", "gcd_bit" ]
3
[ [ "lcm", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
960c57f51ca104c9699cd65e95e0bf3628fe3cfb
2ea81fadb5603d7a5fd5b42599e8f150366fb8f7
v1.0
instruct
Data_Structure
Data_Structure_2505_I
You are given a data structure to manage and manipulate intervals of real numbers. Your task is to enhance its functionality by adding a new method `find_gaps` that identifies gaps between a set of potentially overlapping or adjacent intervals, and an `expand` method that expands each interval by a given amount on both...
from typing import List, Tuple class Interval: def __init__(self, start: int, end: int): self.start = start self.end = end def __repr__(self): return f"Interval ({self.start}, {self.end})" def merge_intervals(intervals: List[Interval]) -> List[Interval]: if not intervals: ...
from solution import Interval, find_gaps, expand def test_find_gaps_no_intervals(): assert find_gaps([]) == [] def test_find_gaps_no_gaps(): intervals = [Interval(1, 5), Interval(5, 10)] assert find_gaps(intervals) == [] def test_find_gaps_with_gaps(): intervals = [Interval(1, 5), Interval(8, 10), In...
[]
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\nclass Interval:\n def __init__(self, start: int, end: int):\n self.start = start\n self.end = end\n\n de...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00002505", "row_id": 2505, "seed_ids": "[285]" }
0.637297
Data_Structure_2505
I
[ "merge_intervals", "find_gaps", "expand" ]
3
[ [ "find_gaps", "merge_intervals" ] ]
1
[]
false
[ "Interval" ]
true
pytest
true
[]
true
13ca2af33fc7bcfe30ce8547ac47819b8a0d4a3c
168d4186ea9a667af94ec98268fa94bcecd7e8e1
v1.0
instruct
Data_Structure
Data_Structure_2510_I
#### Context Alice is learning about number theory and cryptography. She is particularly fascinated by the concept of primitive roots and their importance in cryptographic algorithms. She needs to write a function to identify all the primitive roots of a given positive integer n. However, she encounters performance iss...
def gcd(a, b): while b: a, b = b, a % b return a def is_primitive_root(n, candidate): required_set = {num for num in range(1, n) if gcd(num, n) == 1} actual_set = {pow(candidate, powers, n) for powers in range(1, n)} return required_set == actual_set def find_primitive_root_optimized(n: in...
from solution import find_primitive_root_optimized def test_no_primitive_root(): assert find_primitive_root_optimized(10) == [] def test_small_prime(): assert find_primitive_root_optimized(7) == [3, 5] def test_large_prime(): assert find_primitive_root_optimized(13) == [2, 6, 7, 11] def test_non_prime()...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def is_primitive_root(n, candidate):", "function_name": "is_primitive_root", "parameter_list": "(n, candidate)" }, ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom functools import lru_cache\n\ndef find_primitive_root_optimized(n: int) -> list:\n if n <= 1:\n return []\n\n def gcd(a, b):\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00002510", "row_id": 2510, "seed_ids": "[160]" }
0.531296
Data_Structure_2510
I
[ "gcd", "is_primitive_root", "find_primitive_root_optimized" ]
3
[ [ "is_primitive_root", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
408f111be083e91303c0068766c86be07063ff71
38702e226b026e04f23efeb9d8eca43b7766bc66
v1.0
instruct
Data_Structure
Data_Structure_2531_I
### String Reversal Challenge #### Context: You are given several methods to reverse a string, each demonstrating different concepts of algorithm design and performance characteristics. Your task is to implement a function to reverse a string using at least two distinct methods from the provided ones. #### Task: Impl...
def reverse_string(s: str, method: str) -> str: if method == "recursive": return recursive_reverse(s) elif method == "iterative": return iterative_reverse(s) elif method == "pythonic": return pythonic_reverse(s) elif method == "ultra_pythonic": return ultra_pythonic_rever...
from solution import reverse_string def test_reverse_string_recursive(): assert reverse_string("hello", "recursive") == "olleh" assert reverse_string("world", "recursive") == "dlrow" assert reverse_string("a", "recursive") == "a" def test_reverse_string_iterative(): assert reverse_string("hello", "ite...
[ { "docstring": null, "function_declaration": "def reverse_string(s, method):", "function_name": "reverse_string", "parameter_list": "(s, method)" }, { "docstring": null, "function_declaration": "def recursive_reverse(s):", "function_name": "recursive_reverse", "parameter_list": "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def reverse_string(s, method):\n \"\"\"\n Reverses the input string `s` using the specified `method`.\n \n Parameters:\n s (str): The string to...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00002531", "row_id": 2531, "seed_ids": "[61]" }
0.681688
Data_Structure_2531
I
[ "reverse_string", "recursive_reverse", "iterative_reverse", "pythonic_reverse", "ultra_pythonic_reverse" ]
5
[ [ "reverse_string", "iterative_reverse" ], [ "reverse_string", "pythonic_reverse" ], [ "reverse_string", "recursive_reverse" ], [ "reverse_string", "ultra_pythonic_reverse" ] ]
4
[]
false
[]
false
pytest
true
[]
true
eab5d58f5625409756fd870e80d1b1d618da0d02
2162fc94b16a011c0ed6b76a57ace89073108624
v1.0
instruct
Data_Structure
Data_Structure_2567_I
### Question: Implement AVL Tree Insert Operation with Rebalancing #### Scenario: You are tasked with implementing the insert operation for an AVL tree that automatically maintains balance after any insertion. Your goal is to ensure that the AVL tree remains height-balanced. #### Function Signature: ```python class A...
class Node: def __init__(self, key): self.key = key self.left = None self.right = None self.height = 1 def get_height(node): return node.height if node else 0 def update_height(node): node.height = 1 + max(get_height(node.left), get_height(node.right)) def get_balance(node...
import pytest from solution import AvlTree def test_insert_single_element(): tree = AvlTree() tree.insert(10) assert tree.in_order_traverse() == [10] def test_insert_multiple_elements(): tree = AvlTree() tree.insert(10) tree.insert(20) tree.insert(15) assert tree.in_order_traverse() ==...
[]
[ 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 AvlTree:\n class Node:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00002567", "row_id": 2567, "seed_ids": "[313]" }
0.532839
Data_Structure_2567
I
[ "get_height", "update_height", "get_balance", "right_rotate", "left_rotate", "rebalance" ]
6
[ [ "get_balance", "get_height" ], [ "left_rotate", "update_height" ], [ "rebalance", "get_balance" ], [ "rebalance", "left_rotate" ], [ "rebalance", "right_rotate" ], [ "right_rotate", "update_height" ], [ "update_height", "get_height" ...
7
[]
false
[ "Node", "AvlTree" ]
true
pytest
true
[]
true
fe9238fdddec2b3c949af78f82b3652168b4a01e
a58cf8b5b8a3a7a3eb29c714fa079f013cc3f521
v1.0
instruct
Data_Structure
Data_Structure_2583_I
### RSA Encryption with Enhanced Key Generation #### Problem Statement You are tasked with implementing an RSA encryption system with an improved prime generation algorithm. The existing code uses a simple brute force method, which is inefficient. Your goal is to: 1. Implement an optimized prime generation function u...
import random def is_prime(num, k=5): """ Miller-Rabin primality test. num: Number to test for primality. k: Number of iterations for accuracy. """ if num <= 1 or num == 4: return False if num <= 3: return True # Find d such that d * 2^r = num-1 for some r >= 1 d = num - 1 ...
import pytest from solution import is_prime, gen_prime, generate_key, encrypt, decrypt def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(17) == True assert is_prime(18) == False assert is_prime(19) == True def test_gen_prime(...
[ { "docstring": "Miller-Rabin primality test.\nnum: Number to test for primality.\nk: Number of iterations for accuracy.", "function_declaration": "def is_prime(num, k=5):", "function_name": "is_prime", "parameter_list": "(num, k=5)" }, { "docstring": "Generate a prime number with k bits.\nk:...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_prime(num, k=5):\n \"\"\"\n Returns True if num is a prime number, False otherwise using Miller-Rabin test.\n k is the number...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00002583", "row_id": 2583, "seed_ids": "[154]" }
0.518375
Data_Structure_2583
I
[ "is_prime", "gen_prime", "generate_key", "encrypt", "decrypt" ]
5
[ [ "gen_prime", "is_prime" ], [ "generate_key", "gen_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5e3a3ac9d29d99f0c0946799a7c4a9e75104634e
07950447ce9ff6806c1d5814567276370d6f90bf
v1.0
instruct
Data_Structure
Data_Structure_2594_I
Matrix Inversion Verification **Objective**: Implement a function that verifies the correctness of the matrix inversion algorithm provided in the code snippet by checking the product of the original matrix and its inverted matrix. #### Problem Statement Given a matrix `original_matrix`, implement a function `verify_i...
import numpy as np def invert_matrix(matrix): return np.linalg.inv(matrix) def verify_inversion(original_matrix): """ Verify if the inverse of a matrix is correct. """ # Convert the matrix to numpy array matrix_np = np.array(original_matrix) # Compute the inverse using the given funct...
def test_verify_inversion_simple_2x2(): original_matrix = [ [4, 7], [2, 6] ] assert verify_inversion(original_matrix) == True def test_verify_inversion_another_2x2(): original_matrix = [ [1, 2], [3, 4] ] assert verify_inversion(original_matrix) == True def test_...
[ { "docstring": null, "function_declaration": "def invert_matrix(matrix):", "function_name": "invert_matrix", "parameter_list": "(matrix)" }, { "docstring": "Verify if the inverse of a matrix is correct.", "function_declaration": "def verify_inversion(original_matrix):", "function_nam...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef invert_matrix(matrix):\n \"\"\"\n Computes the inverse of a given square matrix.\n This function assumes that the matrix pr...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00002594", "row_id": 2594, "seed_ids": "[347]" }
0.58944
Data_Structure_2594
I
[ "invert_matrix", "verify_inversion" ]
2
[ [ "verify_inversion", "invert_matrix" ] ]
1
[]
false
[]
false
pytest
false
[ "numpy" ]
false
43ca263ad8cb6166d86a0954926c02e9db59fa6d
a519e94a776137627a72d83891facbc4129a4913
v1.0
instruct
Data_Structure
Data_Structure_2649_I
**Problem Statement**: You are tasked with enhancing and extending a Markov Chain model for a text generation system where each state corresponds to a word, and transitions between states are based on the preceding word in a sentence. Given a dictionary structure of a Markov Chain for a text generation task, create n...
import random def is_valid_chain(chain: dict) -> bool: """ Validates the Markov Chain by ensuring all probability distributions from each state sum to 1 (or nearly 1 due to floating-point precision). """ for state, transitions in chain.items(): if not (0.99 <= sum(transitions.values()) <= 1...
from solution import is_valid_chain, generate_text def test_is_valid_chain(): valid_chain = { 'a': {'b': 0.5, 'c': 0.5}, 'b': {'a': 1.0}, 'c': {'a': 0.7, 'b': 0.3} } invalid_chain = { 'a': {'b': 0.2, 'c': 0.5}, 'b': {'a': 1.1}, 'c': {'a': 0.7, 'b': 0.1} ...
[ { "docstring": "Validates the Markov Chain by ensuring all probability distributions\nfrom each state sum to 1 (or nearly 1 due to floating-point precision).", "function_declaration": "def is_valid_chain(chain):", "function_name": "is_valid_chain", "parameter_list": "(chain)" }, { "docstring...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_valid_chain(chain: dict) -> bool:\n \"\"\"\n Check if the Markov Chain is valid. A valid chain has all \n probability distrib...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00002649", "row_id": 2649, "seed_ids": "[232]" }
0.581665
Data_Structure_2649
I
[ "is_valid_chain", "generate_text", "weighted_choice" ]
3
[ [ "generate_text", "weighted_choice" ] ]
1
[]
false
[]
false
pytest
true
[]
true
513443ebe8c1f7ad45d9b7a3cfdb30f63016af9a
e6324cd9eab4fe17bbf666f651761ebc25aaf4be
v1.0
instruct
Data_Structure
Data_Structure_2693_I
### RSA Encryption Key Generation and Encryption/Decryption Functions **Context**: You will be designing and implementing secure digital communication using the RSA algorithm. The RSA algorithm is widely used for securing sensitive data, especially in internet-based communications. Your task is to implement key compon...
import random from sympy import isprime, mod_inverse def generate_prime_candidate(length): p = random.getrandbits(length) p |= (1 << length - 1) | 1 return p def generate_prime_number(length): p = generate_prime_candidate(length) while not isprime(p): p = generate_prime_candidate(length) ...
from solution import generate_key, encrypt, decrypt def test_key_generation(): n, e, d = generate_key(16, seed=42) assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) def test_encryption_decryption(): n, e, d = generate_key(16, seed=42) data = 42 encrypted_data = ...
[ { "docstring": null, "function_declaration": "def generate_prime_candidate(length):", "function_name": "generate_prime_candidate", "parameter_list": "(length)" }, { "docstring": null, "function_declaration": "def generate_prime_number(length):", "function_name": "generate_prime_numbe...
[ 0, 0, 0, 1, 1, 1, 1, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_key(k: int, seed: int = None) -> (int, int, int):\n if seed is not None:\n ran...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00002693", "row_id": 2693, "seed_ids": "[154]" }
0.675664
Data_Structure_2693
I
[ "generate_prime_candidate", "generate_prime_number", "gcd", "generate_key", "encrypt", "decrypt" ]
6
[ [ "generate_key", "gcd" ], [ "generate_key", "generate_prime_number" ], [ "generate_prime_number", "generate_prime_candidate" ] ]
3
[]
false
[]
false
pytest
true
[ "sympy" ]
false
496160f24b90481c92027589793bd41f6e7f7908
3f14fb827e5deb68a94813dcce7b07a3cf7d2000
v1.0
instruct
Data_Structure
Data_Structure_2737_I
You are tasked to implement a Binary Search Tree (BST) with basic functionalities: insertion, search, and deletion. Additionally, you should implement a function to find the kth smallest element in the BST. ### Requirements 1. **Insertion**: ```python def insert(root: TreeNode, key: int) -> TreeNode: ``` -...
class TreeNode: def __init__(self, key): self.val = key self.left = None self.right = None def insert(root, key): if root is None: return TreeNode(key) else: if key < root.val: root.left = insert(root.left, key) else: root.right = inse...
import pytest from solution import TreeNode, insert, search, delete, kth_smallest def test_insert_and_search(): root = None root = insert(root, 5) root = insert(root, 3) root = insert(root, 7) root = insert(root, 2) root = insert(root, 4) assert search(root, 5) assert search(root, ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, key):\n self.val = key\n self.left = None\n self.right = None\n\ndef insert(root, key):\n if r...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00002737", "row_id": 2737, "seed_ids": "[287]" }
0.526464
Data_Structure_2737
I
[ "insert", "search", "minValueNode", "delete", "inorderTraversal", "kth_smallest" ]
6
[ [ "delete", "minValueNode" ], [ "kth_smallest", "inorderTraversal" ] ]
2
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
4ca2168e941ab878bbb85f539b50679aeb071bfe
4a90f1d6c2fbfd1cd2bbfd962279b20611982228
v1.0
instruct
Data_Structure
Data_Structure_2748_I
Implementing a Robust RSA Key Generator Given your understanding of the RSA encryption algorithm, write a Python program to generate RSA keys (`n`, `e`, `d`), and ensure robust handling of edge cases and performance pitfalls. ### Problem Requirements * Implement a function `generate_rsa_keys(k: int) -> Tuple[int, int...
import random from typing import Tuple def is_prime(num: int, k: int = 5) -> bool: """ Miller-Rabin primality test to check if a number is prime. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0: return False # Write (num - 1) as 2^r * d r,...
from solution import generate_rsa_keys, is_prime, modinv def test_generate_rsa_keys_valid_range(): n, e, d = generate_rsa_keys(32) assert n.bit_length() == 32 assert e == 65537 assert 1 < d < (n - 1) def test_generate_rsa_keys_greater_than_minimum(): n, e, d = generate_rsa_keys(128) assert n.b...
[ { "docstring": "Miller-Rabin primality test to check if a number is prime.", "function_declaration": "def is_prime(num, k=5):", "function_name": "is_prime", "parameter_list": "(num, k=5)" }, { "docstring": "Generate an odd integer randomly.", "function_declaration": "def generate_prime_c...
[ 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 typing import Tuple\n\ndef is_prime(num: int, k: int = 5) -> bool:\n \"\"\"\n Perform Miller-Rabin primality test to check if a numb...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00002748", "row_id": 2748, "seed_ids": "[154]" }
0.58721
Data_Structure_2748
I
[ "is_prime", "generate_prime_candidate", "generate_prime", "gcd", "modinv", "generate_rsa_keys" ]
6
[ [ "generate_prime", "generate_prime_candidate" ], [ "generate_prime", "is_prime" ], [ "generate_rsa_keys", "gcd" ], [ "generate_rsa_keys", "generate_prime" ], [ "generate_rsa_keys", "modinv" ] ]
5
[]
false
[]
false
pytest
true
[]
true
310eab9546497c7dcf19bc302adc337c679530e4
5538690d64fbc7fd3e3615e3828b23c04c74aa1b
v1.0
instruct
Data_Structure
Data_Structure_2757_I
You are provided with a Markov Chain simulation function. A Markov Chain in this context is defined by a dictionary where keys represent states and values are dictionaries that map from the current state to the probabilities of transitioning to other states. Your task is to implement a function that: 1. Validates the...
import random def validate_chain(chain): """ Validate the Markov chain. Args: chain (dict): The Markov chain represented as a dictionary. Returns: bool: True if valid, False otherwise. """ for state, transitions in chain.items(): total_prob = sum(transitions.values()) ...
from solution import validate_chain, simulate_markov_chain def test_validate_chain_valid(): chain = { 'A': {'A': 0.6, 'E': 0.4}, 'E': {'A': 0.7, 'E': 0.3} } assert validate_chain(chain) == True def test_validate_chain_invalid_sum_greater_than_one(): chain = { 'A': {'A': 0.6, 'E...
[ { "docstring": "Validate the Markov chain.\n\nArgs:\nchain (dict): The Markov chain represented as a dictionary.\n\nReturns:\nbool: True if valid, False otherwise.", "function_declaration": "def validate_chain(chain):", "function_name": "validate_chain", "parameter_list": "(chain)" }, { "doc...
[ 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 validate_chain(chain):\n \"\"\"\n Validate the Markov chain.\n \n Args:\n chain (dict): The Markov chain represented as a ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00002757", "row_id": 2757, "seed_ids": "[232]" }
0.477611
Data_Structure_2757
I
[ "validate_chain", "simulate_markov_chain", "_next_state" ]
3
[ [ "simulate_markov_chain", "_next_state" ] ]
1
[]
false
[]
false
pytest
true
[]
true
800201cc553a0309a8712442eaedda10a42b1593
442a33cc418c832cbb1f8353c0f7ec6924004666
v1.0
instruct
Data_Structure
Data_Structure_2763_I
### Maximum Water Flow in a Pipe Network #### Scenario You are given a network of pipes linking various reservoirs. Each pipe has a certain capacity which denotes the maximum amount of water it can transfer per unit time. Your task is to determine the maximum possible amount of water that can flow from the main reserv...
from collections import deque def bfs(rGraph, s, t, parent): visited = [False] * len(rGraph) queue = deque([s]) visited[s] = True while queue: u = queue.popleft() for v, capacity in enumerate(rGraph[u]): if visited[v] == False and capacity > 0: ...
from solution import maximum_water_flow def test_example_case(): pipes = [ [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_water_flow(pipes) == 23 def test_no_path(...
[ { "docstring": null, "function_declaration": "def bfs(rGraph, s, t, parent):", "function_name": "bfs", "parameter_list": "(rGraph, s, t, parent)" }, { "docstring": null, "function_declaration": "def maximum_water_flow(pipes):", "function_name": "maximum_water_flow", "parameter_li...
[ 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_capacity, source, sink, parent):\n n = len(residual_capacity)\n visited = [False] * n\n queue = deq...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00002763", "row_id": 2763, "seed_ids": "[241]" }
0.666829
Data_Structure_2763
I
[ "bfs", "maximum_water_flow" ]
2
[ [ "maximum_water_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
675a1ef20ea70c33142f6c8da630b0ed1c36837a
b63155a9913bf0b7b4006ed89f4afec3aeb3d642
v1.0
instruct
Data_Structure
Data_Structure_2799_I
### Cosine Similarity Implementation **Objective**: Implement a function to calculate the cosine similarity between two one-dimensional lists of numerical data. **Function Signature**: ```python def cosine_similarity(vec1: List[float], vec2: List[float]) -> float: ``` **Input**: * `vec1`: A list of floats, represent...
from typing import List import math def _l2_distance(vec: List[float]) -> float: """ Helper function to calculate the L2 norm (Euclidean norm) of a vector. """ return math.sqrt(sum(x ** 2 for x in vec)) def cosine_similarity(vec1: List[float], vec2: List[float]) -> float: """ Calculate the cos...
from solution import cosine_similarity def test_cosine_similarity_identical_vectors(): assert math.isclose(cosine_similarity([1, 1], [1, 1]), 1.0) def test_cosine_similarity_orthogonal_vectors(): assert math.isclose(cosine_similarity([1, 0], [0, 1]), 0.0) def test_cosine_similarity_opposite_vectors(): as...
[ { "docstring": "Helper function to calculate the L2 norm (Euclidean norm) of a vector.", "function_declaration": "def _l2_distance(vec):", "function_name": "_l2_distance", "parameter_list": "(vec)" }, { "docstring": "Calculate the cosine similarity between two vectors.", "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": "import math\nfrom typing import List\n\ndef _l2_distance(vec: List[float]) -> float:\n \"\"\"\n Computes the L2 norm (Euclidean distance) of a vector.\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00002799", "row_id": 2799, "seed_ids": "[149]" }
0.64061
Data_Structure_2799
I
[ "_l2_distance", "cosine_similarity" ]
2
[ [ "cosine_similarity", "_l2_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
60dd7006c34159deb14380634d82feb9ee3b2ac4
69de73a1fd540eb9ba2792cc387a5c22bf9d0207
v1.0
instruct
Data_Structure
Data_Structure_2845_I
### Coding Assessment: Implement Secure Diffie-Hellman Key Exchange #### Objective This task assesses your understanding of cryptographic techniques, particularly the Diffie-Hellman key exchange algorithm. You need to implement the core components of the algorithm and ensure secure key exchange between two parties. #...
import random def is_prime(num): """ Check if a number is prime. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return False ...
import pytest from solution import is_prime, get_primitive_root, generate_private_key, generate_public_key, generate_shared_secret def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(17) == True assert...
[ { "docstring": "Check if a number is prime. ", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Get the smallest primitive root of a given prime. ", "function_declaration": "def get_primitive_root(prime):", "funct...
[ 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\nimport sympy\n\ndef is_prime(num):\n \"\"\"\n Checks if a given number is prime.\n Utilizes sympy.isprime for efficiency.\n \"\"\"\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00002845", "row_id": 2845, "seed_ids": "[146]" }
0.468442
Data_Structure_2845
I
[ "is_prime", "get_primitive_root", "gcd", "generate_private_key", "generate_public_key", "generate_shared_secret" ]
6
[ [ "get_primitive_root", "gcd" ], [ "get_primitive_root", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5f5f27770d71e12f6d3151360492e07d047fa559
86be475cc930c424cc8f153c8bf812d03e89e1de
v1.0
instruct
Data_Structure
Data_Structure_2885_I
### Secure Communication with Diffie-Hellman Key Exchange You are assigned the task of implementing part of a secure communication protocol based on the Diffie-Hellman key exchange algorithm. Your goal is to write functions that perform the key operations needed for Alice and Bob to securely establish a shared key. #...
import random def is_prime(num: int) -> bool: """ Determines if a number num is prime. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: ...
from solution import is_prime, euler_totient, find_primitive_root, diffie_hellman_key_exchange def test_is_prime(): assert is_prime(2) == True assert is_prime(17) == True assert is_prime(18) == False assert is_prime(97) == True assert is_prime(100) == False def test_euler_totient(): assert eul...
[ { "docstring": "Determines if a number num is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Computes the Euler's Totient function ϕ(n).", "function_declaration": "def euler_totient(n):", "function_name...
[ 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": "import random\nfrom math import gcd\nfrom functools import reduce\n\ndef is_prime(num: int) -> bool:\n \"\"\"\n Check if a number is prime.\n \"\"\"\...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00002885", "row_id": 2885, "seed_ids": "[146]" }
0.5525
Data_Structure_2885
I
[ "is_prime", "euler_totient", "find_primitive_root", "diffie_hellman_key_exchange" ]
4
[ [ "diffie_hellman_key_exchange", "is_prime" ], [ "find_primitive_root", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
339d45e89ad65c6ef0d0607c2291a0274f61329f
784cc5b01d108d2eaa481c28b5faaec06df78aac
v1.0
instruct
Data_Structure
Data_Structure_2906_I
### Coding Challenge You are given a sorted array of integers and a new integer `val` that needs to be inserted into the array. The aim is to maintain the sorted order after the insertion. Write a function `insertion_sort_with_search(array, val)` that returns a new sorted array with `val` inserted in its correct posit...
from typing import List def search_insert(array: List[int], val: int) -> int: """ Helper function to find the index at which val should be inserted to maintain sorted order. """ left, right = 0, len(array) - 1 while left <= right: mid = left + (right - left) // 2 if ar...
from solution import insertion_sort_with_search def test_insert_middle(): assert insertion_sort_with_search([1, 3, 5, 6], 2) == [1, 2, 3, 5, 6] def test_insert_existing(): assert insertion_sort_with_search([1, 3, 5, 6], 5) == [1, 3, 5, 5, 6] def test_insert_end(): assert insertion_sort_with_search([1, 3,...
[ { "docstring": "Helper function to find the index at which val should be inserted to maintain sorted order.", "function_declaration": "def search_insert(array, val):", "function_name": "search_insert", "parameter_list": "(array, val)" }, { "docstring": "Returns a new sorted array with val in...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n This helper function returns the index at which `val` should...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00002906", "row_id": 2906, "seed_ids": "[199]" }
0.632666
Data_Structure_2906
I
[ "search_insert", "insertion_sort_with_search" ]
2
[ [ "insertion_sort_with_search", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
89d239c9b9beca3ba82ab55e1337d943e834b48d
38bed404de5ae0f66ef701ce19ab1999c5080ce6
v1.0
instruct
Data_Structure
Data_Structure_2916_I
### Reversing a String using Different Algorithms #### Problem Statement You are provided with four different methods for reversing a string: recursive, iterative, pythonic, and ultra pythonic. You need to implement the following Python function that takes a string `s` as input and uses all these methods to reverse th...
def reverse_recursive(s: str) -> str: if len(s) == 0: return s else: return s[-1] + reverse_recursive(s[:-1]) def reverse_iterative(s: str) -> str: reversed_s = [] for char in s: reversed_s.insert(0, char) return ''.join(reversed_s) def reverse_pythonic(s: str) -> str: ...
from solution import reverse_string, reverse_recursive, reverse_iterative, reverse_pythonic, reverse_ultra_pythonic def test_reverse_recursive(): assert reverse_recursive("hello") == "olleh" assert reverse_recursive("") == "" assert reverse_recursive("a") == "a" assert reverse_recursive("ab") == "ba" ...
[ { "docstring": null, "function_declaration": "def reverse_recursive(s):", "function_name": "reverse_recursive", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def reverse_iterative(s):", "function_name": "reverse_iterative", "parameter_list": "(s)" }, ...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def reverse_string(s: str) -> dict:\n \"\"\"\n This function takes a string s and returns a dictionary with the reversed string\n obtained by differe...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00002916", "row_id": 2916, "seed_ids": "[61]" }
0.695738
Data_Structure_2916
I
[ "reverse_recursive", "reverse_iterative", "reverse_pythonic", "reverse_ultra_pythonic", "reverse_string" ]
5
[ [ "reverse_string", "reverse_iterative" ], [ "reverse_string", "reverse_pythonic" ], [ "reverse_string", "reverse_recursive" ], [ "reverse_string", "reverse_ultra_pythonic" ] ]
4
[]
false
[]
false
pytest
true
[]
true
d028a0523c8680a2857da70d220d970bc08407b3
345503f790e2e1a9a539f819d1b0d54f65dc7761
v1.0
instruct
Data_Structure
Data_Structure_2921_I
### Euler's Totient Function Advanced Application **Objective**: Implement a function to find the least common multiple (LCM) of all numbers from 1 to `n`, and use Euler's Totient Function within your implementation. **Problem Statement**: Given an integer `n`, write a function `lcm_of_numbers(upto_n: int) -> int` th...
from math import gcd from functools import reduce from sympy.ntheory import totient def lcm(a, b): """ Helper function to compute LCM of two numbers a and b. """ return a * b // gcd(a, b) def lcm_of_numbers(upto_n): """ Compute the least common multiple (LCM) of all integers from 1 to upto_n. ...
from solution import lcm_of_numbers def test_lcm_of_numbers(): assert lcm_of_numbers(1) == 1 assert lcm_of_numbers(2) == 2 assert lcm_of_numbers(3) == 6 assert lcm_of_numbers(4) == 12 assert lcm_of_numbers(5) == 60 assert lcm_of_numbers(6) == 60 assert lcm_of_numbers(7) == 420 assert lc...
[ { "docstring": "Helper function to compute LCM of two numbers a and b.", "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": "Compute the least common multiple (LCM) of all integers from 1 to upto_n.", "function_declaration": "de...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from math import gcd\n\ndef euler_totient(x):\n \"\"\" Computes Euler's Totient Function for x \"\"\"\n result = x\n p = 2\n while p * p <= x:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00002921", "row_id": 2921, "seed_ids": "[141]" }
0.597005
Data_Structure_2921
I
[ "lcm", "lcm_of_numbers" ]
2
[ [ "lcm_of_numbers", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
a5812518eb803ee769cb6b4fe009f6247bf0dfef
c108553775300b5758afa3ba51f549f3f48914a4
v1.0
instruct
Data_Structure
Data_Structure_2970_I
### Scenario You are tasked with developing a simple classification model using the nearest neighbor algorithm. Your function will receive a vector to classify and a labeled training set. The functionality should accurately match the provided vector to its nearest neighbor in the training set using the Euclidean distan...
import math def euclidean_distance(v1, v2): """ Compute the Euclidean distance between two vectors v1 and v2. """ return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2))) def classify_vector(x, tSet): """ Classify the vector x based on the nearest neighbor in the training set tSet. Arg...
from solution import classify_vector def test_basic_case(): x = (2.5, 3.6) tSet = { (1.0, 2.0): 'A', (4.5, 3.2): 'B', (2.5, 4.0): 'C' } assert classify_vector(x, tSet) == 'C' def test_single_point(): x = (1.0, 2.0) tSet = { (1.0, 2.0): 'A' } assert class...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef euclidean_distance(vec1, vec2):\n return math.sqrt(sum((a - b) ** 2 for a, b in zip(vec1, vec2)))\n\ndef classify_vector(x, tSet):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00002970", "row_id": 2970, "seed_ids": "[260]" }
0.643327
Data_Structure_2970
I
[ "euclidean_distance", "classify_vector" ]
2
[ [ "classify_vector", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c703f0f4f976e68096c51a1e7ae6daac962adf54
bc470c2e7720da2c9a3f9f7309216886f2d068e6
v1.0
instruct
Data_Structure
Data_Structure_2983_I
## Linked List Addition with Negatives ### Problem Statement: You are given two linked lists representing two integers. The digits are stored in reverse order and each of their nodes contain a single digit. You need to add the two numbers and return the result as a new linked list. The twist is that the integers can ...
class ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next def linked_list_to_number(node: ListNode) -> int: num = 0 place = 1 while node: num += node.value * place place *= 10 node = node.next return num def number_to_linked...
import pytest from solution import ListNode, add_linked_lists def build_linked_list(nums): head = current = ListNode(nums[0]) for num in nums[1:]: current.next = ListNode(num) current = current.next return head def linked_list_to_str(head): result = [] while head: result.ap...
[]
[ 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": "class ListNode:\n def __init__(self, value=0, next=None):\n self.value = value\n self.next = next\n\ndef to_number(node: ListNode, is_negativ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00002983", "row_id": 2983, "seed_ids": "[248]" }
0.563833
Data_Structure_2983
I
[ "linked_list_to_number", "number_to_linked_list", "add_linked_lists" ]
3
[ [ "add_linked_lists", "linked_list_to_number" ], [ "add_linked_lists", "number_to_linked_list" ] ]
2
[]
false
[ "ListNode" ]
true
pytest
true
[]
true
4212f2e2330097f696b89cba27b8a88091a5d87a
e8ad1d84f0fc2973b08d6efeaeadc0ea61e5769c
v1.0
instruct
Data_Structure
Data_Structure_3025_I
### Coding Exercise: Implement Enhanced Radix Sort #### Context You have been tasked with sorting a large list of non-negative integers efficiently. The existing sorting algorithms are either too slow for large inputs or not well-suited for integers with a variable number of digits. Radix sort, with its digit-centric ...
def enhanced_radix_sort(arr): """ Sorts a list of non-negative integers using Radix Sort. :param arr: List of non-negative integers :return: List of integers sorted in ascending order """ if len(arr) == 0: return arr max_num = max(arr) exp = 1 while max_num...
from solution import enhanced_radix_sort def test_radix_sort_basic(): input_list = [170, 45, 75, 90, 802, 24, 2, 66] assert enhanced_radix_sort(input_list) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_with_duplicates(): input_list = [5, 3, 5, 3, 2, 1, 4, 5, 1] assert enhanced_radix_sort(in...
[ { "docstring": "Sorts a list of non-negative integers using Radix Sort.\n\n:param arr: List of non-negative integers\n:return: List of integers sorted in ascending order", "function_declaration": "def enhanced_radix_sort(arr):", "function_name": "enhanced_radix_sort", "parameter_list": "(arr)" }, ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def counting_sort(arr, exp):\n \"\"\"\n A helper function to perform counting sort based on the exponent value.\n It sorts the array according to the...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003025", "row_id": 3025, "seed_ids": "[15]" }
0.598417
Data_Structure_3025
I
[ "enhanced_radix_sort", "counting_sort" ]
2
[ [ "enhanced_radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c3ac689afb234a3faffda2e4c0c3694063bf7b7f
cec11da01f8f5c9d2911f1124e0edde93af15370
v1.0
instruct
Data_Structure
Data_Structure_3033_I
### Question: Implementation of a Simplified Diffie-Hellman Key Exchange You have been provided with the basis of the Diffie-Hellman key exchange algorithm principles. Your task is to implement a simplified version of the Diffie-Hellman key exchange process by following the guidelines provided. ### Instructions: 1. I...
from sympy import isprime from random import randint def gcd(a, b): while b: a, b = b, a % b return a def is_primitive_root(a, p): if not isprime(p): return False required_set = set(num for num in range(1, p) if gcd(num, p) == 1) actual_set = set(pow(a, powers, p) for powers ...
import pytest from solution import simplified_diffie_hellman_key_exchange def test_simplified_diffie_hellman_key_exchange_valid_case(): assert simplified_diffie_hellman_key_exchange(3, 17) == True def test_invalid_prime(): with pytest.raises(ValueError, match="p is not a prime number."): simplified_di...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def is_primitive_root(a, p):", "function_name": "is_primitive_root", "parameter_list": "(a, p)" }, { "docstri...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_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_1
{ "original_instruction": "", "prompt_id": "00003033", "row_id": 3033, "seed_ids": "[146]" }
0.493211
Data_Structure_3033
I
[ "gcd", "is_primitive_root", "simplified_diffie_hellman_key_exchange" ]
3
[ [ "is_primitive_root", "gcd" ], [ "simplified_diffie_hellman_key_exchange", "is_primitive_root" ] ]
2
[]
false
[]
false
pytest
true
[ "sympy" ]
false
dccbf559af4d722d2ff48830bfb0555a8b8372ce
6ac147d9a8175a04e3bd5b5011dfd69ddd5cfa1d
v1.0
instruct
Data_Structure
Data_Structure_3057_I
## Problem Statement You are given the capacity matrix of a directed graph, along with a source and sink node. The objective is to find the maximum flow from the source to the sink using Dinic's Algorithm. Your task is to implement the Dinic's algorithm as described below to find the maximum flow. ### Dinic's Algorit...
from collections import deque def bfs_capacity_level(capacity, source, sink, level): """ Build a level graph using BFS. """ V = len(capacity) level[:] = [-1] * V level[source] = 0 queue = deque([source]) while queue: u = queue.popleft() for v in range(V): i...
def test_dinic(): capacity = [ [0, 10, 10, 0, 0, 0], [0, 0, 2, 4, 8, 0], [0, 0, 0, 0, 9, 0], [0, 0, 0, 0, 0, 10], [0, 0, 0, 6, 0, 10], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert dinic(capacity, source, sink) == 19 def test_dinic_all_edges_same_ca...
[ { "docstring": "Build a level graph using BFS.", "function_declaration": "def bfs_capacity_level(capacity, source, sink, level):", "function_name": "bfs_capacity_level", "parameter_list": "(capacity, source, sink, level)" }, { "docstring": "Use DFS to find an augmenting path and send flow.",...
[ 0, 0, 0, 0, 1, 0, 0, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef bfs(level, capacity, flow, source, sink):\n level[source] = 0\n queue = deque([source])\n while queue:\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00003057", "row_id": 3057, "seed_ids": "[240]" }
0.539729
Data_Structure_3057
I
[ "bfs_capacity_level", "dfs_capacity_flow", "dinic" ]
3
[ [ "dinic", "bfs_capacity_level" ], [ "dinic", "dfs_capacity_flow" ] ]
2
[]
false
[]
false
pytest
false
[]
true
691bf9f62a2254c9558dd3cc9c4d4c8ec42aa864
fcbbaffaac3c0cd2cb9230ef6f2c10a77c6d0c04
v1.0
instruct
Data_Structure
Data_Structure_3086_I
#### Problem Context Company XYZ is facing a major challenge in ensuring optimal distribution of water through their water supply network. As a solution architect, you are tasked with finding the maximum flow of water from the source to the destination in their supply network. Given a network represented by an n × n ...
from typing import List from collections import deque def bfs(rGraph, s, t, parent): visited = [False] * len(rGraph) queue = deque([s]) visited[s] = True while queue: u = queue.popleft() for ind, val in enumerate(rGraph[u]): if visited[ind] == False and val > 0: ...
from solution import maximum_water_flow def test_example_case(): adjacency_matrix = [ [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_water_flow(adjacency_matrix) ==...
[ { "docstring": null, "function_declaration": "def bfs(rGraph, s, t, parent):", "function_name": "bfs", "parameter_list": "(rGraph, s, t, parent)" }, { "docstring": null, "function_declaration": "def maximum_water_flow(adjacency_matrix):", "function_name": "maximum_water_flow", "p...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(rGraph, s, t, parent):\n visited = [False] * len(rGraph)\n queue = deque([s])\n vis...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00003086", "row_id": 3086, "seed_ids": "[241]" }
0.655202
Data_Structure_3086
I
[ "bfs", "maximum_water_flow" ]
2
[ [ "maximum_water_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c20e823108c9008458e24b805660d6adc51276fc
1af314a1116b89aed06dfb4021745951238448af
v1.0
instruct
Data_Structure
Data_Structure_3100_I
#### Problem Statement You are given an integer that represents a sequence of flags, where each bit indicates the state of a specific feature (1 means "enabled" and 0 means "disabled"). Your task is to implement four functions to manipulate these flags: 1. `get_flag(flags, index)`: Check if the feature at position `i...
def get_flag(flags, index): return (flags & (1 << index)) != 0 def enable_flag(flags, index): return flags | (1 << index) def disable_flag(flags, index): return flags & ~(1 << index) def update_flag(flags, index, state): if state: return enable_flag(flags, index) else: return disa...
from solution import get_flag, enable_flag, disable_flag, update_flag def test_get_flag(): assert get_flag(0b1010, 1) == True assert get_flag(0b1010, 2) == False assert get_flag(0b1010, 3) == True assert get_flag(0b1010, 0) == False def test_enable_flag(): assert enable_flag(0b0000, 1) == 0b0010 ...
[ { "docstring": null, "function_declaration": "def get_flag(flags, index):", "function_name": "get_flag", "parameter_list": "(flags, index)" }, { "docstring": null, "function_declaration": "def enable_flag(flags, index):", "function_name": "enable_flag", "parameter_list": "(flags,...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def get_flag(flags, index):\n \"\"\"\n Check if the feature at position 'index' is enabled.\n \"\"\"\n return (flags & (1 << index)) != 0\n\ndef e...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003100", "row_id": 3100, "seed_ids": "[212]" }
0.542614
Data_Structure_3100
I
[ "get_flag", "enable_flag", "disable_flag", "update_flag" ]
4
[ [ "update_flag", "disable_flag" ], [ "update_flag", "enable_flag" ] ]
2
[]
false
[]
false
pytest
true
[]
true
093985fc6dae8d8ee5eab69529ef9179c793e23d
8ab11eecd6ff88d09e1ee8a828d533372211c449
v1.0
instruct
Data_Structure
Data_Structure_3106_I
#### Context You are tasked with implementing an efficient ordered insertion mechanism into a sorted array. To achieve this, you will use the provided `search_insert` function to find the correct position and then insert the element in that position while maintaining the array order. #### Problem Statement Write a fun...
def search_insert(array, val): """ Binary search function to find the appropriate insert position. """ low, high = 0, len(array) - 1 while low <= high: mid = (low + high) // 2 if array[mid] == val: return mid elif array[mid] < val: low = mid + 1 ...
from solution import ordered_insert def test_ordered_insert_existing_value(): assert ordered_insert([1, 3, 5, 6], 5) == [1, 3, 5, 5, 6] def test_ordered_insert_middle(): assert ordered_insert([1, 3, 5, 6], 2) == [1, 2, 3, 5, 6] def test_ordered_insert_end(): assert ordered_insert([1, 3, 5, 6], 7) == [1, ...
[ { "docstring": "Binary search function to find the appropriate insert position.", "function_declaration": "def search_insert(array, val):", "function_name": "search_insert", "parameter_list": "(array, val)" }, { "docstring": "Inserts val into array such that the resultant array remains sorte...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl", "solution_code": "def search_insert(array, val):\n \"\"\"\n Binary search to find the insertion position for val in a sorted array.\n \"\"\"\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003106", "row_id": 3106, "seed_ids": "[199]" }
0.60495
Data_Structure_3106
I
[ "search_insert", "ordered_insert" ]
2
[ [ "ordered_insert", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2ff09a9174c643a683878d5afb06b705f18b44ab
59c989b24bbcf684df5c08c929bbffce23f6ae1d
v1.0
instruct
Data_Structure
Data_Structure_3110_I
### Nearest Neighbor Algorithm Implementation #### Background You are working on a basic nearest neighbor classifier to predict the class of a given point based on the closest data points in a training set. #### Problem Statement Write a function `nearest_neighbor_classifier(x, train_set)` that takes a point `x` (a ...
import math def euclidean_distance(point1, point2): """ Computes the Euclidean distance between two points. """ return math.sqrt(sum((p1 - p2) ** 2 for p1, p2 in zip(point1, point2))) def nearest_neighbor_classifier(x, train_set): """ Returns the class of the nearest point in the train_set to ...
from solution import nearest_neighbor_classifier def test_simple_case(): x = (1, 2) train_set = { (3, 4): "A", (1, 1): "B", (2, 2): "C" } assert nearest_neighbor_classifier(x, train_set) == "B" def test_single_data_point(): x = (1, 2) train_set = { (3, 4): "A" ...
[]
[ 0, 0, 0, 1, 1, 1, 0, 1, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef euclidean_distance(point1, point2):\n return math.sqrt(sum((a - b) ** 2 for a, b in zip(point1, point2)))\n\ndef nearest_neighbor_classi...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00003110", "row_id": 3110, "seed_ids": "[260]" }
0.672001
Data_Structure_3110
I
[ "euclidean_distance", "nearest_neighbor_classifier" ]
2
[ [ "nearest_neighbor_classifier", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a84f89dd87d5dd89fa28067c044f682e25a86732
6e39a1a972937fefddbf09788160e7b0b4f818e8
v1.0
instruct
Data_Structure
Data_Structure_3120_I
### Scenario You have been hired by a company that specializes in sorting large datasets of numerical information. The company is transitioning from traditional comparison-based sorts to more efficient linear time sorting algorithms and has asked you to implement and optimize Radix Sort for their internal use. They re...
from typing import List def counting_sort(arr: List[int], exp: int) -> List[int]: n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = arr[i] // exp count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] i = n - 1 while i >= 0:...
from solution import custom_radix_sort def test_custom_radix_sort_example_cases(): assert custom_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] assert custom_radix_sort([3, 3, 3, 3, 3]) == [3, 3, 3, 3, 3] assert custom_radix_sort([100, 10, 1000, 1, 10, 100, 1000]) == [1,...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp):", "function_name": "counting_sort", "parameter_list": "(arr, exp)" }, { "docstring": null, "function_declaration": "def custom_radix_sort(arr):", "function_name": "custom_radix_sort", "parameter_list": "(a...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef custom_radix_sort(arr: List[int]) -> List[int]:\n def counting_sort(arr, exp):\n n = len(arr)\n output = [0] *...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003120", "row_id": 3120, "seed_ids": "[15]" }
0.567131
Data_Structure_3120
I
[ "counting_sort", "custom_radix_sort" ]
2
[ [ "custom_radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
737952564172194e24f2c19260e17666167db57a
4b6b0b5ab3f06a4a3eefb3e48c4543a8f0c606a6
v1.0
instruct
Data_Structure
Data_Structure_3135_I
You are given a dataset of points in a multidimensional space represented as (x, y, z, ...). You need to implement the Nearest Neighbor algorithm to classify a new data point based on this dataset. ### Task Write a function `classify_point(new_point, training_set)` that takes the following inputs: 1. `new_point`: A t...
import math def distance(x, y): """Calculates the Euclidean distance between vector x and y.""" assert len(x) == len(y), "The vectors must have the same length" return math.sqrt(sum((xi - yi) ** 2 for xi, yi in zip(x, y))) def classify_point(new_point, training_set): """ Classifies a new point bas...
from solution import classify_point def test_classify_point_typical(): assert classify_point((1.0, 2.0), {(0.0, 1.0): 'A', (2.0, 3.0): 'B', (1.0, 3.0): 'A'}) == 'A' def test_classify_point_typical_2(): assert classify_point((1.5, 2.5), {(1.0, 2.0): 'C', (2.0, 3.0): 'D'}) == 'C' def test_classify_point_edge_c...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef distance(x, y):\n \"\"\"Calculates the Euclidean distance between vector x and y.\"\"\"\n assert len(x) == len(y), \"The vectors must...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003135", "row_id": 3135, "seed_ids": "[260]" }
0.657967
Data_Structure_3135
I
[ "distance", "classify_point" ]
2
[ [ "classify_point", "distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6f1ba02a5dd8d7f62c6e60a8467958b6cc8e7d6e
2b5c55b253ce952a2c354e9da6673e97e4b89a3d
v1.0
instruct
Data_Structure
Data_Structure_3138_I
### Secure Communication System with Diffie-Hellman In this task, you will implement a secure communication using the Diffie-Hellman key exchange algorithm. The algorithm will enable two parties, Alice and Bob, to generate a shared secret key that can be used for encrypting their messages. The parties do not share the...
import random from typing import Tuple def modular_exponentiation(base: int, ex: int, mod: int) -> int: """ Perform modular exponentiation. base^ex % mod """ result = 1 base = base % mod while ex > 0: if (ex % 2) == 1: # If ex is odd, multiply base with the result resul...
from solution import secure_diffie_hellman def test_secure_diffie_hellman_example(): a = 2 p = 23 shared_key_alice, shared_key_bob = secure_diffie_hellman(a, p) assert shared_key_alice == shared_key_bob, "Shared keys do not match!" def test_secure_diffie_hellman_small_prime(): a = 5 p = 19 ...
[ { "docstring": "Perform modular exponentiation.\nbase^ex % mod", "function_declaration": "def modular_exponentiation(base, ex, mod):", "function_name": "modular_exponentiation", "parameter_list": "(base, ex, mod)" }, { "docstring": "Perform Diffie-Hellman key exchange algorithm to generate\n...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import Tuple\nimport random\n\ndef mod_exp(base: int, exp: int, mod: int) -> int:\n \"\"\"\n Modular exponentiation: (base^exp) % mod\n \...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003138", "row_id": 3138, "seed_ids": "[146]" }
0.513072
Data_Structure_3138
I
[ "modular_exponentiation", "secure_diffie_hellman" ]
2
[ [ "secure_diffie_hellman", "modular_exponentiation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ac54fc4b2c3dd90282fe6042d23eaaba84272347
34c7581f64ba1def44c3683fe747b19d8605fb6c
v1.0
instruct
Data_Structure
Data_Structure_3144_I
### Question: #### Context: You are required to implement an optimized version of the Hosoya Triangle, a triangular number arrangement where every element is the sum of the two elements directly above it (if they exist). The first two rows are explicitly defined. - 1 - 1 1 The Hosoya number H(i, j) is defined as: ...
from typing import List def optimized_hosoya_triangle(height: int) -> List[List[int]]: if height == 0: return [[1]] memo = {} def hosoya(i, j): if (i, j) in memo: # Use memoization to avoid recalculating return memo[(i, j)] if (j == 0) and (i in {0, 1}): ...
from solution import optimized_hosoya_triangle, print_optimized_hosoya_triangle def test_optimized_hosoya_triangle_height_0(): assert optimized_hosoya_triangle(0) == [[1]] def test_optimized_hosoya_triangle_height_1(): assert optimized_hosoya_triangle(1) == [[1], [1, 1]] def test_optimized_hosoya_triangle_he...
[ { "docstring": null, "function_declaration": "def optimized_hosoya_triangle(height):", "function_name": "optimized_hosoya_triangle", "parameter_list": "(height)" }, { "docstring": null, "function_declaration": "def print_optimized_hosoya_triangle(height):", "function_name": "print_op...
[ 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 optimized_hosoya_triangle(height: int) -> List[List[int]]:\n if height == 0:\n return [[1]]\n \n memo = {}\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00003144", "row_id": 3144, "seed_ids": "[50]" }
0.553087
Data_Structure_3144
I
[ "optimized_hosoya_triangle", "print_optimized_hosoya_triangle" ]
2
[ [ "print_optimized_hosoya_triangle", "optimized_hosoya_triangle" ] ]
1
[]
false
[]
false
pytest
true
[]
true
36557f343bb5d1cf04714607f15cc4ce03ff82a1
eb9b8e6473fb382c92d5cc362824018249f9ad89
v1.0
instruct
Data_Structure
Data_Structure_3193_I
### Context Imagine you are an urban planner tasked with placing a new facility in a city grid that should be as accessible as possible to all residential buildings. The city grid is given as a 2D matrix where: - `0` represents an empty space, - `1` represents a residential building, and - `2` represents an obstacle an...
from collections import deque from typing import List, Tuple def bfs(grid: List[List[int]], start: Tuple[int, int], distance: List[List[int]], reach_cnt: List[List[int]], num_building: int): rows, cols = len(grid), len(grid[0]) directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] queue = deque([(start[0], ...
from solution import shortest_distance def test_example_1(): grid = [ [1, 0, 2, 0, 1], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0] ] assert shortest_distance(grid) == 7 def test_example_2(): grid = [ [1, 0, 2], [0, 2, 2], [2, 2, 1] ] assert shortest_distanc...
[ { "docstring": null, "function_declaration": "def bfs(grid, start, distance, reach_cnt, num_building):", "function_name": "bfs", "parameter_list": "(grid, start, distance, reach_cnt, num_building)" }, { "docstring": null, "function_declaration": "def shortest_distance(grid):", "funct...
[ 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, Tuple\n\ndef bfs(grid: List[List[int]], start_row: int, start_col: int, distances: List[List[int]], re...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003193", "row_id": 3193, "seed_ids": "[185]" }
0.668396
Data_Structure_3193
I
[ "bfs", "shortest_distance" ]
2
[ [ "shortest_distance", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d3a260cac9ccd41c45965557e464abde7cd215c3
c685bc5b9acd51f46d0d93c692767075d313d2ad
v1.0
instruct
Data_Structure
Data_Structure_3210_I
### Question: Implementing and Optimizing Merge Sort #### Context: You are tasked with implementing a custom sorting function for a large-scale application where stability (maintaining the relative order of records with equal keys) is crucial. The application frequently processes large datasets that do not fit into me...
from typing import List def insertion_sort(arr: List[int], left: int, right: int) -> None: for i in range(left + 1, right + 1): key = arr[i] j = i - 1 while j >= left and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def merge(arr: List[int], lef...
from solution import optimized_merge_sort def test_optimized_merge_sort_empty(): assert optimized_merge_sort([]) == [] def test_optimized_merge_sort_single_element(): assert optimized_merge_sort([1]) == [1] def test_optimized_merge_sort_sorted(): assert optimized_merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, ...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr, left, right):", "function_name": "insertion_sort", "parameter_list": "(arr, left, right)" }, { "docstring": null, "function_declaration": "def merge(arr, left, middle, right):", "function_name": "merge", "param...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef insertion_sort(arr: List[int], left: int, right: int):\n for i in range(left + 1, right + 1):\n key = arr[i]\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003210", "row_id": 3210, "seed_ids": "[12]" }
0.633986
Data_Structure_3210
I
[ "insertion_sort", "merge", "optimized_merge_sort_helper", "optimized_merge_sort" ]
4
[ [ "optimized_merge_sort", "optimized_merge_sort_helper" ], [ "optimized_merge_sort_helper", "insertion_sort" ], [ "optimized_merge_sort_helper", "merge" ] ]
3
[]
false
[]
false
pytest
true
[]
true
3317d506ece12e61f4ac56e2e8f0dab7a21c9c51
57838fac08dc60d30a38c691c307b51f49649350
v1.0
instruct
Data_Structure
Data_Structure_3230_I
### Matrix Inversion Function You are required to implement a `matrix_inverse` function that calculates the inverse of an `n x n` matrix using the principles outlined above. Your implementation should follow these steps: 1. **Matrix of Minors**: Compute the minors for each element. 2. **Cofactor Matrix**: Apply altern...
def matrix_determinant(matrix): """Helper function to compute the determinant of a matrix.""" n = len(matrix) if n == 1: return matrix[0][0] if n == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] determinant = 0 for c in range(n): minor = [[matri...
from solution import matrix_inverse def test_matrix_inverse_2x2(): matrix = [ [4, 7], [2, 6] ] expected = [ [0.6, -0.7], [-0.2, 0.4] ] result = matrix_inverse(matrix) assert result == expected, f"Expected {expected}, but got {result}" def test_matrix_inverse_3x3...
[ { "docstring": "Helper function to compute the determinant of a matrix.", "function_declaration": "def matrix_determinant(matrix):", "function_name": "matrix_determinant", "parameter_list": "(matrix)" }, { "docstring": "Helper function to get the minor of the matrix excluding row i and colum...
[ 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_determinant(matrix):\n \"\"\"Helper function to compute the determinant of a matrix.\"\"\"\n n = len(matrix)\n if n == 1:\n return ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00003230", "row_id": 3230, "seed_ids": "[347]" }
0.588269
Data_Structure_3230
I
[ "matrix_determinant", "get_matrix_minor", "matrix_inverse" ]
3
[ [ "matrix_inverse", "get_matrix_minor" ], [ "matrix_inverse", "matrix_determinant" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5756ec2f32000cb1dd07db998abc9d7c75a7ad84
185ab7a34c0a3d29d6824a62426bf6e31ea87d71
v1.0
instruct
Data_Structure
Data_Structure_3257_I
You have been tasked with writing a custom sorting algorithm based on the principles of Bogo Sort, but with an important twist to make it slightly more practical. Instead of sorting the entire array through shuffling, the algorithm should recursively break down the array into smaller sub-arrays using the Divide and Con...
import random from typing import List def is_sorted(arr: List[int]) -> bool: """ Helper function to check if the array is sorted. """ return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) def recursive_bogo_sort(arr: List[int]) -> List[int]: """ Recursively Bogo Sort the array. """...
from solution import recursive_bogo_sort def test_recursive_bogo_sort_sorted(): assert recursive_bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_recursive_bogo_sort_reverse_sorted(): assert recursive_bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_recursive_bogo_sort_unsorted(): assert recu...
[ { "docstring": "Helper function to check if the array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Recursively Bogo Sort the array.", "function_declaration": "def recursive_bogo_sort(arr):", "fu...
[ 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 typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to check if an array is sorted.\n \"\"\"\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003257", "row_id": 3257, "seed_ids": "[16]" }
0.547899
Data_Structure_3257
I
[ "is_sorted", "recursive_bogo_sort" ]
2
[ [ "recursive_bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5dee85702a7bbfcc850981c8db89fb7f780bc863
dede7e21b18debdf772e75e5ea5b3a6fa898b09a
v1.0
instruct
Data_Structure
Data_Structure_3335_I
### Objective Implement a sorting algorithm based on the principles of randomness. You'll create a sort function that keeps randomly shuffling an array until it is sorted. ### Detailed Problem Statement You are required to implement the `bogoSort` function that sorts an array of integers. Your implementation should ...
from typing import List import random def is_sorted(arr: List[int]) -> bool: """Helper function to check if an array is sorted.""" for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogoSort(arr: List[int], max_iterations: int = 100000) -> List[int]: ...
from solution import bogoSort def test_bogo_sort_sorted_array(): assert bogoSort([1, 2, 3]) == [1, 2, 3] def test_bogo_sort_reverse_array(): result = bogoSort([3, 2, 1]) assert result == [1, 2, 3] def test_bogo_sort_with_duplicates(): result = bogoSort([5, 1, 3, 3, 2]) assert result == so...
[ { "docstring": "Helper function to check if an array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts the array by randomly shuffling it until it is sorted or max_iterations is reached.", "functio...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List, Union\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to check if the array is sorted.\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003335", "row_id": 3335, "seed_ids": "[16]" }
0.648344
Data_Structure_3335
I
[ "is_sorted", "bogoSort" ]
2
[ [ "bogoSort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fa69a3629d344952d722dbf06bb1c27cee021afa
c3568fdc22d669194b7add92941d1ad5aad0e1c4
v1.0
instruct
Data_Structure
Data_Structure_3398_I
### Question: Enhanced Interpolation Search You are tasked with implementing an enhanced version of the interpolation search algorithm that gracefully handles edge cases and optimizes performance for non-uniform distributions. Your implementation should switch to binary search if the formula-based position estimation ...
from typing import List def enhanced_interpolation_search(array: List[int], search_key: int) -> int: """ Enhanced Interpolation Search Algorithm with a fallback mechanism to binary search. :param array: List[int] - The sorted array to be searched. :param search_key: int - The key to be searched in...
from solution import enhanced_interpolation_search def test_search_element_present(): assert enhanced_interpolation_search([10, 20, 30, 40, 50], 30) == 2 assert enhanced_interpolation_search([5, 10, 12, 14, 17, 20, 21], 14) == 3 assert enhanced_interpolation_search([1, 2, 3, 4, 5], 1) == 0 assert enhan...
[ { "docstring": "Enhanced Interpolation Search Algorithm with a fallback mechanism to binary search.\n\n:param array: List[int] - The sorted array to be searched.\n:param search_key: int - The key to be searched in the array.\n:returns: int - Index of search_key in array if found, else -1.", "function_declar...
[ 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 enhanced_interpolation_search(array: List[int], search_key: int) -> int:\n def binary_search(array: List[int], low: int, hig...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003398", "row_id": 3398, "seed_ids": "[192]" }
0.521089
Data_Structure_3398
I
[ "enhanced_interpolation_search", "binary_search" ]
2
[ [ "enhanced_interpolation_search", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
437876566fd314968c8eefbe85d00790b49055f8
319d8a5b2a09ba4cddc698638c5876b07ea011bc
v1.0
instruct
Data_Structure
Data_Structure_3435_I
### Robbing Circular Houses You are a professional robber planning to rob houses along a circular street. Each house has a certain amount of money stashed, and the only constraint stopping you from robbing each of them is that adjacent houses have a security system connected, which will automatically contact the polic...
from typing import List def house_robber(houses: List[int]) -> int: n = len(houses) if n == 0: return 0 if n == 1: return houses[0] dp = [0] * n dp[0] = houses[0] dp[1] = max(houses[0], houses[1]) for i in range(2, n): dp[i] = max(dp[i-1], dp[i-2] + houses[...
from solution import circular_house_robber def test_empty_list(): assert circular_house_robber([]) == 0 def test_single_house(): assert circular_house_robber([5]) == 5 def test_two_houses(): assert circular_house_robber([2, 3]) == 3 def test_three_houses(): assert circular_house_robber([2, 3, 2]) ==...
[ { "docstring": null, "function_declaration": "def house_robber(houses):", "function_name": "house_robber", "parameter_list": "(houses)" }, { "docstring": null, "function_declaration": "def circular_house_robber(houses):", "function_name": "circular_house_robber", "parameter_list"...
[ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef rob_linear(houses: List[int]) -> int:\n \"\"\"\n Solves the house robbery problem for a linear street.\n \"\"\"\n p...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00003435", "row_id": 3435, "seed_ids": "[33]" }
0.570453
Data_Structure_3435
I
[ "house_robber", "circular_house_robber" ]
2
[ [ "circular_house_robber", "house_robber" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8f8ef2f06f3ad2071588dc572235e6e1c9a8c191
4e026906b29b85ec0afd9748c0e2572d467c4c34
v1.0
instruct
Data_Structure
Data_Structure_3501_I
You are given an array of integers and asked to implement an efficient sorting algorithm using a combination of Insertion Sort and Binary Search to reduce the number of comparisons while sorting. Your task is to write a function that sorts the array in ascending order. Your implementation should perform the sorting us...
from typing import List def search_insert(array: List[int], val: int) -> int: """ Helper function using binary search to find the correct position to insert val in array. """ left, right = 0, len(array) while left < right: mid = (left + right) // 2 if array[mid] < val: l...
from solution import binary_insertion_sort def test_empty_array(): assert binary_insertion_sort([]) == [] def test_single_element_array(): assert binary_insertion_sort([1]) == [1] def test_sorted_array(): assert binary_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): ...
[ { "docstring": "Helper function using binary search to find the correct position to insert val in array.", "function_declaration": "def search_insert(array, val):", "function_name": "search_insert", "parameter_list": "(array, val)" }, { "docstring": "Sorts an array using a combination of Ins...
[ 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 search_insert(array: List[int], val: int) -> int:\n \"\"\"\n Perform binary search to find the index to insert `val` in `...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003501", "row_id": 3501, "seed_ids": "[199]" }
0.661113
Data_Structure_3501
I
[ "search_insert", "binary_insertion_sort" ]
2
[ [ "binary_insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5f944b91deb9a99b712f0f1a5339240e1c668fc8
185f977ea395de9388a4ce281dfdb31e6d20d70a
v1.0
instruct
Data_Structure
Data_Structure_3518_I
**Context**: You work for a company that deals with various datasets and requires efficient sorting algorithms. While modern algorithms like quicksort and mergesort are generally preferred due to their better performance on large datasets, certain small or nearly-sorted datasets are still best handled by simpler algori...
from typing import List def search_insert(sorted_part: List[int], value: int) -> int: """ This function finds the position where the 'value' should be inserted in the 'sorted_part' list to keep it sorted. """ for i in range(len(sorted_part)): if value < sorted_part[i]: return i ...
from solution import insertion_sort def test_insertion_sort_empty(): assert insertion_sort([]) == [] def test_insertion_sort_single_element(): assert insertion_sort([1]) == [1] def test_insertion_sort_sorted(): assert insertion_sort([1, 2, 3, 4]) == [1, 2, 3, 4] def test_insertion_sort_reverse(): ...
[ { "docstring": "This function finds the position where the 'value' should be inserted\nin the 'sorted_part' list to keep it sorted.", "function_declaration": "def search_insert(sorted_part, value):", "function_name": "search_insert", "parameter_list": "(sorted_part, value)" }, { "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": "from typing import List\n\ndef insertion_sort(array: List[int]) -> List[int]:\n \"\"\"\n Sorts the input list using the insertion sort algorithm.\n \...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003518", "row_id": 3518, "seed_ids": "[199]" }
0.567151
Data_Structure_3518
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
de1391748324b540879bd5e29fee7acfdf075ef9
ac6769e4ab544482114eb211096867fbddeb63f7
v1.0
instruct
Data_Structure
Data_Structure_3524_I
### Task: Write a function that, given a positive integer `n`, finds all primitive roots of `n`. ### Function Signature: ```python def find_all_primitive_roots(n: int) -> List[int]: ``` ### Input: - `n`: A positive integer (1 ≤ n ≤ 10^4). ### Output: - A list of integers representing all primitive roots of `n`. If n...
from typing import List import math def gcd(a, b): while b: a, b = b, a % b return a def euler_totient(n): amount = 0 for k in range(1, n + 1): if math.gcd(n, k) == 1: amount += 1 return amount def find_all_primitive_roots(n: int) -> List[int]: if n == 1: r...
from solution import find_all_primitive_roots def test_find_all_primitive_roots(): assert find_all_primitive_roots(1) == [0] assert find_all_primitive_roots(2) == [1] assert find_all_primitive_roots(3) == [2] assert find_all_primitive_roots(4) == [] assert find_all_primitive_roots(5) == [2, 3] ...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def euler_totient(n):", "function_name": "euler_totient", "parameter_list": "(n)" }, { "docstring": null, ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nfrom math import gcd\n\ndef euler_totient(n: int) -> int:\n \"\"\"\n Compute Euler's Totient function for a given n\n \"\"\"...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003524", "row_id": 3524, "seed_ids": "[160]" }
0.480527
Data_Structure_3524
I
[ "gcd", "euler_totient", "find_all_primitive_roots" ]
3
[ [ "find_all_primitive_roots", "euler_totient" ] ]
1
[]
false
[]
false
pytest
true
[]
true
096b74793ab63d69d426288795c1b497862fc112
8e8985ad46bf1c3c427b2aec357a25703d976eac
v1.0
instruct
Data_Structure
Data_Structure_3548_I
### Bogo Sort Simulation #### Context Bogo Sort, also known as permutation sort, is an inefficient sorting algorithm that randomly shuffles an array until it finds a sorted permutation. Despite its inefficiency, Bogo Sort can be a useful educational tool for understanding the importance of algorithm efficiency and the...
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, simulation=False): """ Sorts the given list using the Bogo Sort algori...
from solution import bogo_sort_simulation def test_simple_unsorted_array(): assert bogo_sort_simulation([3, 2, 5, 1, 4], simulation=False) == [1, 2, 3, 4, 5] def test_with_simulation(): # This test does not assert the printed result but checks functional behavior assert bogo_sort_simulation([3, 2, 1], sim...
[ { "docstring": "Helper function to check if the array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts the given list using the Bogo Sort algorithm.\n\nParameters:\narr (list[int]): The list of intege...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef bogo_sort_simulation(arr: list[int], simulation: bool=False) -> list[int]:\n \"\"\"\n Sorts the given list using Bogo Sort algorith...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003548", "row_id": 3548, "seed_ids": "[16]" }
0.598085
Data_Structure_3548
I
[ "is_sorted", "bogo_sort_simulation" ]
2
[ [ "bogo_sort_simulation", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
80c8720455b92c12db81062ab1cb66fe2f4779cb
761c208ab64e088ac69b13596f18101be8f4b764
v1.0
instruct
Data_Structure
Data_Structure_3608_I
**Problem Description**: You are required to implement a sorting function using the Radix Sort algorithm. The function must be capable of sorting a list of non-negative integers. The function should additionally support a simulation mode that prints the state of the list after each sorting pass. **Function Signature*...
from typing import List def counting_sort(arr: List[int], exp: int, simulation: bool, iteration: int) -> List[int]: n = len(arr) output = [0] * n # output array to store sorted numbers count = [0] * 10 # count array to store occurrences of digits # Store count of occurrences in the count array ...
from solution import radix_sort def test_radix_sort_with_simulation(): arr = [170, 45, 75, 90, 802, 24, 2, 66] sorted_arr = radix_sort(arr, simulation=True) assert sorted_arr == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_on_empty_list(): assert radix_sort([]) == [] def test_radix_sort_sing...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp, simulation, iteration):", "function_name": "counting_sort", "parameter_list": "(arr, exp, simulation, iteration)" }, { "docstring": null, "function_declaration": "def radix_sort(arr, simulation=False):", "funct...
[ 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 counting_sort(arr: List[int], exp: int, simulation: bool, iteration: int) -> List[int]:\n n = len(arr)\n output = [0] * n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003608", "row_id": 3608, "seed_ids": "[15]" }
0.589549
Data_Structure_3608
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
213e878a6d0845a81947b91a044e5f874280346f
d0d84cfa78f20cef4b4960084526f3bc08bcfdb7
v1.0
instruct
Data_Structure
Data_Structure_3653_I
### Binary Search Tree Operations **Context**: You are tasked with implementing basic operations of a Binary Search Tree (BST). The operations will include inserting a value, deleting a value, and searching for a value in the tree. Additionally, you need to implement a method to retrieve the tree's inorder traversal, ...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def insert(node, val): """Inserts a value into the BST.""" if not node: return TreeNode(val) if val < node.val: node.left = insert(node.left, val)...
from solution import TreeNode, insert, delete, search, inorder_traversal def test_insert(): root = TreeNode(5) insert(root, 3) insert(root, 7) insert(root, 2) insert(root, 4) insert(root, 6) insert(root, 8) assert inorder_traversal(root) == [2, 3, 4, 5, 6, 7, 8] def test_search(): ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef in...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00003653", "row_id": 3653, "seed_ids": "[287]" }
0.570722
Data_Structure_3653
I
[ "insert", "delete", "find_min", "search", "inorder_traversal" ]
5
[ [ "delete", "find_min" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
3fd030860b97525fa61a7138c0b11fc3b4a533d4
b68158ac6e7869846ba36f128aa1e331fa94d85c
v1.0
instruct
Data_Structure
Data_Structure_3672_I
### Matrix Inversion Algorithm #### Problem Statement You have been provided with a Python function `invert_matrix(m)` that inverts an \( n \times n \) matrix. The function follows a four-step process to compute the inverse: 1. Computation of the matrix of minors with an alternate sign pattern. 2. Calculation of the d...
from typing import List, Union def get_cofactor(matrix, i, j): return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])] def determinant_recursive(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] ...
from solution import invert_matrix def test_2x2_matrix(): matrix = [ [4, 7], [2, 6] ] expected_output = [ [0.6, -0.7], [-0.2, 0.4] ] assert invert_matrix(matrix) == expected_output def test_singular_matrix(): matrix = [ [1, 2], [2, 4] ] a...
[ { "docstring": null, "function_declaration": "def get_cofactor(matrix, i, j):", "function_name": "get_cofactor", "parameter_list": "(matrix, i, j)" }, { "docstring": null, "function_declaration": "def determinant_recursive(matrix):", "function_name": "determinant_recursive", "par...
[ 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, Union\n\ndef get_matrix_minor(matrix, i, j):\n return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]\n\ndef get_matr...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003672", "row_id": 3672, "seed_ids": "[347]" }
0.553707
Data_Structure_3672
I
[ "get_cofactor", "determinant_recursive", "adjugate_matrix", "transpose_matrix", "invert_matrix" ]
5
[ [ "adjugate_matrix", "determinant_recursive" ], [ "adjugate_matrix", "get_cofactor" ], [ "adjugate_matrix", "transpose_matrix" ], [ "determinant_recursive", "get_cofactor" ], [ "invert_matrix", "adjugate_matrix" ], [ "invert_matrix", "determinant_r...
6
[]
false
[]
false
pytest
true
[]
true
7c97db0f661976974ae6dc0a83147e881fbf836c
3d1b564b51e3b10a3dde75762540abc6beb1fbce
v1.0
instruct
Data_Structure
Data_Structure_3778_I
### **Heap Sort Implementation and Analysis Task** **Objective**: Implement Heap Sort algorithm using both a max heap and a min heap to sort an array in ascending order. Then, analyze the performance and properties of your implementation. --- **Context**: You are provided with the skeleton of a Heap Sort algorithm ...
def heap_sort(arr): """ This function sorts an array using both max heap and min heap logic. For the purpose of this task, we will implement the max heap logic. Parameters: arr (list): The list of integers to be sorted. Returns: list: The sorted list. """ n = len(arr) ...
from solution import heap_sort def test_heap_sort_simple_case(): assert heap_sort([4, 7, 3, 9, 1]) == [1, 3, 4, 7, 9] def test_heap_sort_already_sorted(): assert heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] assert heap_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_heap_sort_all_equal_elements(): ...
[ { "docstring": "This function sorts an array using both max heap and min heap logic.\nFor the purpose of this task, we will implement the max heap logic.\n\nParameters:\narr (list): The list of integers to be sorted.\n\nReturns:\nlist: The sorted list.", "function_declaration": "def heap_sort(arr):", "f...
[ 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 max_heapify(arr, n, i):\n \"\"\"\n This helper function ensures max heap property for a given node.\n \n Parameters:\n arr (list): The list...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003778", "row_id": 3778, "seed_ids": "[8]" }
0.748426
Data_Structure_3778
I
[ "heap_sort", "max_heapify", "min_heapify" ]
3
[ [ "heap_sort", "max_heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a85a866a9917b4c5e3e208ed64788db2a4f861e6
bd5d52d98a4193ea3f0507df79d0d85c59a40455
v1.0
instruct
Data_Structure
Data_Structure_3804_I
You are assigned the task of developing a software module that implements two different algorithms for solving the Set Cover problem. Your solutions should include: 1. An exact algorithm that finds the minimal cost set cover using exhaustive search. 2. An approximate algorithm that finds a near-optimal cost set cover u...
from itertools import chain, combinations def powerset(iterable): """Helper function to calculate the powerset.""" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) def optimal_set_cover(universe, subsets, costs): min_cost = float('inf') best_cover = None...
from solution import optimal_set_cover, greedy_set_cover def test_optimal_set_cover_basic(): universe = {1, 2, 3, 4, 5} subsets = {'S1': {4, 1, 3}, 'S2': {2, 5}, 'S3': {1, 4, 3, 2}} costs = {'S1': 5, 'S2': 10, 'S3': 3} assert set(optimal_set_cover(universe, subsets, costs)) == {'S3', 'S2'} def test_gr...
[ { "docstring": "Helper function to calculate the powerset.", "function_declaration": "def powerset(iterable):", "function_name": "powerset", "parameter_list": "(iterable)" }, { "docstring": null, "function_declaration": "def optimal_set_cover(universe, subsets, costs):", "function_na...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from itertools import chain, combinations\n\ndef powerset(iterable):\n \"\"\"Helper function to calculate the powerset.\"\"\"\n s = list(iterable)\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00003804", "row_id": 3804, "seed_ids": "[130]" }
0.470129
Data_Structure_3804
I
[ "powerset", "optimal_set_cover", "greedy_set_cover" ]
3
[ [ "optimal_set_cover", "powerset" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ff6b84ea9dfd6c1a90bddd6073e42768b28b3f8a
6fc1ced9c8617a954239f209d7e61f7cbd1b761d
v1.0
instruct
Data_Structure
Data_Structure_3830_I
### Nearest Neighbor Classification Task #### Scenario You are tasked with implementing a simpler form of a classifier which uses the Nearest Neighbor algorithm. This classifier will be used in a small-scale recommendation system. #### Objective Your task is to implement a function `nearest_neighbor(x, tSet)` that ta...
import math def distance(x, y): """ Calculate the Euclidean distance between two n-dimensional points x and y. """ return math.sqrt(sum((a - b) ** 2 for a, b in zip(x, y))) def nearest_neighbor(x, tSet): """ Find the classification of the nearest neighbor to the point x from the set tSet. ...
from solution import distance, nearest_neighbor def test_distance_same_point(): assert distance((1.0, 2.0), (1.0, 2.0)) == 0.0 def test_distance_different_points(): assert distance((1.0, 2.0), (4.0, 6.0)) == 5.0 def test_nearest_neighbor_single_point(): tSet = {(2.0, 3.0): 'A'} assert nearest_neighbo...
[ { "docstring": "Calculate the Euclidean distance between two n-dimensional points x and y.", "function_declaration": "def distance(x, y):", "function_name": "distance", "parameter_list": "(x, y)" }, { "docstring": "Find the classification of the nearest neighbor to the point x from the set t...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef distance(x, y):\n \"\"\"\n Returns the Euclidean distance between points x and y.\n \"\"\"\n return math.sqrt(sum((xi - yi) ** ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003830", "row_id": 3830, "seed_ids": "[260]" }
0.663052
Data_Structure_3830
I
[ "distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
50d927077251ec5b330b6fc00c10c38959e9044e
8d0f8004aa9e4a734a4c24492495ed1451acc6d1
v1.0
instruct
Data_Structure
Data_Structure_3831_I
**Question**: You are given three tasks to implement in Python: 1. Write a function that computes the greatest common divisor (GCD) of two non-negative integers using Euclid's algorithm. The function should handle edge cases such as zero inputs and negative values gracefully by raising an appropriate error. 2. Imple...
def gcd(a: int, b: int) -> int: """ Computes the greatest common divisor of integers a and b using Euclid's Algorithm. :param a: First non-negative integer :param b: Second non-negative integer :return: The greatest common divisor of a and b :raises ValueError: If either input is negative or ze...
import pytest from solution import gcd, lcm, trailing_zero def test_gcd_valid_cases(): assert gcd(48, 18) == 6 assert gcd(54, 24) == 6 assert gcd(101, 10) == 1 def test_gcd_edge_cases(): with pytest.raises(ValueError): gcd(0, 5) with pytest.raises(ValueError): gcd(-2, 4) with p...
[ { "docstring": "Computes the greatest common divisor of integers a and b using Euclid's Algorithm.\n\n:param a: First non-negative integer\n:param b: Second non-negative integer\n:return: The greatest common divisor of a and b\n:raises ValueError: If either input is negative or zero", "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 gcd(a: int, b: int) -> int:\n \"\"\"\n Computes the greatest common divisor of integers a and b using Euclid's Algorithm.\n\n :param a: First non...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003831", "row_id": 3831, "seed_ids": "[166]" }
0.680701
Data_Structure_3831
I
[ "gcd", "lcm", "trailing_zero" ]
3
[ [ "lcm", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
93840e1dfde9c288eb6e22c6e38e07df8676766e
22da9cf8109384007c970ae657a2f57fe7df6cb5
v1.0
instruct
Data_Structure
Data_Structure_3838_I
### Nearest Neighbor Classification Implementation #### Scenario Imagine you are developing a simple recommendation system for a movie streaming service. Each movie's features (e.g., genre, length, rating) are represented as numerical vectors, and given a user's movie preferences, you need to recommend the movie from ...
import math def distance(vec1, vec2): """ Calculates the Euclidean distance between two vectors. Arguments: vec1 {tuple} -- The first vector. vec2 {tuple} -- The second vector. Returns: {float} -- The Euclidean distance between the two vectors. """ return math.sqrt(sum((a ...
from solution import distance, nearest_neighbor, recommend_movie def test_distance(): assert distance((1, 2, 3), (4, 5, 6)) == math.sqrt(27) assert distance((0, 0, 0), (0, 0, 0)) == 0 assert distance((1, 1, 1), (2, 2, 2)) == math.sqrt(3) def test_nearest_neighbor(): user_pref_vector = (3.5, 4.0, 2.5) ...
[ { "docstring": "Calculates the Euclidean distance between two vectors.\n\nArguments:\nvec1 {tuple} -- The first vector.\nvec2 {tuple} -- The second vector.\n\nReturns:\n{float} -- The Euclidean distance between the two vectors.", "function_declaration": "def distance(vec1, vec2):", "function_name": "dis...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef distance(vec1, vec2):\n \"\"\"\n Calculates the Euclidean distance between two vectors.\n \n Arguments:\n vec1 {tuple} -- Th...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00003838", "row_id": 3838, "seed_ids": "[260]" }
0.572902
Data_Structure_3838
I
[ "distance", "nearest_neighbor", "recommend_movie" ]
3
[ [ "nearest_neighbor", "distance" ], [ "recommend_movie", "nearest_neighbor" ] ]
2
[]
false
[]
false
pytest
true
[]
true
344d7273b4ef61aac75a3e89d22919cf16438161
189d6c344324bb1214d11ee27f86ae4e53160bcb
v1.0
instruct
Data_Structure
Data_Structure_3866_I
### Pathfinding in Simple Networks **Problem Description**: You are given a simple transportation network represented as a graph, where intersections are nodes, and roads are edges. Each road has a length of 1 unit. Your task is to write a function to determine the longest path between two intersections in this netwo...
def dfs(graph, node, end, visited, path): visited.add(node) path.append(node) if node == end: yield path[:] else: for neighbor in graph[node]: if neighbor not in visited: yield from dfs(graph, neighbor, end, visited, path) path.pop() visited.remove(n...
from solution import find_longest_path def test_basic_case(): graph = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E'] } assert find_longest_path(graph, 'A', 'F') == ['A', 'B', 'E', 'F'] def test_no_path_...
[ { "docstring": null, "function_declaration": "def dfs(graph, node, end, visited, path):", "function_name": "dfs", "parameter_list": "(graph, node, end, visited, path)" }, { "docstring": null, "function_declaration": "def find_longest_path(graph, start, end):", "function_name": "find_...
[ 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 find_longest_path(graph, start, end):\n def dfs(node, path):\n nonlocal longest_path\n if node == end:\n if len(path) > len(lo...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003866", "row_id": 3866, "seed_ids": "[242]" }
0.650368
Data_Structure_3866
I
[ "dfs", "find_longest_path" ]
2
[ [ "find_longest_path", "dfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3bfaad78f2ce73a826629b24746753d5d566c3db
28232da2e2d8fc9e5ce2a70965356a69aaadeda5
v1.0
instruct
Data_Structure
Data_Structure_3891_I
### String Reversing You are tasked with implementing a function to reverse a given string. You will use one of the following methods of string reversal: recursive, iterative, or slicing. #### Requirements: 1. Implement a function `reverse_string` that takes a string `s` and an optional parameter `method`. 2. `method...
def reverse_string(s, method="iterative"): """ Reverses a given string `s` using the specified method. Parameters: s (str): The string to be reversed. method (str): The method to use for reversing the string - "recursive", "iterative", "pythonic", "ultra_pythonic". Returns: str: Th...
from solution import reverse_string def test_reverse_string_recursive(): assert reverse_string("hello", "recursive") == "olleh" assert reverse_string("world", "recursive") == "dlrow" def test_reverse_string_iterative(): assert reverse_string("python") == "nohtyp" # By default using iterative method a...
[ { "docstring": "Reverses a given string `s` using the specified method.\n\nParameters:\ns (str): The string to be reversed.\nmethod (str): The method to use for reversing the string - \"recursive\", \"iterative\", \"pythonic\", \"ultra_pythonic\".\n\nReturns:\nstr: The reversed string.", "function_declarati...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def reverse_string(s, method=\"iterative\"):\n \"\"\"\n Reverses a given string s using the specified method.\n \n Parameters:\n - s: The strin...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003891", "row_id": 3891, "seed_ids": "[61]" }
0.741931
Data_Structure_3891
I
[ "reverse_string", "_reverse_recursive", "_reverse_iterative" ]
3
[ [ "reverse_string", "_reverse_iterative" ], [ "reverse_string", "_reverse_recursive" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ca05a4308809db28b94a12706cae7703c7db3502
6c47b431e0347ddc77143b72d1017d6e89262032
v1.0
instruct
Data_Structure
Data_Structure_3998_I
**Title**: Optimized Insertion Sort using Binary Search **Scenario**: You are working with a financial application that routinely sorts small lists of transactions. Given the frequency and nature of your dataset, you determine that optimizing the Insertion Sort algorithm—by using Binary Search to determine the correct...
from typing import List def search_insert(array: List[int], val: int) -> int: """ Uses binary search to find the index where `val` should be inserted to keep `array` sorted. """ low, high = 0, len(array) while low < high: mid = (low + high) // 2 if array[mid] < val: ...
from solution import insertion_sort, search_insert def test_insertion_sort_example_1(): assert insertion_sort([4, 2, 6, 1, 3]) == [1, 2, 3, 4, 6] def test_insertion_sort_example_2(): assert insertion_sort([10, 5, 3, 8, 6]) == [3, 5, 6, 8, 10] def test_insertion_sort_empty(): assert insertion_sort([]) == ...
[ { "docstring": "Uses binary search to find the index where `val` should be inserted to keep `array` sorted.", "function_declaration": "def search_insert(array, val):", "function_name": "search_insert", "parameter_list": "(array, val)" }, { "docstring": "Sorts the list of integers using the o...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n A helper function that uses binary search to determine the c...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003998", "row_id": 3998, "seed_ids": "[199]" }
0.551767
Data_Structure_3998
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
030cbae05e33bbbac1ed2851bf2d95666bd3babf
52b9ec3add1990539567f4f9c3809c0a00e3b151
v1.0
instruct
Data_Structure
Data_Structure_4019_I
#### Context You are developing a system that heavily relies on mathematical operations related to integers. As part of this system, you need robust implementations for calculating the greatest common divisor (GCD), the least common multiple (LCM), and counting trailing zeros in the binary representation of numbers. Th...
import math def gcd(a, b): """ Returns the greatest common divisor (GCD) of a and b. """ while b: a, b = b, a % b return abs(a) def lcm(a, b): """ Returns the least common multiple (LCM) of a and b. """ return abs(a * b) // gcd(a, b) def trailing_zero(x): """ Retur...
from solution import gcd, lcm, trailing_zero, gcd_bit def test_gcd(): assert gcd(48, 18) == 6 assert gcd(54, 24) == 6 assert gcd(101, 103) == 1 assert gcd(-48, 18) == 6 assert gcd(0, 5) == 5 assert gcd(5, 0) == 5 def test_lcm(): assert lcm(4, 5) == 20 assert lcm(6, 8) == 24 assert ...
[ { "docstring": "Returns the greatest common divisor (GCD) of a and b.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the least common multiple (LCM) of a and b.", "function_declaration": "def lcm(a, b):", "fun...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def gcd(a, b):\n \"\"\"\n Returns the greatest common divisor of a and b using Euclid's algorithm.\n \"\"\"\n while b:\n a, b = b, a % b\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004019", "row_id": 4019, "seed_ids": "[166]" }
0.613794
Data_Structure_4019
I
[ "gcd", "lcm", "trailing_zero", "gcd_bit" ]
4
[ [ "gcd_bit", "trailing_zero" ], [ "lcm", "gcd" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b72c8efe94f703925c533f2edb3266d32773afd7
19f3a4c97853857155c5dd2285c03a3443b84a23
v1.0
instruct
Data_Structure
Data_Structure_4066_I
You are given an array of integers that need to be sorted in non-decreasing order using an exotic sorting algorithm known as Stooge Sort. ### Function Signature ```python def stoogesort(arr: List[int]) -> None: # Your code here ``` ### Input - An array `arr` of integers, where `1 <= len(arr) <= 500`, and each in...
from typing import List def stoogesort(arr: List[int], l: int, h: int) -> None: """ Sorts an array using the Stooge Sort algorithm recursively. The function modifies the array in place. Parameters: arr (List[int]): The array to be sorted. l (int): The starting index of the array to be sort...
from solution import sort_array def test_sort_array_sample_cases(): arr1 = [2, 4, 5, 3, 1] sort_array(arr1) assert arr1 == [1, 2, 3, 4, 5] arr2 = [7, 3, 8] sort_array(arr2) assert arr2 == [3, 7, 8] def test_sort_array_single_element(): arr = [5] sort_array(arr) assert arr == [...
[ { "docstring": "Sorts an array using the Stooge Sort algorithm recursively.\nThe function modifies the array in place.\n\nParameters:\narr (List[int]): The array to be sorted.\nl (int): The starting index of the array to be sorted.\nh (int): The ending index of the array to be sorted.", "function_declaratio...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef stoogesort(arr: List[int], l: int = 0, h: int = None) -> None:\n \"\"\"\n Sorts the given array arr in non-decreasing ord...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004066", "row_id": 4066, "seed_ids": "[10]" }
0.639419
Data_Structure_4066
I
[ "stoogesort", "sort_array" ]
2
[ [ "sort_array", "stoogesort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a77179e267993eebea5bb6b111b179f2981b46c0
92ff0c06f775e7ac5ea6167a56966bf1a0da77b9
v1.0
instruct
Data_Structure
Data_Structure_4096_I
**Insertion Sort with Binary Search Optimization** You are required to implement a modified version of the Insertion Sort algorithm that uses a binary search to find the correct insertion point of an element. This approach optimizes the searching part of the Insertion Sort but still requires shifting elements. #### P...
from typing import List def search_insert(nums: List[int], x: int, low: int, high: int) -> int: """ A helper function that uses binary search to find the index where x should be inserted in the list nums between indexes low and high. """ while low < high: mid = (low + high) // 2 if ...
def test_insertion_sort_empty(): assert insertion_sort([]) == [] def test_insertion_sort_single_element(): assert insertion_sort([1]) == [1] def test_insertion_sort_two_elements(): assert insertion_sort([2, 1]) == [1, 2] def test_insertion_sort_multiple_elements(): assert insertion_sort([4, 2, 7, 1, ...
[ { "docstring": "A helper function that uses binary search to find the index where x should be inserted\nin the list nums between indexes low and high.", "function_declaration": "def search_insert(nums, x, low, high):", "function_name": "search_insert", "parameter_list": "(nums, x, low, high)" }, ...
[ 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 search_insert(arr: List[int], left: int, right: int, target: int) -> int:\n \"\"\"\n Uses binary search to find the index...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004096", "row_id": 4096, "seed_ids": "[199]" }
0.584657
Data_Structure_4096
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
false
[]
true
a65ad1629a99174047268633e6e87bdf14efdacb
b59fc04fbd1a07af58ccf4e1e62406f895d6d262
v1.0
instruct
Data_Structure
Data_Structure_4132_I
### Context The given code implements the Quick Sort algorithm, a popular and efficient sorting algorithm under average case scenarios. Your task is to further enhance and adapt the Quick Sort implementation to address some common pitfalls and optimize its performance to handle large datasets effectively. ### Problem ...
from typing import List def median_of_three(a, b, c): """Return the median of the three elements.""" return sorted([a, b, c])[1] def partition(arr, low, high): """ Partition the array using the median-of-three method to choose the pivot. """ mid = (low + high) // 2 pivot = median_of_three(...
from solution import optimized_quick_sort def test_small_array(): arr = [3, 1, 2] k = 2 assert optimized_quick_sort(arr, k) == [1, 2, 3] def test_large_array(): arr = [5, 2, 9, 1, 5, 6, 8, 7, -3, -2] k = 3 assert optimized_quick_sort(arr, k) == [-3, -2, 1, 2, 5, 5, 6, 7, 8, 9] def test_edge_c...
[ { "docstring": "Return the median of the three elements.", "function_declaration": "def median_of_three(a, b, c):", "function_name": "median_of_three", "parameter_list": "(a, b, c)" }, { "docstring": "Partition the array using the median-of-three method to choose the pivot.", "function_d...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef median_of_three(a, b, c):\n \"\"\"Return the median of the three elements.\"\"\"\n return sorted([a, b, c])[1]\n\ndef par...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004132", "row_id": 4132, "seed_ids": "[25]" }
0.531632
Data_Structure_4132
I
[ "median_of_three", "partition", "insertion_sort", "optimized_quick_sort" ]
4
[ [ "optimized_quick_sort", "insertion_sort" ], [ "optimized_quick_sort", "partition" ], [ "partition", "median_of_three" ] ]
3
[]
false
[]
false
pytest
true
[]
true
72721f7f4ec88586eda16533cee0f872f1239e24
7b1efad2e9e5a8599881b311c5a9bcaff1ca0040
v1.0
instruct
Data_Structure
Data_Structure_4155_I
#### Hamming Weight Calculation with Extended Functionality You are given two functions `count_ones_recur(n)` and `count_ones_iter(n)` that use Brian Kernighan's Algorithm to count '1' bits in a binary representation of an unsigned integer. Your task is to implement a new function `count_ones_list(lst)` that, given a...
from typing import List def count_ones_recur(n: int) -> int: """ Counts the number of '1' bits in the binary representation of an integer using recursion and Brian Kernighan's Algorithm. This is for demonstration purposes and won't be used in the final implementation. """ if n == 0: ...
from solution import count_ones_recur, count_ones_iter, count_ones_list def test_count_ones_recur(): assert count_ones_recur(0) == 0 assert count_ones_recur(3) == 2 assert count_ones_recur(5) == 2 assert count_ones_recur(11) == 3 assert count_ones_recur(8) == 1 assert count_ones_recur(15) == 4 ...
[ { "docstring": "Counts the number of '1' bits in the binary representation of an integer using recursion and\nBrian Kernighan's Algorithm.\n\nThis is for demonstration purposes and won't be used in the final implementation.", "function_declaration": "def count_ones_recur(n):", "function_name": "count_on...
[ 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 count_ones_iter(n: int) -> int:\n \"\"\"\n Count the number of '1' bits in the binary representation of an integer using\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004155", "row_id": 4155, "seed_ids": "[218]" }
0.653372
Data_Structure_4155
I
[ "count_ones_recur", "count_ones_iter", "count_ones_list" ]
3
[ [ "count_ones_list", "count_ones_iter" ] ]
1
[]
false
[]
false
pytest
true
[]
true
96adee8ed833858c426a63ecb034e6c79ba2d0ab
0cda5d2c00c4b0f414a5c3856c89eac1b97614f3
v1.0
instruct
Data_Structure
Data_Structure_4170_I
### RSA Encryption and Decryption (Advanced) You are tasked to implement a secure communication channel using the RSA encryption algorithm. This requires generating keys (public and private), encrypting a message, and then decrypting it. **Function Specifications**: 1. **generate_key(k: int, seed: int = None) -> Tupl...
import random from sympy import isprime, mod_inverse def generate_prime_number(bit_length): while True: num = random.getrandbits(bit_length) if isprime(num): return num def generate_key(k: int, seed: int = None): if k % 4 != 0: raise ValueError("Bit length k must be a multi...
import pytest 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) assert e == 65537 def test_encrypt_decrypt(): n, e, d = generate_key(16, seed=42) dat...
[ { "docstring": null, "function_declaration": "def generate_prime_number(bit_length):", "function_name": "generate_prime_number", "parameter_list": "(bit_length)" }, { "docstring": null, "function_declaration": "def generate_key(k, seed=None):", "function_name": "generate_key", "p...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime_number(bit_length):\n while True:\n num = random.getrandbits(bit_length)...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004170", "row_id": 4170, "seed_ids": "[154]" }
0.58118
Data_Structure_4170
I
[ "generate_prime_number", "generate_key", "encrypt", "decrypt" ]
4
[ [ "generate_key", "generate_prime_number" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
7e09c394053b62f3d30a3db82b6ec43a36147b69
cde976d1950a18a4564477c160125b3ffd97267c
v1.0
instruct
Data_Structure
Data_Structure_4271_I
Secure Encrypted Message Exchange #### Objective Based on the Diffie-Hellman key exchange algorithm provided, your task is to implement a secure message exchange between Alice and Bob. They will use the shared secret key generated from the key exchange to encrypt and decrypt messages using a simple substitution cipher...
def encrypt_message(message, key): """ Encrypts the message using the shared key. """ encrypted_message = ''.join(chr((ord(char) + key - 32) % 95 + 32) for char in message) return encrypted_message def decrypt_message(encrypted_message, key): """ Decrypts the message using the shared key. """ decry...
from solution import encrypt_message, decrypt_message, secure_message_exchange def test_encrypt_decrypt(): message = "HELLO WORLD" key = 3 encrypted_message = encrypt_message(message, key) decrypted_message = decrypt_message(encrypted_message, key) assert message == decrypted_message def test_secu...
[ { "docstring": "Encrypts the message using the shared key. ", "function_declaration": "def encrypt_message(message, key):", "function_name": "encrypt_message", "parameter_list": "(message, key)" }, { "docstring": "Decrypts the message using the shared key. ", "function_declaration": "def...
[ 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 encrypt_message(message, key):\n \"\"\" Encrypts the message using the shared key. \"\"\"\n encrypted_message = ''.join(chr(((ord(c...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004271", "row_id": 4271, "seed_ids": "[146]" }
0.478985
Data_Structure_4271
I
[ "encrypt_message", "decrypt_message", "diffie_hellman_key_exchange", "secure_message_exchange" ]
4
[ [ "secure_message_exchange", "decrypt_message" ], [ "secure_message_exchange", "diffie_hellman_key_exchange" ], [ "secure_message_exchange", "encrypt_message" ] ]
3
[]
false
[]
false
pytest
true
[]
true
362df1a6ad5330bf3a63abbe66a0d1abd5e2789f
73af8012e80ca42c9a907a4b01499597a06daa56
v1.0
instruct
Data_Structure
Data_Structure_4273_I
**Task**: Write a Python function that sorts an array using the Bogo Sort algorithm. However, given the impracticality of Bogo Sort, your task is to modernize this algorithm slightly by implementing a "Bogo-Simulation Sort" that: - Continues shuffling if the array is unsorted. - Stops if a specified maximum number of i...
import random def is_sorted(arr): """ Helper function to check if the array is sorted. """ return all(arr[i] <= arr[i+1] for i in range(len(arr)-1)) def bogo_simulation_sort(arr, max_iterations): """ Bogo-Simulation Sort that shuffles the array until it's sorted or reaches the maximum number o...
from solution import bogo_simulation_sort def test_bogo_simulation_sort_sorted_array(): arr = [1, 2, 3, 4, 5] max_iterations = 1000 sorted_arr = bogo_simulation_sort(arr, max_iterations) assert sorted_arr == [1, 2, 3, 4, 5] def test_bogo_simulation_sort_reverse_array(): arr = [5, 4, 3, 2, 1] m...
[ { "docstring": "Helper function to check if the array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Bogo-Simulation Sort that shuffles the array until it's sorted or reaches the maximum number of iterati...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef bogo_simulation_sort(arr, max_iterations):\n def is_sorted(arr):\n return all(arr[i] <= arr[i+1] for i in range(len(arr) - 1))\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004273", "row_id": 4273, "seed_ids": "[16]" }
0.530492
Data_Structure_4273
I
[ "is_sorted", "bogo_simulation_sort" ]
2
[ [ "bogo_simulation_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1aa111cc4df6f2b5b7af612d7fb520adbfb0bd68
8ab77a359be8cdc6330983ba17227438d2e8eba6
v1.0
instruct
Data_Structure
Data_Structure_4342_I
You are tasked with extending the functionality of a Markov chain. Specifically, you need to implement a function that generates a finite sequence of states given an initial state and a predefined number of transitions. ### Requirements * Implement a function `generate_markov_sequence(chain, initial_state, transitions...
import random def __choose_state(prob_dist): """ Helper function to choose the next state based on a probability distribution. """ states = list(prob_dist.keys()) probabilities = list(prob_dist.values()) return random.choices(states, probabilities)[0] def generate_markov_sequence(chain, initia...
from solution import generate_markov_sequence def test_generate_sequence_basic_case(): chain = { 'A': {'A': 0.6, 'E': 0.4}, 'E': {'A': 0.7, 'E': 0.3} } initial_state = 'A' transitions = 5 sequence = generate_markov_sequence(chain, initial_state, transitions) assert len(sequence...
[ { "docstring": "Helper function to choose the next state based on a probability distribution.", "function_declaration": "def __choose_state(prob_dist):", "function_name": "__choose_state", "parameter_list": "(prob_dist)" }, { "docstring": "Generates a sequence of states given a Markov chain,...
[ 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 generate_markov_sequence(chain, initial_state, transitions):\n \"\"\"\n Generates a sequence of states based on the given Markov ch...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004342", "row_id": 4342, "seed_ids": "[232]" }
0.490831
Data_Structure_4342
I
[ "__choose_state", "generate_markov_sequence" ]
2
[ [ "generate_markov_sequence", "__choose_state" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a59bb6e6b6a9e6346f112e9e6107f0a190d702f0
d86e0b35c2eaf53cfa792666bd1575b65a8c94e4
v1.0
instruct
Data_Structure
Data_Structure_4344_I
Power of Two Array Check #### Context Given the need to frequently verify whether elements in an array are powers of two, it's essential to extend the individual power-of-two check to work on arrays efficiently. #### Objective Write a function `power_of_twos(arr)` that, given an array of integers, returns a list of b...
from typing import List def is_power_of_two(n: int) -> bool: """ Check if a given integer is a power of two. :param n: int - Integer to check. :return: bool - Whether the integer is a power of two. """ if n <= 0: return False return (n & (n - 1)) == 0 def power_of_twos(arr: List[i...
from solution import power_of_twos def test_power_of_twos_with_mixed_input(): assert power_of_twos([1, 2, 3, 4, 5]) == [True, True, False, True, False] def test_power_of_twos_with_only_powers_of_two(): assert power_of_twos([16, 32, 64, 128, 256]) == [True, True, True, True, True] def test_power_of_tw...
[ { "docstring": "Check if a given integer is a power of two.\n\n:param n: int - Integer to check.\n:return: bool - Whether the integer is a power of two.", "function_declaration": "def is_power_of_two(n):", "function_name": "is_power_of_two", "parameter_list": "(n)" }, { "docstring": "Determi...
[ 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 power_of_twos(arr: List[int]) -> List[bool]:\n \"\"\"\n Determine if each integer in the array is a power of two.\n\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004344", "row_id": 4344, "seed_ids": "[215]" }
0.60101
Data_Structure_4344
I
[ "is_power_of_two", "power_of_twos" ]
2
[ [ "power_of_twos", "is_power_of_two" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b747f0aded03c509cf4710857002ab085a1e31c1
03f66895678e17ca3e747277cdf793398c9816c6
v1.0
instruct
Data_Structure
Data_Structure_4379_I
You are given two arrays, `preorder` and `postorder`, of integers representing the preorder and postorder traversal of a full binary tree respectively. Your task is to reconstruct the binary tree and return its inorder traversal. ### Function Signature ```python def inorder_from_pre_post(preorder: List[int], postorder...
from typing import List class TreeNode: def __init__(self, value=0): self.value = value self.left = None self.right = None def build_tree_from_pre_post(preorder: List[int], postorder: List[int]) -> TreeNode: if not preorder or not postorder: return None root = TreeNode(pre...
from solution import inorder_from_pre_post def test_inorder_from_pre_post_case1(): preorder = [1, 2, 4, 5, 3, 6, 7] postorder = [4, 5, 2, 6, 7, 3, 1] expected = [4, 2, 5, 1, 6, 3, 7] assert inorder_from_pre_post(preorder, postorder) == expected def test_inorder_from_pre_post_case2(): preorder = [2...
[]
[ 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\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\ndef c...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004379", "row_id": 4379, "seed_ids": "[300]" }
0.561095
Data_Structure_4379
I
[ "build_tree_from_pre_post", "inorder_traversal", "inorder_from_pre_post" ]
3
[ [ "inorder_from_pre_post", "build_tree_from_pre_post" ], [ "inorder_from_pre_post", "inorder_traversal" ] ]
2
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
40158469c677674165910a7bd8a12a2509f2b9fb
dca52a100d25027f148b4adc40744f87c47b53af
v1.0
instruct
Data_Structure
Data_Structure_4402_I
#### Background Scenario You are part of a team developing a high-frequency trading application where actions must be taken on financial markets in real-time. Given a series of trades occurring in real-time, it's crucial to maintain a sorted list of trade values to ensure the accuracy of trend analysis and decision-ma...
def insertion_sort(arr): """ Perform an insertion sort on the list `arr`. """ 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 optimized_bucket_sort(a...
from solution import optimized_bucket_sort def test_optimized_bucket_sort_sorted_input(): assert optimized_bucket_sort([0.1, 0.2, 0.3, 0.4, 0.5]) == [0.1, 0.2, 0.3, 0.4, 0.5] def test_optimized_bucket_sort_reverse_sorted(): assert optimized_bucket_sort([0.5, 0.4, 0.3, 0.2, 0.1]) == [0.1, 0.2, 0.3, 0.4, 0.5] ...
[ { "docstring": "Perform an insertion sort on the list `arr`.", "function_declaration": "def insertion_sort(arr):", "function_name": "insertion_sort", "parameter_list": "(arr)" }, { "docstring": "Sorts a list of floating-point numbers in the range [0, 1) using the\nBucket Sort algorithm.", ...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def insertion_sort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while j >= 0 and key < arr[j]:\n arr[j...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004402", "row_id": 4402, "seed_ids": "[26]" }
0.507242
Data_Structure_4402
I
[ "insertion_sort", "optimized_bucket_sort" ]
2
[ [ "optimized_bucket_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d32d60d0a325e86aba49f33dbd1751d47fbf550a
30fbac7bd819a68cc48cf0e7cca031bef31abf74
v1.0
instruct
Data_Structure
Data_Structure_4457_I
### Insertion Sort Implementation using Binary Search **Challenge:** Implement an optimized version of the insertion sort algorithm using a helper function `search_insert` described below. Given an unsorted list of integers, sort the list in ascending order. **Function Signature:** ```python def insertion_sort(array:...
from typing import List def search_insert(array, val): """ Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. """ low = 0 high = len(array) - 1 while low <= high: mid = low + (hig...
from solution import insertion_sort def test_insertion_sort_basic(): assert insertion_sort([6, 3, 7, 1, 5]) == [1, 3, 5, 6, 7] def test_insertion_sort_empty(): assert insertion_sort([]) == [] def test_insertion_sort_single_element(): assert insertion_sort([1]) == [1] def test_insertion_sort_sorted_list(...
[ { "docstring": "Given a sorted array and a target value, return the index if the target is\nfound. If not, return the index where it would be if it were inserted in order.", "function_declaration": "def search_insert(array, val):", "function_name": "search_insert", "parameter_list": "(array, val)" ...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n Given a sorted array and a target value, return the index if...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004457", "row_id": 4457, "seed_ids": "[199]" }
0.57811
Data_Structure_4457
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3b5dd8ef78ea133d875bd589828e75544a692faa
df0ecad37467c3f58822393683d3d1e1849f5462
v1.0
instruct
Data_Structure
Data_Structure_4471_I
### Insertion Sort with Binary Search You are required to implement the insertion sort algorithm utilizing the binary search method provided in the `search_insert` function. The goal is to efficiently sort an array of integers by inserting each new element at its correct position within the sorted portion of the array...
from typing import List def search_insert(array: List[int], value: int, start: int, end: int) -> int: """ Perform binary search to find the index at which the value should be inserted to keep the sorted order. """ while start < end: mid = (start + end) // 2 if array[mid] < value: ...
from solution import insertion_sort_with_binary_search def test_insertion_sort_example(): assert insertion_sort_with_binary_search([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12] def test_insertion_sort_with_negative_numbers(): assert insertion_sort_with_binary_search([-1, -3, -2, -10, 0]) == [-10, ...
[ { "docstring": "Perform binary search to find the index at which the value should be inserted\nto keep the sorted order.", "function_declaration": "def search_insert(array, value, start, end):", "function_name": "search_insert", "parameter_list": "(array, value, start, end)" }, { "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": "from typing import List\n\ndef binary_search(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Helper function to find the index to ins...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004471", "row_id": 4471, "seed_ids": "[199]" }
0.609555
Data_Structure_4471
I
[ "search_insert", "insertion_sort_with_binary_search" ]
2
[ [ "insertion_sort_with_binary_search", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
52e077d42c88e8a3baf5d7ba61428825d049599a
87276ad86ae83bc56982b82529c641e534877e60
v1.0
instruct
Data_Structure
Data_Structure_4506_I
### Coding Assessement Question You have been provided with three different methods to solve the Two-Sum Problem on a sorted array of integers. Write a function `enhanced_two_sum` that selects and executes the most efficient method based on the input size. Specifically, use: - Binary Search (`two_sum`) for arrays smal...
def two_sum(numbers, target): # Binary Search Method for i in range(len(numbers)): low, high = i + 1, len(numbers) - 1 while low <= high: mid = (low + high) // 2 complement = target - numbers[i] if numbers[mid] == complement: return [i + 1, mid...
from solution import enhanced_two_sum def test_small_array(): numbers = [2, 7, 11, 15] target = 9 assert enhanced_two_sum(numbers, target) == [1, 2] def test_medium_array(): numbers = [1, 2, 3, 4, 4, 9, 56, 90] target = 8 assert enhanced_two_sum(numbers, target) == [4, 5] def test_large_array...
[ { "docstring": null, "function_declaration": "def two_sum(numbers, target):", "function_name": "two_sum", "parameter_list": "(numbers, target)" }, { "docstring": null, "function_declaration": "def two_sum1(numbers, target):", "function_name": "two_sum1", "parameter_list": "(numbe...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def two_sum(numbers, target):\n for i, num in enumerate(numbers):\n left, right = i + 1, len(numbers) - 1\n while left <= right:\n ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00004506", "row_id": 4506, "seed_ids": "[195]" }
0.607974
Data_Structure_4506
I
[ "two_sum", "two_sum1", "two_sum2", "enhanced_two_sum" ]
4
[ [ "enhanced_two_sum", "two_sum" ], [ "enhanced_two_sum", "two_sum1" ], [ "enhanced_two_sum", "two_sum2" ] ]
3
[]
false
[]
false
pytest
true
[]
true
5efa9cbad84d5e0070b485a5508cbd309268c58c
124a7155b2bf9f94612b8a24cfdcb4465ac12d99
v1.0
instruct
Data_Structure
Data_Structure_4521_I
#### Linked List Intersection Detection You are given two singly linked lists. Write a function `find_intersection_node(head1, head2)` that identifies the first common node between the two input linked lists, if any. The linked lists are represented by their head nodes. ### Function Signature ```python def find_inter...
class Node: def __init__(self, val=None): self.val = val self.next = None def get_length(node): length = 0 while node: length += 1 node = node.next return length def find_intersection_node(head1, head2): """ Identifies the first common node between two singly li...
def test_no_intersection(): a1 = Node(1) b1 = Node(2) a2 = Node(3) b2 = Node(4) a1.next = b1 a2.next = b2 assert find_intersection_node(a1, a2) == None def test_one_empty_list(): a1 = Node(1) b1 = Node(2) a1.next = b1 assert find_intersection_node(a1, Non...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, val=None):\n self.val = val\n self.next = None\n\ndef get_length(node):\n length = 0\n while node:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004521", "row_id": 4521, "seed_ids": "[245]" }
0.608245
Data_Structure_4521
I
[ "get_length", "find_intersection_node" ]
2
[ [ "find_intersection_node", "get_length" ] ]
1
[]
false
[ "Node" ]
true
pytest
false
[]
true
68572595640de6b749d379081f1410409051fbe5
191cb791f47060433a70e266bd824af769d425a6
v1.0
instruct
Data_Structure
Data_Structure_4565_I
### Question **Objective**: Implement an enhanced variant of the Cooley-Tukey FFT algorithm to handle input arrays of any size, padding the array with zeroes to the next power of two if necessary. #### Problem Statement Given an array \( x \) of complex numbers, implement the function `enhanced_fft(x)` that computes ...
import cmath from math import ceil, log2 def _fft(x): N = len(x) if N <= 1: return x even = _fft(x[0::2]) odd = _fft(x[1::2]) T = [cmath.exp(-2j * cmath.pi * k / N) * odd[k] for k in range(N // 2)] return [even[k] + T[k] for k in range(N // 2)] + [even[k] - T[k] for k in range(N // 2)] ...
from solution import enhanced_fft def test_fft_basic(): # Test case from the examples input_data = [2.0+2j, 1.0+3j, 3.0+1j, 2.0+2j] expected_output = [8+8j, 2j, 2-2j, -2+0j] output = enhanced_fft(input_data) assert len(output) == len(expected_output) assert all(abs(output[i] - expected_output[i...
[ { "docstring": null, "function_declaration": "def _fft(x):", "function_name": "_fft", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def enhanced_fft(x):", "function_name": "enhanced_fft", "parameter_list": "(x)" } ]
[ 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\nimport cmath\n\ndef enhanced_fft(x: List[complex]) -> List[complex]:\n n = len(x)\n \n # Helper function to find the next po...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004565", "row_id": 4565, "seed_ids": "[165]" }
0.576543
Data_Structure_4565
I
[ "_fft", "enhanced_fft" ]
2
[ [ "enhanced_fft", "_fft" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2c862290b15d37ac8d21a4e32fc809f95066716e
7a60e05aaf6de24632d4e421d830f205dad665de
v1.0
instruct
Data_Structure
Data_Structure_4686_I
You are provided with a partially implemented Bitonic Sort algorithm. Your task is to extend the functionality to handle arrays of arbitrary lengths by padding them to the nearest power of 2 with a special value that does not interfere with the normal sorting process. ### Instructions - Implement a function `pad_to_p...
import math def pad_to_power_of_two(arr): """ Pads the input array with `float('inf')` until its length is a power of two. Args: arr (list): The input array to be padded. Returns: list: A new array padded to the nearest power of two length. """ length = len(arr) next_power...
from solution import pad_to_power_of_two, bitonic_sort def test_pad_to_power_of_two(): assert pad_to_power_of_two([3, 7, 2, 8, 1, 5]) == [3, 7, 2, 8, 1, 5, float('inf'), float('inf')] assert pad_to_power_of_two([1]) == [1] assert pad_to_power_of_two([1, 2, 3]) == [1, 2, 3, float('inf')] def test_bitonic_s...
[ { "docstring": "Pads the input array with `float('inf')` until its length is a power of two.\n\nArgs:\narr (list): The input array to be padded.\n\nReturns:\nlist: A new array padded to the nearest power of two length.", "function_declaration": "def pad_to_power_of_two(arr):", "function_name": "pad_to_p...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef pad_to_power_of_two(arr):\n \"\"\"\n Pads the input array with `float('inf')` until its length is a power of two.\n \n Args:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004686", "row_id": 4686, "seed_ids": "[17]" }
0.619854
Data_Structure_4686
I
[ "pad_to_power_of_two", "compare_and_swap", "bitonic_merge", "bitonic_sort_util", "bitonic_sort" ]
5
[ [ "bitonic_merge", "compare_and_swap" ], [ "bitonic_sort", "bitonic_sort_util" ], [ "bitonic_sort", "pad_to_power_of_two" ], [ "bitonic_sort_util", "bitonic_merge" ] ]
4
[]
false
[]
false
pytest
true
[]
true
4f90e0ed4593ccf9312061414077f3d3faea1ca3
be34c4f0da4c9457908408b8d641d28edaeb17c7
v1.0
instruct
Data_Structure
Data_Structure_4714_I
**Question: Implement a Modified Quick Sort** ### Problem Statement You are required to create a function `modified_quick_sort` that sorts an array of integers. The function must include additional enhancements for optimizing the pivot selection to avoid the worst-case performance. Specifically, you should use the **m...
def median_of_three(arr, low, high): mid = (low + high) // 2 if arr[low] > arr[mid]: arr[low], arr[mid] = arr[mid], arr[low] if arr[low] > arr[high]: arr[low], arr[high] = arr[high], arr[low] if arr[mid] > arr[high]: arr[mid], arr[high] = arr[high], arr[mid] return mid def p...
from solution import modified_quick_sort def test_sorted_array(): assert modified_quick_sort([1, 2, 3, 4, 5, 6]) == [1, 2, 3, 4, 5, 6] def test_reverse_sorted_array(): assert modified_quick_sort([6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6] def test_unsorted_array(): assert modified_quick_sort([34, 7, 23, 32...
[ { "docstring": null, "function_declaration": "def median_of_three(arr, low, high):", "function_name": "median_of_three", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def modified_quick_sort(arr: list) -> list:\n if len(arr) <= 1:\n return arr\n\n def median_of_three(lst, left, right):\n mid = (left + ri...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004714", "row_id": 4714, "seed_ids": "[25]" }
0.587665
Data_Structure_4714
I
[ "median_of_three", "partition", "quick_sort_helper", "modified_quick_sort" ]
4
[ [ "modified_quick_sort", "quick_sort_helper" ], [ "partition", "median_of_three" ], [ "quick_sort_helper", "partition" ] ]
3
[]
false
[]
false
pytest
true
[]
true
8a04510a6b88f04faff83df39999e3c826c02eb9
9bb9afa476d233e613f303f83e2cbccb613a058f
v1.0
instruct
Data_Structure
Data_Structure_4722_I
Implementing and Enhancing Nearest Neighbor Algorithm You have been given a task to implement the nearest neighbor algorithm. The algorithm is used to classify a query point based on its similarity to points in a training set. The training set consists of multi-dimensional feature vectors, each associated with a speci...
from typing import Tuple, Dict, Any import math import numpy as np def euclidean_distance(a: Tuple[float, ...], b: Tuple[float, ...]) -> float: """ Calculates the Euclidean distance between two multi-dimensional points. """ return math.sqrt(sum((a_i - b_i) ** 2 for a_i, b_i in zip(a, b))) def nearest_...
from solution import nearest_neighbor def test_nearest_neighbor_single_point(): query_point = (2.0, 3.0) training_set = { (1.0, 2.0): 'A' } assert nearest_neighbor(query_point, training_set) == 'A' def test_nearest_neighbor_multiple_points(): query_point = (2.0, 3.0) training_set = { ...
[]
[ 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 Tuple, Dict, Any\nimport math\n\ndef nearest_neighbor(x: Tuple[float, ...], tSet: Dict[Tuple[float, ...], Any]) -> Any:\n \"\"\"\n Fi...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004722", "row_id": 4722, "seed_ids": "[260]" }
0.625732
Data_Structure_4722
I
[ "euclidean_distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
52304eb3910d23c71518e6510de260cd45bfa1eb
4d160b46effb450407f95cdc019b342e0736d86c
v1.0
instruct
Data_Structure
Data_Structure_4749_I
### Coding Assessment Task: Advanced Radix Sort Implementation #### Scenario Imagine you are part of a team tasked with developing a high-performance sorting utility for a large dataset containing various integers. Your team decided to use Radix Sort due to its efficiency with non-comparative sorting. However, your ta...
from typing import List def counting_sort(arr: List[int], exp: int, simulation: bool=False) -> List[int]: n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = abs(arr[i]) // exp count[index % 10] += 1 for i in range(1, 10): count[i] += count[i ...
from solution import advanced_radix_sort def test_advanced_radix_sort_all_positive_numbers(): assert advanced_radix_sort([170, 45, 75, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 170, 802] def test_advanced_radix_sort_all_negative_numbers(): assert advanced_radix_sort([-170, -45, -75, -802, -24, -2, -66]) == [-80...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp, simulation=False):", "function_name": "counting_sort", "parameter_list": "(arr, exp, simulation=False)" }, { "docstring": null, "function_declaration": "def advanced_radix_sort(arr, simulation=False):", "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\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool=False) -> List[int]:\n n = len(arr)\n output = [0] * n\n coun...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004749", "row_id": 4749, "seed_ids": "[15]" }
0.66534
Data_Structure_4749
I
[ "counting_sort", "advanced_radix_sort" ]
2
[ [ "advanced_radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d335353aad9c180b405cc860055696ec87bfb1ad
cf9b27f3cd33ce21dfbb7ec466b9470450378ccc
v1.0
instruct
Data_Structure
Data_Structure_4843_I
### Insertion Sort Implementation with Search Insert Function **Scenario**: You are working on optimizing the insertion sort algorithm by using a helper function, `search_insert`, which utilizes binary search to determine the position for insertion of the next element. This should theoretically reduce the number of ...
from typing import List def search_insert(array: List[int], target: int) -> int: """ Implements binary search to find the insert position for a target in a sorted array. """ left, right = 0, len(array) - 1 while left <= right: mid = (left + right) // 2 if array[mid] < target: ...
from solution import insertion_sort def test_insertion_sort_sorted_array(): assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_insertion_sort_reverse_sorted_array(): assert insertion_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_insertion_sort_random_array(): assert insertion_sort([4,...
[ { "docstring": "Implements binary search to find the insert position for a target in a sorted array.", "function_declaration": "def search_insert(array, target):", "function_name": "search_insert", "parameter_list": "(array, target)" }, { "docstring": "Sorts an array of integers in ascending...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef search_insert(arr: List[int], value: int) -> int:\n \"\"\"\n This function uses binary search to find the index where the...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004843", "row_id": 4843, "seed_ids": "[199]" }
0.539027
Data_Structure_4843
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f8aacc827ec86f45d884376a4ccb8f7d83f28958
c1214788e5ef569e7550bd47ac2773c642cce54e
v1.0
instruct
Data_Structure
Data_Structure_4894_I
Implement Insertion Sort Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at a time. In your implementation, use the 'search_insert' function to determine the correct insertion point of each element. *Implement the following function:* ```python def insertion_sort(array): ...
def search_insert(array, target, start, end): """ Helper function to find the index where 'target' should be inserted in the sorted subarray 'array[start:end+1]'. Parameters: array (List[int]): The list of integers to be sorted. target (int): The target value for which the insertion index ...
from solution import insertion_sort, search_insert def test_search_insert(): assert search_insert([1, 2, 4, 5], 3, 0, 3) == 2 assert search_insert([1, 3, 5, 7], 6, 0, 3) == 3 assert search_insert([1, 2, 3, 4], 0, 0, 3) == 0 assert search_insert([2, 4, 6, 8], 10, 0, 3) == 4 def test_insertion_sort(): ...
[ { "docstring": "Helper function to find the index where 'target' should be inserted \nin the sorted subarray 'array[start:end+1]'.\n\nParameters:\narray (List[int]): The list of integers to be sorted.\ntarget (int): The target value for which the insertion index is to \n be found.\nstart (int): The...
[ 0, 1 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def search_insert(arr, left, right, key):\n \"\"\"\n Helper function to determine the index to insert the key using binary search\n \n Parameters:...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004894", "row_id": 4894, "seed_ids": "[199]" }
0.647299
Data_Structure_4894
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
034f8b43fc190ead4355aca09f236b3bfd6f6390
a7d1e0b7c20ee198730be9af27e57b77f5d5e455
v1.0
instruct
Data_Structure
Data_Structure_4918_I
### Coding Challenge: Custom Radix Sort Implementation #### Scenario You are a software engineer tasked with optimizing the sorting process for a large dataset of integers representing customer IDs. The IDs can be assumed to be non-negative integers. Given that the input list can be extremely large, you must ensure th...
from typing import List def counting_sort(arr: List[int], exp: int) -> None: """ A function to do counting sort based on the digit represented by exp """ n = len(arr) output = [0] * n # output array count = [0] * 10 # count array for digits (0 to 9) # Store count of occurrences in co...
from solution import custom_radix_sort def test_custom_radix_sort_general_case(): assert custom_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_custom_radix_sort_empty_list(): assert custom_radix_sort([]) == [] def test_custom_radix_sort_single_element(): asser...
[ { "docstring": "A function to do counting sort based on the digit represented by exp", "function_declaration": "def counting_sort(arr, exp):", "function_name": "counting_sort", "parameter_list": "(arr, exp)" }, { "docstring": "Function to implement the Radix Sort algorithm", "function_de...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef custom_radix_sort(arr: List[int]) -> List[int]:\n if not arr:\n return arr # Immediate return for empty list\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004918", "row_id": 4918, "seed_ids": "[15]" }
0.598883
Data_Structure_4918
I
[ "counting_sort", "custom_radix_sort" ]
2
[ [ "custom_radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a33dcdb8e0d53fb76b41a6bd95dd5a4a7800edf8
04a21449f758878b9982ac1df684e010900ab975
v1.0
instruct
Data_Structure
Data_Structure_4989_I
### Bucket Sort Implementation Challenge **Context**: You are tasked with enhancing a sorting system for an e-commerce platform. The system uses bucket sort to optimize the ranking of product prices for various categories. Your objective is to implement `bucket_sort` and `next_sort` functions that efficiently sort an ...
from typing import List def next_sort(arr: List[float]) -> List[float]: """ Performs insertion sort on the provided list `arr`. """ 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...
from solution import bucket_sort def test_bucket_sort_basic(): assert bucket_sort([42.3, 12.1, 13.5, 99.9, 2.2, 54.4, 22.2]) == [2.2, 12.1, 13.5, 22.2, 42.3, 54.4, 99.9] def test_bucket_sort_empty(): assert bucket_sort([]) == [] def test_bucket_sort_single_element(): assert bucket_sort([42.3]) == [42.3] ...
[ { "docstring": "Performs insertion sort on the provided list `arr`.", "function_declaration": "def next_sort(arr):", "function_name": "next_sort", "parameter_list": "(arr)" }, { "docstring": "Sorts the list `arr` using bucket sort algorithm.", "function_declaration": "def bucket_sort(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 insertion_sort(arr: List[float]) -> List[float]:\n \"\"\"\n Performs an insertion sort on the given array and returns the...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004989", "row_id": 4989, "seed_ids": "[26]" }
0.50916
Data_Structure_4989
I
[ "next_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "next_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
69daa92542b02a110b6fcb971377a796980caef0
862b298789f3fcfcc0a3dd8cb0b97104463121d9
v1.0
instruct
Data_Structure
Data_Structure_4997_I
### Hailstone Sequence Analysis and Extension #### Objective: Implement and analyze the hailstone sequence generator and write a function to compute statistics on the sequence. #### Details: 1. **Function 1**: `hailstone(n)`: Generate the hailstone sequence starting from an integer `n`. * **Input**: A positive in...
def hailstone(n): """ Generate the hailstone sequence starting from an integer n. Parameters: n (int): A positive integer (1 ≤ n ≤ 10^6). Returns: List[int]: A list representing the hailstone sequence starting from n and ending at 1. """ sequence = [] while n !=...
from solution import hailstone, hailstone_extended_statistics def test_hailstone_1(): assert hailstone(1) == [1] def test_hailstone_7(): assert hailstone(7) == [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] def test_hailstone_27(): assert hailstone(27) == [27, 82, 41, 124, 62, 31, 94, 47,...
[ { "docstring": "Generate the hailstone sequence starting from an integer n.\n\nParameters:\n n (int): A positive integer (1 ≤ n ≤ 10^6).\n \nReturns:\n List[int]: A list representing the hailstone sequence starting from n and ending at 1.", "function_declaration": "def hailstone(n):", "function...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def hailstone(n):\n \"\"\"\n Returns the hailstone sequence starting from n and ending at 1.\n \"\"\"\n sequence = []\n while n != 1:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004997", "row_id": 4997, "seed_ids": "[167]" }
0.566178
Data_Structure_4997
I
[ "hailstone", "hailstone_extended_statistics" ]
2
[ [ "hailstone_extended_statistics", "hailstone" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a38b9ee38fce04a8fd38be2f5650b31677a72d54
d62148198296f5e39d744b53484e0f3cbe01c114
v1.0
instruct
Data_Structure
Data_Structure_5053_I
### Question: Comprehensive String Reversal Function You are tasked with creating a comprehensive function that reverses a given string. You must implement a function that allows selection between four different reversal techniques: 1. **Recursive**: Using recursion to divide and conquer. 2. **Iterative**: Using a tw...
def reverse_string(s: str, method: str) -> str: if method == "recursive": return recursive_reverse(s) elif method == "iterative": return iterative_reverse(s) elif method == "pythonic": return pythonic_reverse(s) elif method == "ultra_pythonic": return ultra_pythonic_rever...
from solution import reverse_string def test_recursive_reverse(): assert reverse_string("example", "recursive") == "elpmaxe" assert reverse_string("a", "recursive") == "a" assert reverse_string("", "recursive") == "" assert reverse_string("racecar", "recursive") == "racecar" assert reverse_string("...
[ { "docstring": null, "function_declaration": "def reverse_string(s, method):", "function_name": "reverse_string", "parameter_list": "(s, method)" }, { "docstring": null, "function_declaration": "def recursive_reverse(s):", "function_name": "recursive_reverse", "parameter_list": "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def reverse_string(s: str, method: str) -> str:\n if method == \"recursive\":\n return _reverse_recursive(s)\n elif method == \"iterative\":\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005053", "row_id": 5053, "seed_ids": "[61]" }
0.746835
Data_Structure_5053
I
[ "reverse_string", "recursive_reverse", "iterative_reverse", "pythonic_reverse", "ultra_pythonic_reverse" ]
5
[ [ "reverse_string", "iterative_reverse" ], [ "reverse_string", "pythonic_reverse" ], [ "reverse_string", "recursive_reverse" ], [ "reverse_string", "ultra_pythonic_reverse" ] ]
4
[]
false
[]
false
pytest
true
[]
true
b6543f2537b062b09bbd1a737d969d6a58c67684
f8044582a6eb35ad623eb5114c9844467bd3c10a
v1.0
instruct
Data_Structure
Data_Structure_5057_I
### Secure Key Exchange using Diffie-Hellman Protocol **Objective**: Implement a secure key exchange using the Diffie-Hellman protocol. ### Problem Statement Alice and Bob want to securely share a secret key over an insecure communication channel using the Diffie-Hellman key exchange protocol. The security of the com...
from typing import List import random def is_prime(n: int) -> bool: """ Checks if a number n is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: ...
from solution import is_prime, calculate_primitive_root, diffie_hellman_key_exchange def test_is_prime(): assert is_prime(2) == True assert is_prime(11) == True assert is_prime(23) == True assert is_prime(1) == False assert is_prime(10) == False assert is_prime(0) == False assert is_prime(-...
[ { "docstring": "Checks if a number n is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Finds all the primitive roots of a prime number p.", "function_declaration": "def calculate_primitive_root(p):", "funct...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n: int) -> bool:\n \"\"\"\n Determines if a number n is a prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00005057", "row_id": 5057, "seed_ids": "[146]" }
0.467483
Data_Structure_5057
I
[ "is_prime", "calculate_primitive_root", "diffie_hellman_key_exchange" ]
3
[ [ "calculate_primitive_root", "is_prime" ], [ "diffie_hellman_key_exchange", "calculate_primitive_root" ], [ "diffie_hellman_key_exchange", "is_prime" ] ]
3
[]
false
[]
false
pytest
true
[]
true
d4ca33b6cdca1c87e125c33c0d2c79b8a154db11
d18e316333ebdd658db9a5ce01d16f8d07810946
v1.0
instruct
Data_Structure
Data_Structure_5066_I
### Problem: Enhanced Comb Sort You are given an array of integers and need to sort it using an enhanced version of the Comb Sort algorithm. Your task is to modify the given Comb Sort algorithm so that it can handle the following additional requirements: 1. **Pre-check for Small Arrays**: If the array length is less ...
def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr def enhanced_comb_sort(arr): n = len(arr) # Pre-check for small arrays if n...
from solution import enhanced_comb_sort def test_sorted_array(): assert enhanced_comb_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reversed_array(): assert enhanced_comb_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_unsorted_array(): assert enhanced_comb_sort([23, -3, 4, 68, 34, 23, 93, 0]) == [...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr):", "function_name": "insertion_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def enhanced_comb_sort(arr):", "function_name": "enhanced_comb_sort", "parameter_list": "(arr)" ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def enhanced_comb_sort(arr):\n def insertion_sort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005066", "row_id": 5066, "seed_ids": "[21]" }
0.627585
Data_Structure_5066
I
[ "insertion_sort", "enhanced_comb_sort" ]
2
[ [ "enhanced_comb_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a3200fa22eba8e89b44f8cfab4b359cd92774d65
b6d257a0c257139d79f902aa26c1acde43f83283
v1.0
instruct
Data_Structure
Data_Structure_5068_I
### Nearest Neighbor Algorithm with Constraints You are given a nearest neighbor algorithm that finds the closest vector to a given vector from a training set and returns the result associated with that vector. Your task is to implement this functionality as accurately and efficiently as possible. #### Problem Descri...
from typing import Tuple, Dict, Any import math def euclidean_distance(a: Tuple[float], b: Tuple[float]) -> float: return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b))) def nearest_neighbor(x: Tuple[float], tSet: Dict[Tuple[float], Any]) -> Any: closest_vector = None min_distance = float('inf') fo...
from solution import nearest_neighbor def test_nearest_neighbor_example(): x = (1.0, 2.0) tSet = { (1.1, 2.1): 'A', (3.0, 4.0): 'B', (6.0, 7.0): 'C' } assert nearest_neighbor(x, tSet) == 'A' def test_nearest_neighbor_single_vector(): x = (1.0, 2.0) tSet = { (1.0...
[ { "docstring": null, "function_declaration": "def euclidean_distance(a, b):", "function_name": "euclidean_distance", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def nearest_neighbor(x, tSet):", "function_name": "nearest_neighbor", "parameter_list":...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom typing import Tuple, Dict, Any\n\ndef euclidean_distance(vec1: Tuple[float], vec2: Tuple[float]) -> float:\n return math.sqrt(sum((a - b)...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005068", "row_id": 5068, "seed_ids": "[260]" }
0.650516
Data_Structure_5068
I
[ "euclidean_distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f52b308e763908b2aa34f5bfe8f4b2d0660caf66
00ac910a24ede7c71374337cb2abdd1587bf049f
v1.0
instruct
Data_Structure
Data_Structure_5091_I
### Merge Sort Implementation Question You have been assigned a task to implement the Merge Sort algorithm. Merge Sort is a classic divide-and-conquer algorithm that is efficient and guarantees a time complexity of O(n log(n)) for sorting an array of elements. Your task is to implement the `merge_sort` function which ...
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts an array of integers using the merge sort algorithm. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half,...
from solution import merge_sort def test_merge_sort_with_random_array(): assert merge_sort([34, 7, 23, 32, 5, 62]) == [5, 7, 23, 32, 34, 62] def test_merge_sort_with_reverse_sorted_array(): assert merge_sort([4, 3, 2, 1]) == [1, 2, 3, 4] def test_merge_sort_with_single_element(): assert merge_sort([1]) =...
[ { "docstring": "Sorts an array of integers using the merge sort algorithm.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merges two sorted lists into one sorted list.", "function_declaration": "def merge(left...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Implementation of the merge sort algorithm.\n \"\"\"\n if len(a...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005091", "row_id": 5091, "seed_ids": "[12]" }
0.680515
Data_Structure_5091
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5696b80272deae3a8828533968b83988a10d7951
5fac0cc3300d7d794f8d89f9532ff4d0d2fb43ce
v1.0
instruct
Data_Structure
Data_Structure_5113_I
### RSA Encryption and Decryption Implementation (Advanced) You are required to implement the RSA encryption algorithm for a secure communication system. Your task is to provide functions for generating RSA keys, encrypting messages, and decrypting messages, demonstrating a thorough understanding of RSA principles and ...
import random from sympy import isprime, mod_inverse def generate_prime(bits): while True: prime_candidate = random.getrandbits(bits) if isprime(prime_candidate): return prime_candidate def generate_key(k, seed=None): if seed is not None: random.seed(seed) p = gene...
from solution import generate_key, encrypt, decrypt def test_generate_key(): n, e, d = generate_key(16, seed=1234) assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) def test_encrypt_decrypt(): n, e, d = generate_key(16, seed=1234) data = 42 encrypted = encrypt(d...
[ { "docstring": null, "function_declaration": "def generate_prime(bits):", "function_name": "generate_prime", "parameter_list": "(bits)" }, { "docstring": null, "function_declaration": "def generate_key(k, seed=None):", "function_name": "generate_key", "parameter_list": "(k, seed=...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, gcd, mod_inverse\n\n\ndef generate_key(k, seed=None):\n \"\"\"\n Generates the public and private keys for RSA...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005113", "row_id": 5113, "seed_ids": "[154]" }
0.57408
Data_Structure_5113
I
[ "generate_prime", "generate_key", "encrypt", "decrypt" ]
4
[ [ "generate_key", "generate_prime" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
d73d646b8563597830daf6c5858ee507cf257971
2dab15800ee1c36c90cf46b0e9a80b23c1306a61
v1.0
instruct
Data_Structure
Data_Structure_5168_I
You are tasked with implementing the Bitonic Sort algorithm. This algorithm sorts using a divide-and-conquer approach and is notably efficient when parallelism is leveraged. Although in your implementation, you will not use parallel processing, the core principles of the Bitonic Sort must be retained. The Bitonic Sort ...
def bitonic_compare(arr, start, end, direction): length = end - start mid = length // 2 for i in range(start, start + mid): if (direction and arr[i] > arr[i + mid]) or (not direction and arr[i] < arr[i + mid]): arr[i], arr[i + mid] = arr[i + mid], arr[i] def bitonic_merge(arr, start, en...
from solution import bitonic_sort def test_bitonic_sort_ascending(): arr = [3, 7, 2, 8, 1, 5, 4, 6] expected = [1, 2, 3, 4, 5, 6, 7, 8] assert bitonic_sort(arr, reverse=True) == expected def test_bitonic_sort_descending(): arr = [3, 7, 2, 8, 1, 5, 4, 6] expected = [8, 7, 6, 5, 4, 3, 2, 1] asse...
[ { "docstring": null, "function_declaration": "def bitonic_compare(arr, start, end, direction):", "function_name": "bitonic_compare", "parameter_list": "(arr, start, end, direction)" }, { "docstring": null, "function_declaration": "def bitonic_merge(arr, start, end, direction):", "fun...
[ 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 bitonic_sort(arr, reverse=False):\n def compare_and_swap(arr, i, j, direction):\n if (direction and arr[i] > arr[j]) or (not direction and arr[i...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005168", "row_id": 5168, "seed_ids": "[17]" }
0.655589
Data_Structure_5168
I
[ "bitonic_compare", "bitonic_merge", "bitonic_sort_recursive", "bitonic_sort" ]
4
[ [ "bitonic_merge", "bitonic_compare" ], [ "bitonic_sort", "bitonic_sort_recursive" ], [ "bitonic_sort_recursive", "bitonic_merge" ] ]
3
[]
false
[]
false
pytest
true
[]
true
f1618d975a86fec454ae7f014ae7e92732b68ee6
a66c3f594b97214e92211e889a2f4034f53dac2e
v1.0
instruct
Data_Structure
Data_Structure_5313_I
### Question: Cycle Detection in a Directed Graph Using DFS You are given a directed graph represented as an adjacency list. Your task is to write a function `contains_cycle(graph)` that determines whether the graph contains a cycle. #### Function Signature ```python def contains_cycle(graph: Dict[str, List[str]]) ->...
from enum import Enum from typing import List, Dict class TraversalState(Enum): WHITE = 0 # Vertex has not been visited yet GRAY = 1 # Vertex is being visited (in the current path) BLACK = 2 # Vertex and all its descendants have been completely visited def is_in_cycle(graph, traversal_states, vertex):...
from solution import contains_cycle def test_no_cycle(): graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['F'], 'D': ['E', 'F'], 'E': [], 'F': []} assert not contains_cycle(graph) def test_with_cycle(): graph = {'A': ['B', 'C'], '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": "from enum import Enum\nfrom typing import Dict, List\n\nclass TraversalState(Enum):\n WHITE = 0 # Vertex has not been visited\n GRAY = 1 # Vertex is ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005313", "row_id": 5313, "seed_ids": "[237]" }
0.665082
Data_Structure_5313
I
[ "is_in_cycle", "contains_cycle" ]
2
[ [ "contains_cycle", "is_in_cycle" ] ]
1
[]
false
[ "TraversalState" ]
true
pytest
true
[]
true
e31c6e2f3c8440ed67616d2a8691588ce3e3405d
2a4ff4a77b5af6501a3f7acba6d7b9d498cc83dc
v1.0
instruct
Data_Structure
Data_Structure_5354_I
Implement Nearest Neighbor Classifier #### Context You are working on a simple classification system that uses a nearest neighbor algorithm to classify data points. Your task is to create a function that finds the nearest neighbor of a given input vector `x` from a training set `tSet`. #### Task Implement the `neares...
import math def euclidean_distance(v1, v2): """ Calculates the Euclidean distance between two vectors v1 and v2. """ sum_squared_diff = sum((a - b) ** 2 for a, b in zip(v1, v2)) return math.sqrt(sum_squared_diff) def nearest_neighbor(x, tSet): """ Finds the nearest neighbor of vector x fro...
from solution import nearest_neighbor, euclidean_distance def test_euclidean_distance(): assert euclidean_distance((0, 0), (3, 4)) == 5.0 assert euclidean_distance((1, 2), (1, 2)) == 0.0 assert euclidean_distance((1, 2, 3), (4, 5, 6)) == math.sqrt(27) def test_nearest_neighbor_basic(): x = (2, 3) ...
[ { "docstring": "Calculates the Euclidean distance between two vectors v1 and v2.", "function_declaration": "def euclidean_distance(v1, v2):", "function_name": "euclidean_distance", "parameter_list": "(v1, v2)" }, { "docstring": "Finds the nearest neighbor of vector x from the training set tS...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef euclidean_distance(v1, v2):\n \"\"\"\n Calculate the Euclidean distance between two vectors v1 and v2.\n \"\"\"\n return math.s...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005354", "row_id": 5354, "seed_ids": "[260]" }
0.626396
Data_Structure_5354
I
[ "euclidean_distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
395275aadcfe6e176e582bb9f9102c1dedae0479
83328ad1db0043276dded87b2028bb5ce8a20cc0
v1.0
instruct
Data_Structure
Data_Structure_5370_I
### Question: Implement Accelerated Pattern Matching in a Text Given a large text and a pattern string, write a function using the Knuth-Morris-Pratt (KMP) algorithm that efficiently finds all starting positions of the pattern in the text. #### Function Signature ```python def find_pattern_positions(text: str, patter...
from typing import List def compute_lps(pattern: str) -> List[int]: """ Helper function to compute the longest proper prefix which is also suffix table (lps array) for the given pattern using KMP algorithm. """ lps = [0] * len(pattern) length = 0 # length of the previous longest prefix suffix ...
import pytest from solution import find_pattern_positions def test_single_occurrence(): assert find_pattern_positions("hello world", "world") == [6] def test_multiple_occurrences(): assert find_pattern_positions("abcabcabc", "abc") == [0, 3, 6] def test_no_occurrence(): assert find_pattern_positions("abc...
[ { "docstring": "Helper function to compute the longest proper prefix which is also suffix table (lps array)\nfor the given pattern using KMP algorithm.", "function_declaration": "def compute_lps(pattern):", "function_name": "compute_lps", "parameter_list": "(pattern)" }, { "docstring": "Func...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef find_pattern_positions(text: str, pattern: str) -> List[int]:\n def compute_lps(pattern: str) -> List[int]:\n \"\"\"\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00005370", "row_id": 5370, "seed_ids": "[93]" }
0.57232
Data_Structure_5370
I
[ "compute_lps", "find_pattern_positions" ]
2
[ [ "find_pattern_positions", "compute_lps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
454eaddae38b8b83816f35963ed37ae660cf9431
068c0e2d1ccdb7fd913d2b2b6e944c24e5ed7ddc
v1.0
instruct
Data_Structure
Data_Structure_5381_I
**Scenario**: You are developing a microservice for a software system that processes large volumes of numerical data. The service needs to efficiently compute the GCD and LCM of integer pairs, including the ability to handle large values and edge cases robustly. As such, you are tasked with implementing these calculati...
def calculate_gcd(a: int, b: int) -> int: """ Calculate the Greatest Common Divisor (GCD) of two non-zero integers. """ if not isinstance(a, int) or not isinstance(b, int): raise ValueError("Both inputs must be integers.") if a == 0 or b == 0: raise ValueError("Both input values must...
from solution import calculate_gcd, calculate_lcm def test_calculate_gcd_positive_numbers(): assert calculate_gcd(48, 18) == 6 def test_calculate_gcd_negative_numbers(): assert calculate_gcd(-48, 18) == 6 assert calculate_gcd(48, -18) == 6 assert calculate_gcd(-48, -18) == 6 def test_calculate_gcd_wi...
[ { "docstring": "Calculate the Greatest Common Divisor (GCD) of two non-zero integers.", "function_declaration": "def calculate_gcd(a, b):", "function_name": "calculate_gcd", "parameter_list": "(a, b)" }, { "docstring": "Calculate the Least Common Multiple (LCM) of two non-zero integers.", ...
[ 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 calculate_gcd(a, b):\n \"\"\"\n Returns the greatest common divisor (GCD) of a and b.\n \"\"\"\n if not isinstance(a, int) or not isinstance(b...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005381", "row_id": 5381, "seed_ids": "[166]" }
0.510903
Data_Structure_5381
I
[ "calculate_gcd", "calculate_lcm" ]
2
[ [ "calculate_lcm", "calculate_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a8b7cef669e453cd141819d166f57605967d0725
76a553277cfef34b4395c9362c8e0f3b42319bda
v1.0
instruct
Data_Structure
Data_Structure_5390_I
### Radix Sort Implementation **Scenario**: You are tasked with implementing a sorting module that sorts large lists of non-negative integers efficiently. Your module will use Radix Sort, a highly efficient sorting algorithm for such data. The sorting needs to be stable, ensuring that the relative order of numbers wit...
def counting_sort_for_radix(arr, exp): n = len(arr) output = [0] * n # output array that will have sorted arr count = [0] * 10 # count array to store occurrences of digits # Store count of occurrences in count[] for i in range(n): index = (arr[i] // exp) % 10 count[index] += 1 ...
from solution import radix_sort def test_radix_sort_typical_case(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_single_element(): assert radix_sort([123]) == [123] def test_radix_sort_empty_list(): assert radix_sort([]) == [] def test_rad...
[ { "docstring": null, "function_declaration": "def counting_sort_for_radix(arr, exp):", "function_name": "counting_sort_for_radix", "parameter_list": "(arr, exp)" }, { "docstring": "Performs radix sort on a list of non-negative integers", "function_declaration": "def radix_sort(arr):", ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n for i in range(n):\n index = (arr[i] // exp) % 10\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005390", "row_id": 5390, "seed_ids": "[15]" }
0.617651
Data_Structure_5390
I
[ "counting_sort_for_radix", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort_for_radix" ] ]
1
[]
false
[]
false
pytest
true
[]
true
750ceaf6e2f1ef0f14e5b55320aa730bbaf9124f
f64d4562f9a60a4306635d5c0f1ad338e4028cbf
v1.0
instruct
Data_Structure
Data_Structure_5409_I
### Sudoku Solver Implementation #### Context You are tasked with implementing a Sudoku solver. Sudoku is a number puzzle game played on a 9x9 grid, divided into 3x3 subgrids. The objective is to fill the grid with numbers from 1 to 9 such that each row, each column, and each 3x3 subgrid contains all the numbers from ...
from typing import List def is_valid(board: List[List[str]], row: int, col: int, num: str) -> bool: # Check if num is not in the current row/column/subgrid # Check row for i in range(9): if board[row][i] == num: return False # Check column for i in range(9): if board[i]...
from solution import sudoku_solver def test_sudoku_solver(): board1 = [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ...
[ { "docstring": null, "function_declaration": "def is_valid(board, row, col, num):", "function_name": "is_valid", "parameter_list": "(board, row, col, num)" }, { "docstring": null, "function_declaration": "def find_empty(board):", "function_name": "find_empty", "parameter_list": "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def sudoku_solver(board):\n def is_valid(num, row, col):\n # Check if the number is not repeated in the row, column and 3x3 subgrid\n for i i...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005409", "row_id": 5409, "seed_ids": "[179]" }
0.686374
Data_Structure_5409
I
[ "is_valid", "find_empty", "sudoku_solver" ]
3
[ [ "sudoku_solver", "find_empty" ], [ "sudoku_solver", "is_valid" ] ]
2
[]
false
[]
false
pytest
true
[]
true
aa7e130b1c4dde04f8959674a2746ea6e56e9672
4a6415d2e539a563d4063f79c3e6064cf6ddace2
v1.0
instruct
Data_Structure
Data_Structure_5450_I
### Question: Enhanced Sorting Algorithm Implementation Given the provided code snippet for the Cocktail Shaker Sort, your task is to implement an enhanced sorting algorithm with the following specifications: 1. **Hybrid Approach**: Combine the Cocktail Shaker Sort with a more efficient algorithm (of your choice) to ...
def cocktail_shaker_sort(arr): n = len(arr) swapped = True start = 0 end = n - 1 while swapped: swapped = False for i in range(start, end): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] swapped = True if not swappe...
from solution import enhanced_sort def test_enhanced_sort_small_array(): assert enhanced_sort([3, 2, 5, 4, 1]) == [1, 2, 3, 4, 5] def test_enhanced_sort_sorted_array(): assert enhanced_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] assert enhanced_sort([10, 20, 30, 40, 50]) == [10, 20, 30, 40, 50] def test_enh...
[ { "docstring": null, "function_declaration": "def cocktail_shaker_sort(arr):", "function_name": "cocktail_shaker_sort", "parameter_list": "(arr)" }, { "docstring": "Enhanced sorting function combining cocktail shaker sort with a more efficient algorithm.\n\nArgs:\narr (list): A list of integ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def cocktail_shaker_sort(arr):\n \"\"\"\n Helper function to perform Cocktail Shaker Sort on the array.\n \"\"\"\n n = len(arr)\n swapped = Tru...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005450", "row_id": 5450, "seed_ids": "[24]" }
0.608304
Data_Structure_5450
I
[ "cocktail_shaker_sort", "enhanced_sort" ]
2
[ [ "enhanced_sort", "cocktail_shaker_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f95406f6ea5a7ddeae4d864756118fc3cffb7aa5
3b48bf47a8ad84be56f1ec4ccee1edba9e5715a3
v1.0
instruct
Data_Structure
Data_Structure_5458_I
You are given a large body of text and a set of phrases. Your task is to implement a function that identifies all the starting positions of each phrase within the given text using the Knuth-Morris-Pratt (KMP) algorithm for pattern matching. ### Function Signature ```python def find_phrases_in_text(text: str, phrases:...
from typing import List def kmp_search(pattern: str, text: str) -> List[int]: """ Perform KMP search of the pattern in the text and returns a list of starting indices where the pattern is found in the text. """ def compute_lps(pattern: str) -> List[int]: lps = [0] * len(pattern) len...
from solution import find_phrases_in_text def test_empty_text_and_phrases(): assert find_phrases_in_text('', []) == [] assert find_phrases_in_text('', ['hello']) == [[]] assert find_phrases_in_text('hello', []) == [] def test_phrases_found_in_text(): assert find_phrases_in_text('hello there hero! hell...
[ { "docstring": "Perform KMP search of the pattern in the text and returns a list of starting indices\nwhere the pattern is found in the text.", "function_declaration": "def kmp_search(pattern, text):", "function_name": "kmp_search", "parameter_list": "(pattern, text)" }, { "docstring": null,...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef compute_kmp_table(pattern: str) -> List[int]:\n \"\"\"\n Computes the KMP partial match table (also known as \"failure fu...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00005458", "row_id": 5458, "seed_ids": "[93]" }
0.547781
Data_Structure_5458
I
[ "kmp_search", "find_phrases_in_text" ]
2
[ [ "find_phrases_in_text", "kmp_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
70a1f128ba063ec1e632975c91fd2d5829bd76c1
29560129fc044d85d9fc68e9a8febfbc9f5701ac
v1.0
instruct
Data_Structure
Data_Structure_5464_I
### Pancake Sort Implementation Challenge You are provided with a sorting algorithm called Pancake Sort. This algorithm sorts an array by repeatedly flipping sections of the array. Your task is to modify the given algorithm to improve its efficiency and ensure robust handling of edge cases. #### Problem Statement Wr...
def flip(arr, k): """ Reverse the order of the first k elements of arr. """ return arr[:k][::-1] + arr[k:] def optimized_pancake_sort(arr): """ Sorts the array using an optimized pancake sort method. """ n = len(arr) for i in range(n, 1, -1): # Find the index of the largest ...
from solution import optimized_pancake_sort def test_sorted_array(): assert optimized_pancake_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): assert optimized_pancake_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_unsorted_array(): assert optimized_pancake_sort([3, 2, 4, 1]) ...
[ { "docstring": "Reverse the order of the first k elements of arr.", "function_declaration": "def flip(arr, k):", "function_name": "flip", "parameter_list": "(arr, k)" }, { "docstring": "Sorts the array using an optimized pancake sort method.", "function_declaration": "def optimized_panca...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def optimized_pancake_sort(arr):\n \"\"\"\n Sorts an array using an optimized version of the Pancake Sort algorithm.\n \"\"\"\n def flip(arr, k):\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005464", "row_id": 5464, "seed_ids": "[9]" }
0.712298
Data_Structure_5464
I
[ "flip", "optimized_pancake_sort" ]
2
[ [ "optimized_pancake_sort", "flip" ] ]
1
[]
false
[]
false
pytest
true
[]
true
afae80cd91f2389a3f51fb84394d62a45c642f39
7d19f4887f423cf49d6dd81123c19f8a71efc6ea
v1.0
instruct
Data_Structure
Data_Structure_5509_I
## Coding Assessment Question ### Matrix Inversion Function Implementation **Objective**: Implement a function to invert an invertible \(n \times n\) matrix, adhering to the principles of matrix operations, including the use of minors, cofactors, adjugation, and determinant calculations. ### Problem Statement: You a...
from typing import List def determinant(matrix: List[List[float]]) -> float: """ Calculate the determinant of a square matrix. """ n = len(matrix) if n == 1: return matrix[0][0] if n == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] det = 0 ...
from solution import invert_matrix def test_invert_2x2_matrix(): matrix = [ [1, 2], [3, 4] ] expected = [ [-2.0, 1.0], [1.5, -0.5] ] assert invert_matrix(matrix) == expected def test_invert_3x3_matrix(): matrix = [ [3, 0, 2], [2, 0, -2], ...
[ { "docstring": "Calculate the determinant of a square matrix.", "function_declaration": "def determinant(matrix):", "function_name": "determinant", "parameter_list": "(matrix)" }, { "docstring": "Calculate the minor of a matrix element at a specified row and column.", "function_declarati...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef determinant(matrix: List[List[float]]) -> float:\n \"\"\"\n Calculate the determinant of a square matrix.\n \"\"\"\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005509", "row_id": 5509, "seed_ids": "[347]" }
0.604859
Data_Structure_5509
I
[ "determinant", "minor", "cofactor", "transpose", "invert_matrix" ]
5
[ [ "cofactor", "determinant" ], [ "cofactor", "minor" ], [ "invert_matrix", "cofactor" ], [ "invert_matrix", "determinant" ], [ "invert_matrix", "transpose" ] ]
5
[]
false
[]
false
pytest
true
[]
true
6c18d321a62ac47ee2992e386fe00c9c61346c69
64c90e2f29f1bd404baa0464b74eb8063db7f2e0