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_31125_I
### **Heap Sort Implementation** You are given two variants of heap sort implemented in the form of functions `max_heap_sort` and `min_heap_sort`. The `max_heap_sort` sorts an array in ascending order by converting it into a max heap and repeatedly removing the greatest element, whereas `min_heap_sort` does the same b...
def max_heapify(arr, n, i, simulation=False): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[i] < arr[left]: largest = left if right < n and arr[largest] < arr[right]: largest = right if largest != i: arr[i], arr[largest] = arr[largest], arr[i] ...
def test_hybrid_heap_sort_empty(): assert hybrid_heap_sort([], use_max_heap=True) == [] assert hybrid_heap_sort([], use_max_heap=False) == [] def test_hybrid_heap_sort_single_element(): assert hybrid_heap_sort([1], use_max_heap=True) == [1] assert hybrid_heap_sort([1], use_max_heap=False) == [1] def t...
[ { "docstring": null, "function_declaration": "def max_heapify(arr, n, i, simulation=False):", "function_name": "max_heapify", "parameter_list": "(arr, n, i, simulation=False)" }, { "docstring": null, "function_declaration": "def min_heapify(arr, n, i, simulation=False):", "function_n...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def max_heapify(arr, n, i):\n largest = i\n l = 2 * i + 1\n r = 2 * i + 2\n\n if l < n and arr[largest] < arr[l]:\n largest = l\n\n if r...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00031125", "row_id": 31125, "seed_ids": "[8]" }
0.627211
Data_Structure_31125
I
[ "max_heapify", "min_heapify", "max_heap_sort", "min_heap_sort", "hybrid_heap_sort" ]
5
[ [ "hybrid_heap_sort", "max_heap_sort" ], [ "hybrid_heap_sort", "min_heap_sort" ], [ "max_heap_sort", "max_heapify" ], [ "min_heap_sort", "min_heapify" ] ]
4
[]
false
[]
false
pytest
false
[]
true
ff1f4cb5710c5b0897d9b7fc492de25f11059de7
2b97a11249702cef02d21c45c89344b3fe95f6a1
v1.0
instruct
Data_Structure
Data_Structure_31163_I
You are part of a software engineering team working on a data compression tool utilizing Huffman coding. Your task is to implement functions to encode and decode data files using the Huffman coding algorithm. ### Requirements 1. **Encoding**: Implement a function `encode_data(input_file: str, output_file: str)` that...
import heapq from collections import defaultdict, Counter class HuffmanNode: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def build_huffman_tree(frequencies):...
import os from solution import encode_data, decode_data def create_test_file(file_path, content): with open(file_path, 'w') as f: f.write(content) def read_file(file_path): with open(file_path, 'r') as f: return f.read() def test_encode_decode(): test_input = 'test_input.txt' encoded_...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\nfrom collections import defaultdict, Counter\n\n# Node for Huffman Tree\nclass Node:\n def __init__(self, char=None, freq=None):\n sel...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00031163", "row_id": 31163, "seed_ids": "[335]" }
0.506259
Data_Structure_31163
I
[ "build_huffman_tree", "generate_huffman_codes", "encode_data", "decode_data" ]
4
[ [ "encode_data", "build_huffman_tree" ], [ "encode_data", "generate_huffman_codes" ] ]
2
[]
false
[ "HuffmanNode" ]
true
pytest
true
[]
true
6d5034c6c8fd2c38cae3a8bd2fb63478fc782716
813ef6d1e49b37bcb52e4c1250a5a4e64bb8d94d
v1.0
instruct
Data_Structure
Data_Structure_31170_I
You are given an implementation of the Diffie-Hellman key exchange algorithm. Your task is to enhance this implementation by introducing secure prime generation and validating the inputs thoroughly. ### Function Signature ```python def diffie_hellman_secure_key_exchange(a: int, p: int, option: int=None) -> bool: p...
import random def is_prime(n, k=5): """ Test if a number is prime using the Miller-Rabin test. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0: return False # Find d such that d * 2^r = n-1 r, d = 0, n - 1 while d % 2 == 0: r += 1 d ...
from solution import diffie_hellman_secure_key_exchange, is_prime, find_primitive_root, is_primitive_root def test_is_prime(): assert is_prime(2) == True assert is_prime(4) == False assert is_prime(7919) == True def test_find_primitive_root(): assert find_primitive_root(23) == 5 assert find_primit...
[ { "docstring": "Test if a number is prime using the Miller-Rabin test. ", "function_declaration": "def is_prime(n, k=5):", "function_name": "is_prime", "parameter_list": "(n, k=5)" }, { "docstring": "Find a primitive root for prime p. This is a simple method and might not work for larger pri...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_prime(n, k=5):\n \"\"\" Test if a number is prime using the Miller-Rabin test. \"\"\"\n if n <= 1:\n return False\n if...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00031170", "row_id": 31170, "seed_ids": "[146]" }
0.465277
Data_Structure_31170
I
[ "is_prime", "find_primitive_root", "is_coprime", "diffie_hellman_secure_key_exchange", "is_primitive_root" ]
5
[ [ "diffie_hellman_secure_key_exchange", "is_prime" ], [ "diffie_hellman_secure_key_exchange", "is_primitive_root" ], [ "find_primitive_root", "is_coprime" ], [ "find_primitive_root", "is_prime" ], [ "is_primitive_root", "is_prime" ] ]
5
[]
false
[]
false
pytest
true
[]
true
0d2a76f35dc8fe865884aeaef82c3dd144c1a9be
1db546efbc29cace3ee628a4033b36c433286af8
v1.0
instruct
Data_Structure
Data_Structure_31242_I
### Scenario: You are tasked with developing a search functionality for an academic database that finds and ranks research papers based on their similarity to a given query paper. To achieve this, you need to calculate the cosine similarity between the word frequency vectors of the papers. ### Task: Write a function `...
from typing import List import math def _l2_distance(vec: List[float]) -> float: """ Calculate the L2 norm (Euclidean norm) of a vector. """ return math.sqrt(sum(x * x for x in vec)) def cosine_similarity(vec1: List[float], vec2: List[float]) -> float: """ Calculate the cosine similarity betwe...
from solution import cosine_similarity def test_cosine_similarity_identical_vectors(): assert math.isclose(cosine_similarity([1, 1, 1], [1, 1, 1]), 1.0, rel_tol=1e-9) def test_cosine_similarity_orthogonal_vectors(): assert math.isclose(cosine_similarity([1, 0], [0, 1]), 0.0, rel_tol=1e-9) def test_cosine_sim...
[ { "docstring": "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 word frequency vectors.", "function_declaratio...
[ 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\nimport math\n\ndef _l2_distance(vec: List[float]) -> float:\n \"\"\"\n Calculate the L2 norm (Euclidean norm) of a vector.\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00031242", "row_id": 31242, "seed_ids": "[149]" }
0.690031
Data_Structure_31242
I
[ "_l2_distance", "cosine_similarity" ]
2
[ [ "cosine_similarity", "_l2_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d7e9ed9627da83f2dda1a4671c72a69e08d154bd
9227d70e22f34fce66098f867549eea13bb32e29
v1.0
instruct
Data_Structure
Data_Structure_31247_I
### Objective Assume you are tasked with sorting a library's catalog system. The basic sorting mechanism available is extremely underperforming, known as Stooge Sort. Below is its implementation. Your goal is to fix any errors in the provided code and optimize its functionality as needed. Also, implement a function to ...
def stoogesort(arr, l, h): """ Function to perform Stooge Sort on the array """ if l >= h: return # If first element is greater than the last, swap them if arr[l] > arr[h]: arr[l], arr[h] = arr[h], arr[l] # If there are more than 2 elements in the array segment if h - l...
from solution import stoogesort, check_sort, compare_to_builtin_sort def test_stooge_sort(): arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] expected_output = sorted(arr) stoogesort(arr, 0, len(arr) - 1) assert arr == expected_output def test_check_sort_true(): assert check_sort([1, 2, 3, 4, 5]) == True ...
[ { "docstring": "Function to perform Stooge Sort on the array", "function_declaration": "def stoogesort(arr, l, h):", "function_name": "stoogesort", "parameter_list": "(arr, l, h)" }, { "docstring": "Function to check if the array is sorted in non-decreasing order", "function_declaration"...
[ 0, 0, 0, 1, 1, 0, 1, 1, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def stoogesort(arr, l, h):\n if l >= h:\n return\n\n # If first element is greater than last, swap them\n if arr[l] > arr[h]:\n arr[l],...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00031247", "row_id": 31247, "seed_ids": "[10]" }
0.563681
Data_Structure_31247
I
[ "stoogesort", "check_sort", "compare_to_builtin_sort" ]
3
[ [ "compare_to_builtin_sort", "stoogesort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1ade6a9f0eb72c2d3df2032398a74a71633ee64b
7c65b084ad5f393db50340801a6fe9466e2aa1a9
v1.0
instruct
Data_Structure
Data_Structure_31279_I
### Question: Implement Huffman Coding for Data Compression Given an input file, implement the Huffman Coding algorithm to encode the file's content and then decode the file back to its original content to verify that the lossless compression works correctly. The main tasks are to: 1. Calculate the frequency of each c...
import heapq import os from collections import defaultdict, Counter import pickle class Node: def __init__(self, char=None, freq=None, left=None, right=None): self.char = char self.freq = freq self.left = left self.right = right def __lt__(self, other): return s...
import os from solution import encode_file, decode_file def test_huffman_coding(): input_content = "hello huffman" input_filename = "test_input.txt" encoded_filename = "test_encoded.bin" decoded_filename = "test_decoded.txt" with open(input_filename, "w") as file: file.write(input_cont...
[]
[ 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 heapq\nfrom collections import Counter, defaultdict\nimport pickle\n\nclass HuffmanNode:\n def __init__(self, symbol=None, freq=0):\n self.sy...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00031279", "row_id": 31279, "seed_ids": "[335]" }
0.499999
Data_Structure_31279
I
[ "build_huffman_tree", "build_codes", "encode_text", "pad_encoded_text", "to_bytearray", "encode_file", "remove_padding", "decode_text", "decode_file" ]
9
[ [ "decode_file", "decode_text" ], [ "decode_file", "remove_padding" ], [ "encode_file", "build_codes" ], [ "encode_file", "build_huffman_tree" ], [ "encode_file", "encode_text" ], [ "encode_file", "pad_encoded_text" ], [ "encode_file", ...
7
[]
false
[ "Node" ]
true
pytest
true
[]
true
1f1e4a41f38433215e45420548005317875fdb0c
4805c2d4dd74d490095851e1731663dd4366e0d2
v1.0
instruct
Data_Structure
Data_Structure_31484_I
### Context Merge Sort is a popular sorting algorithm known for its efficiency and simplicity. In this task, you are required to implement the Merge Sort algorithm to sort an array of integers in ascending order. ### Problem Statement You need to implement the following functions: 1. `merge_sort(arr)`: which takes a...
def merge_sort(arr): """ Sorts the array 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:]) merged = [] merge(left_half, right_half, merged) return merged...
from solution import merge_sort, merge def test_merge_sort_empty_array(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] assert merge_sort([5]) == [5] def test_merge_sort_sorted_array(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_m...
[ { "docstring": "Sorts the array using the merge sort algorithm.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merges two sorted arrays into a single sorted array.", "function_declaration": "def merge(left, ri...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array of integers using the merge sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n \...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00031484", "row_id": 31484, "seed_ids": "[12]" }
0.703361
Data_Structure_31484
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
839a32f199b4a53f3dbc874fa96610c9ad73b9ad
ca0f44ee221cee8683eef710de137bbead9785d3
v1.0
instruct
Data_Structure
Data_Structure_31491_I
### Inverse Matrix Finder You are tasked with implementing a function that finds the inverse of a given n x n invertible matrix. The matrix will be represented as a list of lists, where each inner list represents a row of the matrix. ### Function Signature ```python def invert_matrix(matrix: List[List[float]]) -> Li...
from typing import List def get_determinant(matrix: List[List[float]]) -> float: n = len(matrix) if n == 1: return matrix[0][0] # Base case for 2x2 matrix if n == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] determinant = 0 for c in range(n): det...
from solution import invert_matrix def test_invert_2x2_matrix(): matrix = [ [4, 7], [2, 6] ] result = invert_matrix(matrix) expected = [ [0.6, -0.7], [-0.2, 0.4] ] for i in range(2): for j in range(2): assert abs(result[i][j] - expected[i][j])...
[ { "docstring": null, "function_declaration": "def get_determinant(matrix):", "function_name": "get_determinant", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def get_minor(matrix, i, j):", "function_name": "get_minor", "parameter_list": "(matrix, ...
[ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef get_determinant(matrix: List[List[float]]) -> float:\n \"\"\"\n This function calculates the determinant of a given squar...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00031491", "row_id": 31491, "seed_ids": "[347]" }
0.560605
Data_Structure_31491
I
[ "get_determinant", "get_minor", "get_matrix_of_minors", "transpose_and_multiply", "invert_matrix" ]
5
[ [ "get_determinant", "get_minor" ], [ "get_matrix_of_minors", "get_determinant" ], [ "get_matrix_of_minors", "get_minor" ], [ "invert_matrix", "get_determinant" ], [ "invert_matrix", "get_matrix_of_minors" ], [ "invert_matrix", "transpose_and_multi...
6
[]
false
[]
false
pytest
true
[]
true
7e7e682ac7e4d30317a16b11d02c1d54f68670cf
33918ea5b1b86624a6054df79a5102322c5bb0a1
v1.0
instruct
Data_Structure
Data_Structure_31546_I
You are given a matrix \(A\) of size \(n \times n\) where \(n\) is an integer. You need to compute the power of the matrix \(A^p\) where \(p\) is also an integer. The matrix exponentiation should be performed using efficient algorithms instead of direct multiplication to ensure better performance. ### Tasks: 1. Imple...
from typing import List def multiply(matA: List[List[int]], matB: List[List[int]]) -> List[List[int]]: n = len(matA) result = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): for k in range(n): result[i][j] += matA[i][k] * matB[k][j] return result d...
from solution import multiply, identity, matrix_exponentiation def test_multiply_basic(): matA = [ [1, 2], [3, 4] ] matB = [ [5, 6], [7, 8] ] assert multiply(matA, matB) == [ [19, 22], [43, 50] ] def test_identity_matrix(): assert identity(3)...
[ { "docstring": null, "function_declaration": "def multiply(matA, matB):", "function_name": "multiply", "parameter_list": "(matA, matB)" }, { "docstring": null, "function_declaration": "def identity(n):", "function_name": "identity", "parameter_list": "(n)" }, { "docstring...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef multiply(matA: List[List[int]], matB: List[List[int]]) -> List[List[int]]:\n n = len(matA)\n result = [[0] * n for _ in r...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00031546", "row_id": 31546, "seed_ids": "[340]" }
0.501681
Data_Structure_31546
I
[ "multiply", "identity", "matrix_exponentiation" ]
3
[ [ "matrix_exponentiation", "identity" ], [ "matrix_exponentiation", "multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
eb2b2460aa8b58f8b66f66e7168977e6d20c3e23
337a8ac17a665e31c0289cc6262aedc12c7bc248
v1.0
instruct
Data_Structure
Data_Structure_31553_I
Implementing Improved Merge Sort #### Scenario: You are tasked with optimizing an e-commerce platform's backend system for efficiently sorting large lists of products based on their prices. The platform often needs to handle sorting jobs that involve millions of entries. To achieve this, you'll use the merge sort algo...
def merge_sort_optimized(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort_optimized(arr[:mid]) right = merge_sort_optimized(arr[mid:]) return merge(left, right) def merge(left, right): merged_array = [] left_index, right_index = 0, 0 while left_index <...
from solution import merge_sort_optimized def test_empty_list(): assert merge_sort_optimized([]) == [] def test_single_element_list(): assert merge_sort_optimized([5]) == [5] def test_sorted_list(): assert merge_sort_optimized([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_list(): asser...
[ { "docstring": null, "function_declaration": "def merge_sort_optimized(arr):", "function_name": "merge_sort_optimized", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)"...
[ 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 merge_sort_optimized(arr: list) -> list:\n \"\"\"\n Perform a memory-optimized merge sort on the input list.\n \"\"\"\n if len(arr) <= 1:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00031553", "row_id": 31553, "seed_ids": "[12]" }
0.530219
Data_Structure_31553
I
[ "merge_sort_optimized", "merge" ]
2
[ [ "merge_sort_optimized", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2ec173ea51009688f20f3b5a8875033b9fe0c49d
3b5ebad9f2d2dea1a47b0b88471fef03b0cfdc24
v1.0
instruct
Data_Structure
Data_Structure_31607_I
### Question: You are tasked with implementing your version of RSA key generation and encrypt/decrypt operations. Using the information provided, complete the functions to meet the following requirements: #### Part 1: Generate Key Implement the `generate_key(bits)` function. - **Input**: `bits` - an integer, the numb...
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(bits): """ Generate RSA key pair. Parameters: bits (int): numb...
from solution import generate_key, encrypt, decrypt def test_key_generation(): n, e, d = generate_key(16) assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) assert e != d def test_encrypt_decrypt(): n, e, d = generate_key(16) data = 20 encrypted = encrypt(dat...
[ { "docstring": null, "function_declaration": "def generate_prime(bits):", "function_name": "generate_prime", "parameter_list": "(bits)" }, { "docstring": "Generate RSA key pair.\n\nParameters:\nbits (int): number of bits in modulus n\n\nReturns:\ntuple: (n, e, d) where n is the modulus, e is...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime_candidate(bits):\n p = random.getrandbits(bits)\n # Make sure p is odd\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00031607", "row_id": 31607, "seed_ids": "[154]" }
0.643031
Data_Structure_31607
I
[ "generate_prime", "generate_key", "encrypt", "decrypt" ]
4
[ [ "generate_key", "generate_prime" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
cd1a91b11f13b8b517033b62cca471958039272b
2e7a472aff0ab4016fdf885f5f609a8d7f944c81
v1.0
instruct
Data_Structure
Data_Structure_31632_I
**Title**: Efficient GCD and LCM with Edge Case Handling **Objective**: In this question, you must implement functions to calculate the greatest common divisor (GCD) and the least common multiple (LCM) of two integers. Additionally, you will implement a function to count trailing zeroes in the binary representation of...
def gcd(a: int, b: int) -> int: """ Computes the greatest common divisor of a and b using the Euclidean algorithm """ while b: a, b = b, a % b return abs(a) def lcm(a: int, b: int) -> int: """ Computes the least common multiple of a and b using the relationship lcm(a, b) = abs(a * b) / gcd(a, b...
from solution import gcd, lcm, trailing_zeroes, gcd_bit def test_gcd(): assert gcd(48, 18) == 6 assert gcd(-48, 18) == 6 assert gcd(0, 18) == 18 assert gcd(18, 0) == 18 assert gcd(0, 0) == 0 def test_lcm(): assert lcm(4, 5) == 20 assert lcm(18, 48) == 144 assert lcm(-4, 5) == 20 as...
[ { "docstring": "Computes the greatest common divisor of a and b using the Euclidean algorithm ", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Computes the least common multiple of a and b using the relationship lcm(a, b) = ab...
[ 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 two integers using the Euclidean algorithm.\n \"\"\"\n while b:...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00031632", "row_id": 31632, "seed_ids": "[166]" }
0.636838
Data_Structure_31632
I
[ "gcd", "lcm", "trailing_zeroes", "gcd_bit" ]
4
[ [ "gcd_bit", "trailing_zeroes" ], [ "lcm", "gcd" ] ]
2
[]
false
[]
false
pytest
true
[]
true
741d5e0a07c55ee35bc0fee38c43d0a9fb40d071
b876ad1e717f78787fb0ca6b6364aad4e3e557e1
v1.0
instruct
Data_Structure
Data_Structure_31643_I
### Selection Sort and Prime Check Integration #### Objective Your task is to combine the Selection Sort algorithm with a functionality to check the prime numbers within the list. #### Problem Statement Implement a function `selection_sort_and_count_primes(arr: List[int]) -> Tuple[List[int], int]` that performs the ...
from typing import List, Tuple def is_prime(n: int) -> bool: """ Helper function to check if a number is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + ...
from solution import selection_sort_and_count_primes def test_example_cases(): assert selection_sort_and_count_primes([29, 10, 14, 37, 13]) == ([10, 13, 14, 29, 37], 3) assert selection_sort_and_count_primes([5, 4, 3, 2, 1]) == ([1, 2, 3, 4, 5], 3) def test_empty_array(): assert selection_sort_and_cou...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Sorts the list using Selection Sort and counts the prime numbers in the list.", "function_declaration": "de...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Checks if a number n is prime.\n \"\"\"\n if n <= 1:\n return Fa...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00031643", "row_id": 31643, "seed_ids": "[18]" }
0.687026
Data_Structure_31643
I
[ "is_prime", "selection_sort_and_count_primes" ]
2
[ [ "selection_sort_and_count_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
aca2f503ef3aa623e0d1ab9b759150da580c6f30
7ce3810910f1954b2fddc623ff994ac9a843a499
v1.0
instruct
Data_Structure
Data_Structure_31775_I
**Merge Sort Variation Implementation** You have been tasked with improving the performance of the merge sort implementation provided. The original implementation has a recursive merge sort coupled with a support function for merging. The goal is to implement an iterative version of merge sort to avoid the additional ...
def iterative_merge_sort(arr): """ Perform an iterative merge sort on the provided array. :param arr: List of integers to be sorted :return: Sorted list of integers in non-decreasing order """ if len(arr) <= 1: return arr width = 1 n = len(arr) while width < n: ...
from solution import iterative_merge_sort def test_iterative_merge_sort_example_case(): assert iterative_merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] def test_iterative_merge_sort_single_element(): assert iterative_merge_sort([1]) == [1] def test_iterative_merge_sort_sorted_list(): ...
[ { "docstring": "Perform an iterative merge sort on the provided array.\n\n:param arr: List of integers to be sorted\n:return: Sorted list of integers in non-decreasing order", "function_declaration": "def iterative_merge_sort(arr):", "function_name": "iterative_merge_sort", "parameter_list": "(arr)"...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def iterative_merge_sort(arr):\n \"\"\"\n Sorts an array of integers in non-decreasing order using an iterative merge sort algorithm.\n \"\"\"\n i...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00031775", "row_id": 31775, "seed_ids": "[12]" }
0.62155
Data_Structure_31775
I
[ "iterative_merge_sort", "merge" ]
2
[ [ "iterative_merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3aa127b3114c44679082fa09140e3f3789af996b
a1a151a02b754c2b7948331b3c8fd5bb4835b4ce
v1.0
instruct
Data_Structure
Data_Structure_31817_I
### Diffie-Hellman with Error Handling You are to implement a function in Python that ensures the secure exchange of keys between two parties using the Diffie-Hellman key exchange protocol. The primes and coprimes must be validated, and any inconsistency or error in input should result in a clear and descriptive error...
import random from sympy import isprime, primerange def diffie_hellman_secure(a: int, p: int, verbose: bool = False) -> None: if not is_valid_prime(p): print(f"Error: {p} is not a prime number.") return if not is_primitive_root(a, p): print(f"Error: {a} is not a primitive root of {p}.")...
from solution import diffie_hellman_secure, is_valid_prime, is_primitive_root def test_prime_check(): assert is_valid_prime(11) == True assert is_valid_prime(15) == False def test_primitive_root_check(): assert is_primitive_root(2, 11) == True assert is_primitive_root(2, 15) == False def test_diffie_...
[ { "docstring": null, "function_declaration": "def diffie_hellman_secure(a, p, verbose=False):", "function_name": "diffie_hellman_secure", "parameter_list": "(a, p, verbose=False)" }, { "docstring": null, "function_declaration": "def is_valid_prime(n):", "function_name": "is_valid_pri...
[ 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 is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00031817", "row_id": 31817, "seed_ids": "[146]" }
0.526871
Data_Structure_31817
I
[ "diffie_hellman_secure", "is_valid_prime", "is_primitive_root", "gcd" ]
4
[ [ "diffie_hellman_secure", "is_primitive_root" ], [ "diffie_hellman_secure", "is_valid_prime" ], [ "is_primitive_root", "gcd" ] ]
3
[]
false
[]
false
pytest
true
[ "sympy" ]
false
256dbd5ec64c108f7e17b1818747e36875bd82f1
a3e2328a79dc2128a8a9fc8bd3fc6c23a57d5c82
v1.0
instruct
Data_Structure
Data_Structure_31887_I
**Matrix Inversion Function** Given a square matrix, the task is to implement a function that computes its inverse. This problem requires a deep understanding of matrix operations and determinants. Your implementation should be robust and efficiently handle edge cases. ### Function Signature ```python def invert_mat...
from typing import List def get_matrix_minor(matrix: List[List[float]], i: int, j: int) -> List[List[float]]: return [ [row[k] for k in range(len(matrix)) if k != j] for row in (matrix[r] for r in range(len(matrix)) if r != i) ] def get_matrix_determinant(matrix: List[List[float]]) -> float: ...
from solution import invert_matrix def test_valid_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_valid_3x3_matrix(): matrix = [ [1, 2, 3], [0, 1, 4...
[ { "docstring": null, "function_declaration": "def get_matrix_minor(matrix, i, j):", "function_name": "get_matrix_minor", "parameter_list": "(matrix, i, j)" }, { "docstring": null, "function_declaration": "def get_matrix_determinant(matrix):", "function_name": "get_matrix_determinant"...
[ 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 get_matrix_minor(matrix: List[List[float]], i: int, j: int) -> List[List[float]]:\n return [\n [row[k] for k in range...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00031887", "row_id": 31887, "seed_ids": "[347]" }
0.58373
Data_Structure_31887
I
[ "get_matrix_minor", "get_matrix_determinant", "get_matrix_inverse", "invert_matrix" ]
4
[ [ "get_matrix_determinant", "get_matrix_minor" ], [ "get_matrix_inverse", "get_matrix_determinant" ], [ "get_matrix_inverse", "get_matrix_minor" ], [ "invert_matrix", "get_matrix_inverse" ] ]
4
[]
false
[]
false
pytest
true
[]
true
2da803bfe6056689c4ca4e5e86a14ccd6af095ee
ec617099bd7fc7693a671467bb6aef607d1383b1
v1.0
instruct
Data_Structure
Data_Structure_31891_I
### Context You are tasked with implementing a dynamic algorithm for solving a problem involving matrix operations in a scientific computing application. As part of this, you need to create a function that efficiently computes the n-th power of a matrix by exploiting properties of matrix multiplication and the identity...
def identity_matrix(size): """Creates an identity matrix of given size.""" return [[1 if i == j else 0 for j in range(size)] for i in range(size)] def matrix_multiply(A, B): """Multiplies two matrices A and B.""" size = len(A) result = [[0] * size for _ in range(size)] for i in range(size): ...
from solution import matrix_exponentiation, identity_matrix, matrix_multiply def test_identity_matrix(): assert identity_matrix(2) == [ [1, 0], [0, 1] ] def test_matrix_multiply(): A = [ [1, 2], [3, 4] ] B = [ [2, 0], [1, 2] ] assert matrix_m...
[ { "docstring": "Creates an identity matrix of given size.", "function_declaration": "def identity_matrix(size):", "function_name": "identity_matrix", "parameter_list": "(size)" }, { "docstring": "Multiplies two matrices A and B.", "function_declaration": "def matrix_multiply(A, B):", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def matrix_multiply(A, B):\n \"\"\"\n Multiplies two square matrices A and B.\n \"\"\"\n n = len(A)\n C = [[0] * n for _ in range(n)]\n for ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00031891", "row_id": 31891, "seed_ids": "[340]" }
0.519397
Data_Structure_31891
I
[ "identity_matrix", "matrix_multiply", "matrix_exponentiation" ]
3
[ [ "matrix_exponentiation", "identity_matrix" ], [ "matrix_exponentiation", "matrix_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e5777045fe093e53ab31cc681b81c179d4b62423
6343e1376dbee6e19d4350168f513aad79eb3749
v1.0
instruct
Data_Structure
Data_Structure_31993_I
#### Prime Number Summation and Count Introduction: Prime numbers are fundamental in number theory and have many applications in cryptography, algorithms, and scientific computations. In this task, you will write a Python function that identifies prime numbers from a list and computes specific outputs based on them. ...
def prime_check(n): """Check if a number is a prime or not.""" if n <= 1: return False if n == 2: return True if n % 2 == 0: return False p = 3 while p * p <= n: if n % p == 0: return False p += 2 return True def sum_and_count_primes(numbe...
from solution import sum_and_count_primes def test_sum_and_count_primes_example1(): assert sum_and_count_primes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == (17, 4) def test_sum_and_count_primes_example2(): assert sum_and_count_primes([-10, -3, 0, 1, 2]) == (2, 1) def test_sum_and_count_primes_no_primes(): assert...
[ { "docstring": "Check if a number is a prime or not.", "function_declaration": "def prime_check(n):", "function_name": "prime_check", "parameter_list": "(n)" }, { "docstring": "Identifies prime numbers from a list and computes the sum and count of primes.\n\nArgs:\nnumbers: List of integers....
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00031993", "row_id": 31993, "seed_ids": "[143]" }
0.726822
Data_Structure_31993
I
[ "prime_check", "sum_and_count_primes" ]
2
[ [ "sum_and_count_primes", "prime_check" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cd6b639643129409bc090b9c44f3ef85d554620f
bd292b9003aea174023ad0b96c5ce83962af8b91
v1.0
instruct
Data_Structure
Data_Structure_32035_I
### Scenario: You are working on a scientific computational library that assists researchers in performing numerical computations efficiently. One key feature of your library is matrix operations, specifically matrix inversion. Given the importance of dealing with matrix inversions optimally and correctly, you need to ...
from typing import List def determinant(matrix: List[List[float]], n: int) -> float: if n == 1: return matrix[0][0] if n == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] det = 0 for c in range(n): det += ((-1) ** c) * matrix[0][c] * determinant(get_min...
from solution import invert_matrix def test_invert_matrix_2x2(): matrix = [ [4, 7], [2, 6] ] expected = [ [0.6, -0.7], [-0.2, 0.4] ] result = invert_matrix(matrix) assert result == expected def test_invert_matrix_non_square(): matrix = [ [1, 2, 3], ...
[ { "docstring": null, "function_declaration": "def determinant(matrix, n):", "function_name": "determinant", "parameter_list": "(matrix, n)" }, { "docstring": null, "function_declaration": "def get_minor(matrix, i, j):", "function_name": "get_minor", "parameter_list": "(matrix, i,...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef invert_matrix(matrix: List[List[float]]) -> List[List[float]]:\n if not isinstance(matrix, list) or not all(isinstance(row, ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00032035", "row_id": 32035, "seed_ids": "[347]" }
0.549185
Data_Structure_32035
I
[ "determinant", "get_minor", "invert_matrix" ]
3
[ [ "determinant", "get_minor" ], [ "invert_matrix", "determinant" ], [ "invert_matrix", "get_minor" ] ]
3
[]
false
[]
false
pytest
true
[]
true
bf93f3d9dcdfcb8eed2e2d01dae64be514a0ab60
b315322914cdb85289ea8792ae4f10a311b44f25
v1.0
instruct
Data_Structure
Data_Structure_32075_I
### Diffie-Hellman Key Exchange Implementation #### Background: Diffie-Hellman Key Exchange is a cryptographic method enabling two parties to securely share a common secret key over an unsecured channel. This method is foundational in securing communication protocols like SSL/TLS. #### Task: Implement a more secured ...
import random def is_prime(n): """Return True if n is a prime number.""" if n == 2 or n == 3: return True if n <= 1 or n % 2 == 0: return False if n < 9: return True if n % 3 == 0: return False r = int(n**0.5) step = 2 for f in range(5, r + 1, step): ...
from solution import diffie_hellman_key_exchange_v2 def test_diffie_hellman_valid_example1(): a = 5 p = 23 assert diffie_hellman_key_exchange_v2(a, p) == True def test_diffie_hellman_valid_example2(): a = 2 p = 11 assert diffie_hellman_key_exchange_v2(a, p) == True def test_diffie_hellman_inv...
[ { "docstring": "Return True if n is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { ...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.111
{ "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 \"\"\"Checks if a number is a prime using the Miller-Rabin primality test.\"\"\"\n if n <= 1:\n return False\...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00032075", "row_id": 32075, "seed_ids": "[146]" }
0.519394
Data_Structure_32075
I
[ "is_prime", "gcd", "find_primitive_root", "diffie_hellman_key_exchange_v2" ]
4
[ [ "diffie_hellman_key_exchange_v2", "find_primitive_root" ], [ "diffie_hellman_key_exchange_v2", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
44bd5181fdcaa16b91b34906dc22d0715262c8a7
7520150068e60dd1501af87add39615f5a06076c
v1.0
instruct
Data_Structure
Data_Structure_32084_I
### Question Implement a function called `optimized_cosine_similarity` that calculates the cosine similarity between two vectors but also incorporates precomputation for scenarios where the same vectors might be used frequently. The function should handle the essential calculations just as described for `cosine_similar...
import math from typing import List, Optional def l2_distance(vec: List[float]) -> float: """ Compute the L2 distance (Euclidean norm) of a vector. """ return math.sqrt(sum([x**2 for x in vec])) def optimized_cosine_similarity(vec1: List[float], vec2: List[float], norm1: Optional[float] = None, norm2:...
from solution import optimized_cosine_similarity, l2_distance def test_optimized_cosine_similarity_with_precomputed_norms(): vec1 = [3, 4] vec2 = [4, -7] norm1 = l2_distance(vec1) norm2 = l2_distance(vec2) result = optimized_cosine_similarity(vec1, vec2, norm1, norm2) expected = ((3*4) + (4*-7)...
[ { "docstring": "Compute the L2 distance (Euclidean norm) of a vector.", "function_declaration": "def l2_distance(vec):", "function_name": "l2_distance", "parameter_list": "(vec)" }, { "docstring": "Compute the cosine similarity between two vectors, optionally using precomputed norms.\n\n:par...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom typing import List, Optional\n\ndef l2_distance(vec: List[float]) -> float:\n \"\"\"\n Compute the L2 distance (Euclidean norm) of a v...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00032084", "row_id": 32084, "seed_ids": "[149]" }
0.590104
Data_Structure_32084
I
[ "l2_distance", "optimized_cosine_similarity" ]
2
[ [ "optimized_cosine_similarity", "l2_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fbffa3ec8f792a51991fe87b3724af3ffc35cb68
6a28c135d9a048daef9b69e776fde7e496fdc1db
v1.0
instruct
Data_Structure
Data_Structure_32091_I
### Nearest Neighbor Classification Given the implementation of the nearest neighbor algorithm provided, your task is to complete and optimize the `nearest_neighbor_improved` function. This function should classify an input vector `x` by finding the nearest neighbor within a given training set `tSet` (dictionary where...
import math def euclidean_distance(v1, v2): """ Calculate and return the Euclidean distance between two vectors. """ return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2))) def nearest_neighbor_improved(x, tSet): """ Classify the input vector x by finding the nearest neighbor in tSet. ...
from solution import nearest_neighbor_improved def test_nearest_neighbor_basic_case(): x = (1.0, 2.0, 1.5) tSet = { (1.0, 2.0, 1.0): 'cat', (2.0, 3.0, 2.0): 'dog', (0.0, 1.0, 0.5): 'mouse' } assert nearest_neighbor_improved(x, tSet) == 'cat' def test_nearest_neighbor_another_...
[ { "docstring": "Calculate and return the Euclidean distance between two vectors.", "function_declaration": "def euclidean_distance(v1, v2):", "function_name": "euclidean_distance", "parameter_list": "(v1, v2)" }, { "docstring": "Classify the input vector x by finding the nearest neighbor in ...
[ 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 nearest_neighbor_improved(x, tSet):\n \"\"\"\n Classify input vector x by finding the nearest neighbor within a given training set tS...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00032091", "row_id": 32091, "seed_ids": "[260]" }
0.62422
Data_Structure_32091
I
[ "euclidean_distance", "nearest_neighbor_improved" ]
2
[ [ "nearest_neighbor_improved", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c5f41931bb6589d3ef1eef28153689ee39493dfc
059c365bad8045b1c779326ca46ede69eb22f7fc
v1.0
instruct
Data_Structure
Data_Structure_32096_I
### Context: As the head of a cybersecurity project, you need to develop an encryption system using the RSA algorithm. The primary focus is designing a robust key generation mechanism while ensuring encryption and decryption of data works seamlessly based on the generated keys. ### Task: You are required to implement ...
import random from sympy import isprime from math import gcd def generate_large_prime(bits): while True: p = random.getrandbits(bits) if isprime(p): return p def mod_inverse(e, phi): gcd, x, y = extended_gcd(e, phi) if gcd != 1: raise Exception('Modular inverse does not...
from solution import generate_key, encrypt, decrypt def test_generate_key_sanity_check(): n, e, d = generate_key(16, seed=42) assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) def test_encrypt_decrypt_basic(): n, e, d = generate_key(16, seed=42) data = 42 en...
[ { "docstring": null, "function_declaration": "def generate_large_prime(bits):", "function_name": "generate_large_prime", "parameter_list": "(bits)" }, { "docstring": null, "function_declaration": "def mod_inverse(e, phi):", "function_name": "mod_inverse", "parameter_list": "(e, p...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime\nfrom math import gcd\n\ndef mod_exp(base, exp, modulus):\n result = 1\n while exp > 0:\n if exp % 2 == ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00032096", "row_id": 32096, "seed_ids": "[154]" }
0.670949
Data_Structure_32096
I
[ "generate_large_prime", "mod_inverse", "extended_gcd", "generate_key", "encrypt", "decrypt" ]
6
[ [ "generate_key", "generate_large_prime" ], [ "generate_key", "mod_inverse" ], [ "mod_inverse", "extended_gcd" ] ]
3
[]
false
[]
false
pytest
true
[ "sympy" ]
false
21033ad42a8237f6a6700e201df0f1ad916ffb28
ec03c7930eb71a50524361ae576f9dc31408f43a
v1.0
instruct
Data_Structure
Data_Structure_32117_I
### Question: Computing Extended GCD and LCM with Additional Functionalities You are tasked to design a comprehensive function suite to compute the Greatest Common Divisor (GCD), Least Common Multiple (LCM), and the number of trailing zeros in the binary form of a number. Additionally, you are to compute the GCD using...
def gcd(a: int, b: int) -> int: """ Compute the GCD of two integers using the Euclidean algorithm. """ while b: a, b = b, a % b return a def lcm(a: int, b: int) -> int: """ Compute the LCM of two integers using their GCD. The formula is: lcm(a, b) = abs(a*b) // gcd(a, b) """...
import pytest from solution import gcd, lcm, trailing_zero, gcd_bit def test_gcd(): assert gcd(8, 12) == 4 assert gcd(14, 21) == 7 assert gcd(101, 103) == 1 assert gcd(0, 5) == 5 assert gcd(7, 0) == 7 def test_lcm(): assert lcm(8, 12) == 24 assert lcm(14, 21) == 42 assert lcm(101, 103)...
[ { "docstring": "Compute the GCD of two integers using the Euclidean algorithm.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Compute the LCM of two integers using their GCD.\nThe formula is: lcm(a, b) = abs(a*b) // gcd(a, b)...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def gcd(a, b):\n \"\"\"Computes the Greatest Common Divisor (GCD) of two numbers a and b.\"\"\"\n while b:\n a, b = b, a % b\n return a\n\ndef...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00032117", "row_id": 32117, "seed_ids": "[166]" }
0.639582
Data_Structure_32117
I
[ "gcd", "lcm", "trailing_zero", "gcd_bit" ]
4
[ [ "gcd_bit", "trailing_zero" ], [ "lcm", "gcd" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f7ba8f00d34d8f81918d1001f1a3bc2329e42fb2
3c76e3a0c0384ecd24d2ec3cde64fad2f54bd1c5
v1.0
instruct
Data_Structure
Data_Structure_32175_I
### House Robber Problem with Enhanced Challenge You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, but the only constraint stopping you from robbing each of them is that adjacent houses have a security system connected, and it will automatically cont...
from typing import List def house_robber_linear(houses: List[int]) -> int: if not houses: return 0 if len(houses) == 1: return houses[0] prev1, prev2 = 0, 0 for house in houses: current = max(house + prev2, prev1) prev2 = prev1 prev1 = current r...
from solution import house_robber_circular def test_house_robber_circular_example1(): houses = [2, 3, 2] assert house_robber_circular(houses) == 3 def test_house_robber_circular_example2(): houses = [1, 2, 3, 1] assert house_robber_circular(houses) == 4 def test_house_robber_circular_empty(): hou...
[ { "docstring": null, "function_declaration": "def house_robber_linear(houses):", "function_name": "house_robber_linear", "parameter_list": "(houses)" }, { "docstring": null, "function_declaration": "def house_robber_circular(houses):", "function_name": "house_robber_circular", "p...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef house_robber_linear(houses: List[int]) -> int:\n if not houses:\n return 0\n if len(houses) == 1:\n return ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00032175", "row_id": 32175, "seed_ids": "[33]" }
0.590754
Data_Structure_32175
I
[ "house_robber_linear", "house_robber_circular" ]
2
[ [ "house_robber_circular", "house_robber_linear" ] ]
1
[]
false
[]
false
pytest
true
[]
true
578f17d47129ec49eceeffbe0de3d59a10d445c8
d655939be6d773a2740d6ceb502a2666c3fc58ae
v1.0
instruct
Data_Structure
Data_Structure_32241_I
### Advanced Cryptographic Algorithm Assessment You are working for a cryptography firm and have been tasked with enhancing the efficiency and reliability of certain fundamental algorithms. These algorithms are critical for the proper functioning of cryptographic protocols and ensuring the security of encrypted commun...
import math from typing import List def find_order(a: int, n: int) -> int: """ Returns the order (smallest positive integer k) of integer a modulo n. Output -1 if no order exists. """ if math.gcd(a, n) != 1: return -1 # No order if a and n are not coprime k = 1 value = a % n ...
import pytest from solution import find_order, euler_totient, find_primitive_root def test_find_order(): assert find_order(2, 7) == 3 assert find_order(3, 7) == 6 assert find_order(2, 6) == -1 # 2 and 6 are not coprime assert find_order(5, 9) == 6 def test_euler_totient(): assert euler_totient(1)...
[ { "docstring": "Returns the order (smallest positive integer k) of integer a modulo n.\nOutput -1 if no order exists.", "function_declaration": "def find_order(a, n):", "function_name": "find_order", "parameter_list": "(a, n)" }, { "docstring": "Euler's Totient function value φ(n) which coun...
[ 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\nimport math\nfrom collections import defaultdict\n\ndef find_order(a: int, n: int) -> int:\n \"\"\"\n Find the smallest k such ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00032241", "row_id": 32241, "seed_ids": "[160]" }
0.465563
Data_Structure_32241
I
[ "find_order", "euler_totient", "find_primitive_root" ]
3
[ [ "find_primitive_root", "euler_totient" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c8eb8ee94a32de32178883eaef3e00e61c6ec180
9c652a57dddc48cef10a21bd48bccc6fd57755e1
v1.0
instruct
Data_Structure
Data_Structure_32310_I
### IP Address Binary Representation **Context** You are tasked with creating a utility to help network engineers convert IPv4 addresses from their common dotted-decimal notation to a binary representation. This will help in tasks like subnetting, network analysis, and IP address management. **Objective** Write a fun...
def decimal_to_binary_util(val): """ Convert 8-bit decimal number to binary representation :type val: str or int :rtype: str """ val = int(val) return f'{val:08b}' def decimal_to_binary_ip(ip): """ Convert dotted-decimal ip address to binary representation with help of decimal_to_bi...
from solution import decimal_to_binary_ip, decimal_to_binary_util def test_decimal_to_binary_util(): assert decimal_to_binary_util("0") == "00000000" assert decimal_to_binary_util("1") == "00000001" assert decimal_to_binary_util("128") == "10000000" assert decimal_to_binary_util("255") == "11111111" d...
[ { "docstring": "Convert 8-bit decimal number to binary representation\n:type val: str or int\n:rtype: str", "function_declaration": "def decimal_to_binary_util(val):", "function_name": "decimal_to_binary_util", "parameter_list": "(val)" }, { "docstring": "Convert dotted-decimal ip address to...
[ 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 decimal_to_binary_util(val):\n \"\"\"\n Convert 8-bit decimal number to binary representation.\n :type val: str\n :rtype: str\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00032310", "row_id": 32310, "seed_ids": "[152]" }
0.518287
Data_Structure_32310
I
[ "decimal_to_binary_util", "decimal_to_binary_ip" ]
2
[ [ "decimal_to_binary_ip", "decimal_to_binary_util" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e86386fa7fcc6d5bba25ee4e744ee962cab29ea6
16ef430d9454b28f39c7f236eb15497ee7a13f3d
v1.0
instruct
Data_Structure
Data_Structure_32396_I
### Task You're given two two-dimensional matrices represented as lists of lists. Your task is to implement a function `optimized_multiply` to compute the product of these matrices using an optimized approach with a specific focus on reducing the time complexity from \(O(n^3)\) to \(O(n^{\log_2 7})\). ### Implementat...
def add_matrices(a, b): """ Adds two matrices element-wise. """ n = len(a) result = [[a[i][j] + b[i][j] for j in range(n)] for i in range(n)] return result def subtract_matrices(a, b): """ Subtracts two matrices element-wise. """ n = len(a) result = [[a[i][j] - b[i][j] for j...
from solution import optimized_multiply def test_basic_multiplication(): multiplicand = [[1, 2, 3], [4, 5, 6]] multiplier = [[7, 8], [9, 10], [11, 12]] expected = [[58, 64], [139, 154]] assert optimized_multiply(multiplicand, multiplier) == expected def test_incompatible_dimensions(): multiplicand...
[ { "docstring": "Adds two matrices element-wise.", "function_declaration": "def add_matrices(a, b):", "function_name": "add_matrices", "parameter_list": "(a, b)" }, { "docstring": "Subtracts two matrices element-wise.", "function_declaration": "def subtract_matrices(a, b):", "function...
[ 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 matrix_addition(A, B):\n \"\"\" Helper function to add two matrices. \"\"\"\n n = len(A)\n return [[A[i][j] + B[i][j] for j in range(n)] for i in...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00032396", "row_id": 32396, "seed_ids": "[343]" }
0.606531
Data_Structure_32396
I
[ "add_matrices", "subtract_matrices", "split_matrix", "strassen_multiply", "padded_matrix", "optimized_multiply" ]
6
[ [ "optimized_multiply", "padded_matrix" ], [ "optimized_multiply", "strassen_multiply" ], [ "strassen_multiply", "add_matrices" ], [ "strassen_multiply", "split_matrix" ], [ "strassen_multiply", "subtract_matrices" ] ]
5
[]
false
[]
false
pytest
true
[]
true
cc5857804ed9685015a074b1dd01261520bc3c2d
6fab18126687bd22b38e4c4dce317824daae8c07
v1.0
instruct
Data_Structure
Data_Structure_32405_I
### Diffie-Hellman Key Exchange with Additional Security In this exercise, you are required to implement the Diffie-Hellman Key Exchange protocol with additional security checks and optimizations. The goal is to ensure the secure exchange of keys between two entities, Alice and Bob, while maintaining the integrity and...
import random from math import gcd def is_prime(n: int) -> bool: if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return Tru...
from solution import is_prime, euler_totient, find_primitive_roots, prime_factors, generate_private_key, generate_public_key, compute_shared_key, diffie_hellman_key_exchange def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(29) == Tru...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def euler_totient(n):", "function_name": "euler_totient", "parameter_list": "(n)" }, { "docstring": null,...
[ 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 math import gcd\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Function to check if a given number n is prime.\n \n Parameters:\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00032405", "row_id": 32405, "seed_ids": "[146]" }
0.536433
Data_Structure_32405
I
[ "is_prime", "euler_totient", "find_primitive_roots", "prime_factors", "generate_private_key", "generate_public_key", "compute_shared_key", "diffie_hellman_key_exchange" ]
8
[ [ "diffie_hellman_key_exchange", "compute_shared_key" ], [ "diffie_hellman_key_exchange", "generate_private_key" ], [ "diffie_hellman_key_exchange", "generate_public_key" ], [ "find_primitive_roots", "euler_totient" ], [ "find_primitive_roots", "is_prime" ],...
6
[]
false
[]
false
pytest
true
[]
true
379f07bb5226716d22e8328abfc26bd527ea4029
0550805f0408a7d431a6c8a35e18ebac5af20c32
v1.0
instruct
Data_Structure
Data_Structure_32426_I
Enhanced Bogo Sort Analysis #### Context: Imagine you're teaching a class on sorting algorithms, and you have just demonstrated the infamous Bogo Sort to your students, highlighting its inefficiency. To reinforce their understanding of better sorting algorithms, you want them to compare Bogo Sort with an optimized sor...
import time import random from copy import deepcopy def quick_sort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quick_sort(left) + middle + quick_so...
from solution import compare_sorts def test_compare_sorts_with_small_array(): arr = [3, 2, 1] result = compare_sorts(arr) assert result["bogo_sort_time"] > 0 assert result["quick_sort_time"] > 0 assert isinstance(result["bogo_sort_terminated_early"], bool) def test_compare_sorts_with_empty_array()...
[ { "docstring": null, "function_declaration": "def quick_sort(arr):", "function_name": "quick_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def bogo_sort(arr, max_iterations=1000):", "function_name": "bogo_sort", "parameter_list": "(arr, max_ite...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport time\nfrom copy import deepcopy\n\ndef bogo_sort(arr, max_iterations=1000):\n iteration = 0\n\n def is_sorted(arr):\n for i...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00032426", "row_id": 32426, "seed_ids": "[16]" }
0.527563
Data_Structure_32426
I
[ "quick_sort", "bogo_sort", "compare_sorts" ]
3
[ [ "compare_sorts", "bogo_sort" ], [ "compare_sorts", "quick_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
794ac8d2ee695d59298cfae03b1f28d7dc252f2d
b7f1f0b231a15b82a1436c448d42a8555767c0b4
v1.0
instruct
Data_Structure
Data_Structure_32496_I
You are required to implement a function that finds the nearest neighbor of a given vector from a set of training vectors. Given a target vector `x` and a training set `tSet`, which is a dictionary of vectors as keys and labels as values, your task is to determine the label of the vector in `tSet` that is closest to `x...
import math def euclidean_distance(v1, v2): return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2))) def find_nearest_neighbor(x, tSet): nearest_label = None min_distance = float('inf') for vector, label in tSet.items(): distance = euclidean_distance(x, vector) if distance < mi...
from solution import find_nearest_neighbor def test_find_nearest_neighbor_basic(): x = (3.5, -2.1) tSet = { (1.0, -1.0): "Label1", (4.5, -0.5): "Label2", (2.0, -3.0): "Label3" } assert find_nearest_neighbor(x, tSet) == "Label3" def test_find_nearest_neighbor_tie(): x = (...
[ { "docstring": null, "function_declaration": "def euclidean_distance(v1, v2):", "function_name": "euclidean_distance", "parameter_list": "(v1, v2)" }, { "docstring": null, "function_declaration": "def find_nearest_neighbor(x, tSet):", "function_name": "find_nearest_neighbor", "pa...
[ 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 math\n\ndef find_nearest_neighbor(x: tuple, tSet: dict) -> str:\n def euclidean_distance(vec1, vec2):\n return math.sqrt(sum((a - b) ** 2 for...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00032496", "row_id": 32496, "seed_ids": "[260]" }
0.662377
Data_Structure_32496
I
[ "euclidean_distance", "find_nearest_neighbor" ]
2
[ [ "find_nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
60081301d1e0e873c0853888864da6b5bc2505c5
8a82e58fa6efce985a429e1616b142f756f6716c
v1.0
instruct
Data_Structure
Data_Structure_32547_I
#### Scenario: You're given the task to sort an array using the unconventional and inefficient Stooge Sort algorithm. However, in real scenarios, this algorithm isn't practical due to its high time complexity, so you'll also implement an optimized version afterward. #### Problem Statement: 1. Implement the Stooge Sor...
import time from typing import List, Dict def stooge_sort(arr: List[int], l: int, h: int) -> List[int]: if l >= h: return arr if arr[l] > arr[h]: arr[l], arr[h] = arr[h], arr[l] if h - l + 1 > 2: t = (h - l + 1) // 3 stooge_sort(arr, l, h - t) stooge_sort(arr, l + ...
import pytest from solution import stooge_sort, optimized_sort, compare_performance def test_stooge_sort_basic(): arr = [1, 3, 64, 5, 7, 8] sorted_arr = stooge_sort(arr.copy(), 0, len(arr) - 1) assert sorted_arr == sorted(arr) def test_stooge_sort_single_element(): arr = [1] sorted_arr = stooge_so...
[ { "docstring": null, "function_declaration": "def stooge_sort(arr, l, h):", "function_name": "stooge_sort", "parameter_list": "(arr, l, h)" }, { "docstring": null, "function_declaration": "def optimized_sort(arr):", "function_name": "optimized_sort", "parameter_list": "(arr)" }...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\nimport random\nfrom typing import List, Dict\n\n\ndef stooge_sort(arr: List[int], l: int, h: int) -> List[int]:\n \"\"\"\n Sorts array from...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00032547", "row_id": 32547, "seed_ids": "[10]" }
0.515949
Data_Structure_32547
I
[ "stooge_sort", "optimized_sort", "compare_performance" ]
3
[ [ "compare_performance", "optimized_sort" ], [ "compare_performance", "stooge_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5d6b8c279bdb10759b898382f3565b5df6ff471f
452667c8d190694e8ac574062f162f0bae3b626b
v1.0
instruct
Data_Structure
Data_Structure_32584_I
### Matrix Inversion Assessment Task #### Objective Implement a function to invert an n x n invertible matrix. The function should follow the principles outlined in the provided algorithm and must handle edge cases appropriately. #### Requirements - Write a function `invert_matrix(matrix: List[List[float]]) -> List[L...
from typing import List def array_is_matrix(array): if not isinstance(array, list) or not all(isinstance(row, list) for row in array): return False row_length = len(array[0]) if not all(len(row) == row_length for row in array): return False return True def get_determinant(matrix: List[...
import pytest from solution import invert_matrix def test_not_a_matrix(): assert invert_matrix(123) == [[-1]] assert invert_matrix("not a matrix") == [[-1]] assert invert_matrix([[1, 2], [3]]) == [[-1]] def test_non_square_matrix(): assert invert_matrix([[1, 2, 3], [4, 5, 6]]) == [[-2]] assert inv...
[ { "docstring": null, "function_declaration": "def array_is_matrix(array):", "function_name": "array_is_matrix", "parameter_list": "(array)" }, { "docstring": null, "function_declaration": "def get_determinant(matrix):", "function_name": "get_determinant", "parameter_list": "(matr...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef array_is_matrix(array: List[List[float]]) -> bool:\n \"\"\" Check if array is a well-formed matrix. \"\"\"\n if not array...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00032584", "row_id": 32584, "seed_ids": "[347]" }
0.582245
Data_Structure_32584
I
[ "array_is_matrix", "get_determinant", "get_minor", "transpose_and_multiply", "invert_matrix" ]
5
[ [ "get_determinant", "get_minor" ], [ "invert_matrix", "array_is_matrix" ], [ "invert_matrix", "get_determinant" ], [ "invert_matrix", "get_minor" ], [ "invert_matrix", "transpose_and_multiply" ] ]
5
[]
false
[]
false
pytest
true
[]
true
8e62f5b154c6a0f5b4096d66acb7c9808bf5dc9a
3267dd84e1bf824e977c7fd8293261a4eefbbdad
v1.0
instruct
Data_Structure
Data_Structure_32596_I
## Problem Statement You are required to implement a variant of the Bucket Sort algorithm. The provided implementation uses insertion sort to sort elements within each bucket. However, due to its potential inefficiencies in certain scenarios, we want to replace the insertion sort with a more efficient quicksort. **Fu...
from typing import List def quicksort(arr: List[int]) -> List[int]: if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(righ...
def test_bucket_sort_example1(): input = [4, 2, 2, 8, 3, 3, 1] expected = [1, 2, 2, 3, 3, 4, 8] assert bucket_sort(input) == expected def test_bucket_sort_example2(): input = [9, 7, 8, 2, 3, 1, 4, 6, 5] expected = [1, 2, 3, 4, 5, 6, 7, 8, 9] assert bucket_sort(input) == expected def test_bucke...
[ { "docstring": null, "function_declaration": "def quicksort(arr):", "function_name": "quicksort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def bucket_sort(arr):", "function_name": "bucket_sort", "parameter_list": "(arr)" } ]
[ 1, 1, 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 quicksort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00032596", "row_id": 32596, "seed_ids": "[26]" }
0.558906
Data_Structure_32596
I
[ "quicksort", "bucket_sort" ]
2
[ [ "bucket_sort", "quicksort" ] ]
1
[]
false
[]
false
pytest
false
[]
true
81dee128dda3ecd805d0f43d8a44e589d7b6a939
a8b7c7518bcdffae78ca288ef967c60ce78f7490
v1.0
instruct
Data_Structure
Data_Structure_32603_I
### Matrix Inversion with Custom Constraints Your task is to implement a function that inverts a given \( n \times n \) matrix, but with some constraints for an educational scenario. This question assesses your understanding of matrix operations such as transpose, determinant, and cofactor calculations. ### Function ...
from typing import List def get_determinant(matrix: List[List[float]], n: int) -> float: if n == 1: return matrix[0][0] if n == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] determinant = 0 for c in range(n): determinant += ((-1)**c) * matrix[0][c] * g...
from solution import custom_invert_matrix def test_invalid_square_matrix(): assert custom_invert_matrix([[1, 2], [3, 4, 5]]) == "Invalid matrix: not a square matrix" def test_invalid_small_matrix(): assert custom_invert_matrix([[1.0]]) == "Invalid matrix: matrix is too small" def test_singular_matrix(): ...
[ { "docstring": null, "function_declaration": "def get_determinant(matrix, n):", "function_name": "get_determinant", "parameter_list": "(matrix, n)" }, { "docstring": null, "function_declaration": "def get_cofactor(matrix, p, q):", "function_name": "get_cofactor", "parameter_list"...
[ 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 typing import List, Union\n\ndef determinant(matrix: List[List[float]]) -> float:\n \"\"\"Recursively calculates the determinant of a matrix.\"\"\"\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00032603", "row_id": 32603, "seed_ids": "[347]" }
0.521266
Data_Structure_32603
I
[ "get_determinant", "get_cofactor", "adjoint", "custom_invert_matrix" ]
4
[ [ "adjoint", "get_cofactor" ], [ "adjoint", "get_determinant" ], [ "custom_invert_matrix", "adjoint" ], [ "custom_invert_matrix", "get_determinant" ], [ "get_determinant", "get_cofactor" ] ]
5
[]
false
[]
false
pytest
true
[]
true
086e9a84d241a9e0bcb7083560bc8b33c23953e7
b8529edbec24aeca31ba599a6522ee283df2880b
v1.0
instruct
Data_Structure
Data_Structure_32611_I
### Maximum Flow with Specific Constraints **Context:** You're managing a water distribution network represented as a directed graph. Each vertex represents a node (e.g., water plants, distribution points) and each edge represents a pipeline with a certain capacity. Your goal is to maximize the water flow from the mai...
from typing import List def bfs(C, F, source, sink, parent): """ A helper function that performs BFS to find an augmenting path in the residual graph. Returns True if a path is found from source to sink, otherwise False. """ visited = [False] * len(C) queue = [source] visited[source] = True...
from solution import max_water_flow def test_example_case(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert max_water_flow(capacity...
[ { "docstring": "A helper function that performs BFS to find an augmenting path in the residual graph.\nReturns True if a path is found from source to sink, otherwise False.", "function_declaration": "def bfs(C, F, source, sink, parent):", "function_name": "bfs", "parameter_list": "(C, F, source, sin...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef bfs(C, F, source, sink, parent):\n \"\"\"\n A helper function that performs BFS to find an augmenting path in the residua...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00032611", "row_id": 32611, "seed_ids": "[240]" }
0.60573
Data_Structure_32611
I
[ "bfs", "max_water_flow" ]
2
[ [ "max_water_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5ec897c1d4d7217d175f8885fcd97ad4e2a02a55
8568209b918e2278f30da654da482a062f846140
v1.0
instruct
Data_Structure
Data_Structure_32614_I
### Task Implement the Dinic’s algorithm for computing the maximum flow in a flow network. Given a directed graph represented by a capacity matrix, your function should find the total maximum flow from a given source to a given sink. ### Description: Your implementation should include the following functions: 1. **...
from collections import deque def dinic_bfs(capacity, flow, level, source, sink): """ Perform BFS to update level graph. Returns True if sink is reachable from source in the level graph; otherwise False. """ level[:] = [-1] * len(level) level[source] = 0 queue = deque([source]) while ...
from solution import dinic def test_dinic_simple_case(): capacity = [ [0, 20, 30, 10], [0, 0, 40, 10], [0, 0, 0, 20], [0, 0, 0, 0] ] source = 0 sink = 3 assert dinic(capacity, source, sink) == 40 def test_dinic_no_flow(): capacity = [ [0, 0, 0], ...
[ { "docstring": "Perform BFS to update level graph.\nReturns True if sink is reachable from source in the level graph; otherwise False.", "function_declaration": "def dinic_bfs(capacity, flow, level, source, sink):", "function_name": "dinic_bfs", "parameter_list": "(capacity, flow, level, source, sin...
[ 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 collections import deque\n\ndef dinic_bfs(capacity, flow, level, source, sink):\n \"\"\"\n Perform a BFS to determine the level graph.\n \"\"\"\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00032614", "row_id": 32614, "seed_ids": "[240]" }
0.509304
Data_Structure_32614
I
[ "dinic_bfs", "dinic_dfs", "dinic" ]
3
[ [ "dinic", "dinic_bfs" ], [ "dinic", "dinic_dfs" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c8504011c79cd29536521330ee3e4395898a9869
7a0084abccdb7bba70f1762b66ad48c3540579fc
v1.0
instruct
Data_Structure
Data_Structure_32631_I
#### Context Matrix exponentiation is a powerful technique used in various computational problems. One crucial application is solving linear recurrence relations, where a matrix representing the transition of states can be raised to a power to compute future states efficiently. #### Task Given a square matrix `mat` of...
def multiply_matrices(a, b): """ Multiply two square matrices a and b. """ n = len(a) result = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): for k in range(n): result[i][j] += a[i][k] * b[k][j] return result def matrix_power(mat, p): ...
from solution import matrix_power def test_matrix_power_2x2_power_2(): mat = [ [1, 2], [3, 4] ] p = 2 expected = [ [7, 10], [15, 22] ] assert matrix_power(mat, p) == expected def test_matrix_power_2x2_power_3(): mat = [ [2, 0], [0, 2] ] ...
[ { "docstring": "Multiply two square matrices a and b.", "function_declaration": "def multiply_matrices(a, b):", "function_name": "multiply_matrices", "parameter_list": "(a, b)" }, { "docstring": "Compute the power of a matrix using matrix exponentiation by repeated squaring.", "function_...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def matrix_multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B.\n \"\"\"\n n = len(A)\n C = [[0] * n for _ in range(n)]\n for i in ra...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00032631", "row_id": 32631, "seed_ids": "[340]" }
0.49631
Data_Structure_32631
I
[ "multiply_matrices", "matrix_power" ]
2
[ [ "matrix_power", "multiply_matrices" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a689ef9f4693925f91ef464f755f6c9ba716da79
5c17c89bc5d646d95c330bab7461cb2bd4441c8f
v1.0
instruct
Data_Structure
Data_Structure_32648_I
### Question: You are tasked with implementing a function that sorts a list of integers using an optimized version of the Bubble Sort algorithm. Your implementation should come with a special feature where if the list is large, you switch to a more efficient sorting algorithm to improve performance. #### Requirements...
from typing import List def bubble_sort(arr: List[int]) -> List[int]: n = len(arr) for i in range(n): swapped = False for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] swapped = True if not swapped: ...
from solution import enhanced_bubble_sort def test_small_list_bubble_sort(): assert enhanced_bubble_sort([64, 25, 12, 22, 11]) == [11, 12, 22, 25, 64] def test_large_list_quick_sort(): input_list = [i for i in range(100, 0, -1)] expected_list = [i for i in range(1, 101)] assert enhanced_bubble_sort(in...
[ { "docstring": null, "function_declaration": "def bubble_sort(arr):", "function_name": "bubble_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def quick_sort(arr):", "function_name": "quick_sort", "parameter_list": "(arr)" }, { "docstring...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef bubble_sort(arr: List[int]) -> List[int]:\n n = len(arr)\n for i in range(n):\n swapped = False\n for j in ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00032648", "row_id": 32648, "seed_ids": "[6]" }
0.605383
Data_Structure_32648
I
[ "bubble_sort", "quick_sort", "enhanced_bubble_sort" ]
3
[ [ "enhanced_bubble_sort", "bubble_sort" ], [ "enhanced_bubble_sort", "quick_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2268549e78fb5011a98adbf6be91a29efed209fc
f7b2625d919de59f5ae4fd886faebbb092b97bd3
v1.0
instruct
Data_Structure
Data_Structure_32661_I
### Topological Sort Implementation Topological sorting of a directed acyclic graph (DAG) is essential for various applications like task scheduling, dependency resolution, etc. Given the importance of this algorithm, your task is to implement a function that performs topological sorting on a given directed graph usin...
from typing import List, Dict def top_sort_recursive(graph: Dict[int, List[int]]) -> List[int]: visited = set() temp = set() result = [] def visit(node): if node in temp: raise ValueError("cycle") if node not in visited: temp.add(node) for neighbor i...
import pytest from solution import topological_sort def test_simple_dag(): graph = { 0: [1, 2], 1: [3], 2: [3], 3: [] } assert topological_sort(graph) in ([0, 1, 2, 3], [0, 2, 1, 3]) def test_single_node(): graph = { 0: [] } assert topological_sort(graph...
[ { "docstring": null, "function_declaration": "def top_sort_recursive(graph):", "function_name": "top_sort_recursive", "parameter_list": "(graph)" }, { "docstring": null, "function_declaration": "def top_sort_iterative(graph):", "function_name": "top_sort_iterative", "parameter_li...
[ 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, Dict\n\ndef topological_sort(graph: dict) -> List[int]:\n def top_sort_recursive(graph: Dict[int, List[int]]) -> List[int]:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00032661", "row_id": 32661, "seed_ids": "[19]" }
0.560765
Data_Structure_32661
I
[ "top_sort_recursive", "top_sort_iterative", "topological_sort" ]
3
[ [ "topological_sort", "top_sort_iterative" ], [ "topological_sort", "top_sort_recursive" ] ]
2
[]
false
[]
false
pytest
true
[]
true
abe535e961bc9550b150c9a5530487b618d4de8b
7c3c8b887a2b881306e204bf36393f09e515300f
v1.0
instruct
Data_Structure
Data_Structure_32677_I
### AVL Tree Insertion and Balance Verification #### Objective You are required to implement a specific function in an AVL Tree that ensures the tree remains balanced after each insertion operation. Specifically, you will write a method that inserts a value into the AVL Tree and checks if the tree remains balanced. #...
class AvlNode: def __init__(self, key, left=None, right=None, height=1): self.key = key self.left = left self.right = right self.height = height class AvlTree: def __init__(self): self.root = None def insert(self, key): self.root = self._insert(self.root, ke...
from solution import AvlTree, avl_insert_and_verify def test_avl_insert_and_verify(): avl_tree = AvlTree() assert avl_insert_and_verify(avl_tree, 10) == True assert avl_insert_and_verify(avl_tree, 20) == True assert avl_insert_and_verify(avl_tree, 5) == True assert avl_insert_and_verify(avl_tree, 3...
[]
[ 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.key = key\n self.left = None\n self.right = None\n self.height = 1\n\nclass A...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00032677", "row_id": 32677, "seed_ids": "[313]" }
0.607902
Data_Structure_32677
I
[ "avl_insert_and_verify", "is_balanced_avl_tree", "get_balance_factor", "height" ]
4
[ [ "avl_insert_and_verify", "is_balanced_avl_tree" ], [ "get_balance_factor", "height" ], [ "is_balanced_avl_tree", "get_balance_factor" ] ]
3
[]
false
[ "AvlNode", "AvlTree" ]
true
pytest
true
[]
true
4893643cc684922839238693d07b95d3c8da2e84
e1ca5b093e6a805f89b0fe500777e64043ba5192
v1.0
instruct
Data_Structure
Data_Structure_32683_I
### Question: Efficient Calculation of LCM and Bitwise GCD #### Context You are tasked with improving the performance of a computationally intensive system that relies heavily on calculating the greatest common divisor (GCD) and least common multiple (LCM) of pairs of integers. For this purpose, you must implement bot...
def gcd_bit_optimized(a, b): """ Returns the greatest common divisor (GCD) of two integers a and b using bitwise operations. """ if a == 0: return b if b == 0: return a # Finding the common power of 2 in both numbers shift = 0 while ((a | b) & 1) == 0: a >>= 1 ...
from solution import gcd_bit_optimized, lcm_optimized def test_gcd_bit_optimized_basic_cases(): assert gcd_bit_optimized(48, 18) == 6 assert gcd_bit_optimized(17, 0) == 17 assert gcd_bit_optimized(0, 31) == 31 def test_gcd_bit_optimized_edge_cases(): assert gcd_bit_optimized(0, 0) == 0 assert gcd_...
[ { "docstring": "Returns the greatest common divisor (GCD) of two integers a and b using bitwise operations.", "function_declaration": "def gcd_bit_optimized(a, b):", "function_name": "gcd_bit_optimized", "parameter_list": "(a, b)" }, { "docstring": "Returns the least common multiple (LCM) of...
[ 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_bit_optimized(a: int, b: int) -> int:\n \"\"\"\n Computes the greatest common divisor (GCD) of a and b using bitwise operations.\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00032683", "row_id": 32683, "seed_ids": "[166]" }
0.603224
Data_Structure_32683
I
[ "gcd_bit_optimized", "lcm_optimized" ]
2
[ [ "lcm_optimized", "gcd_bit_optimized" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7189436fbedaab3ab2a32aee578fc470b6c0ce1d
d4f7cf29c4f77f677346fda28fd631f966d6d9df
v1.0
instruct
Data_Structure
Data_Structure_32781_I
### Coding Problem: Plagiarism Detection Using KMP Algorithm In this problem, you're required to implement a function that helps detect potential plagiarism in student submissions by finding instances of copied code snippets. Use the Knuth-Morris-Pratt (KMP) String Matching Algorithm to search for patterns within text...
def calculate_lps(pattern): """ Calculate the Longest Prefix Suffix (LPS) array. """ lps = [0] * len(pattern) length = 0 i = 1 while i < len(pattern): if pattern[i] == pattern[length]: length += 1 lps[i] = length i += 1 else: ...
def test_case_1(): submission = [ "def foo():", " print('hello world')", " return 1", "", "foo()", "bar()" ] snippet = [ " print('hello world')", " return 1" ] assert detect_plagiarism(submission, snippet) == [2] def ...
[ { "docstring": "Calculate the Longest Prefix Suffix (LPS) array.", "function_declaration": "def calculate_lps(pattern):", "function_name": "calculate_lps", "parameter_list": "(pattern)" }, { "docstring": "Perform KMP search of pattern in text.", "function_declaration": "def kmp_search(te...
[ 0, 0, 0, 1, 1, 0, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Sequence\n\ndef build_lps(pattern: str) -> List[int]:\n lps = [0] * len(pattern)\n length = 0\n i = 1\n while i < len(pat...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00032781", "row_id": 32781, "seed_ids": "[93]" }
0.545961
Data_Structure_32781
I
[ "calculate_lps", "kmp_search", "detect_plagiarism" ]
3
[ [ "detect_plagiarism", "kmp_search" ], [ "kmp_search", "calculate_lps" ] ]
2
[]
false
[]
false
pytest
false
[]
true
dd4d5f3615252626ad3ec9e4f7d424ddfbeeae8f
d3d1df9ac50dac22bbcf021aafc75af4dce6704f
v1.0
instruct
Data_Structure
Data_Structure_32799_I
### Matrix Exponentiation Application in Computer Science Matrix exponentiation is frequently used in computer science, particularly in graph theory and dynamic programming. To ensure you understand the concept thoroughly, implement a function to calculate the n-th power of a given matrix. ### Problem Statement: You...
def matrix_multiply(A, B): """ Multiplies two matrices A and B. Parameters: A (list of lists): The first matrix. B (list of lists): The second matrix. Returns: list of lists: The resultant matrix after multiplication. """ d = len(A) result = [[0] * d for _ in range(d)] for ...
from solution import matrix_exponentiation def test_matrix_exponentiation_basic(): mat = [ [2, 0], [0, 2] ] result = matrix_exponentiation(mat, 3) expected = [ [8, 0], [0, 8] ] assert result == expected def test_matrix_exponentiation_identity(): mat = [ ...
[ { "docstring": "Multiplies two matrices A and B.\n\nParameters:\nA (list of lists): The first matrix.\nB (list of lists): The second matrix.\n\nReturns:\nlist of lists: The resultant matrix after multiplication.", "function_declaration": "def matrix_multiply(A, B):", "function_name": "matrix_multiply", ...
[ 0, 0, 0, 1, 1, 0, 1, 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": "def matrix_exponentiation(mat: list, n: int) -> list:\n \"\"\"\n Returns the matrix mat raised to the power n.\n \n Parameters:\n mat (list): A...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00032799", "row_id": 32799, "seed_ids": "[340]" }
0.549054
Data_Structure_32799
I
[ "matrix_multiply", "identity_matrix", "matrix_exponentiation" ]
3
[ [ "matrix_exponentiation", "identity_matrix" ], [ "matrix_exponentiation", "matrix_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ba24ee7f2353b00355f64635eb7c466aa1615f7d
ceca55f7fc769f4ad38b251f592548899c8493cb
v1.0
instruct
Data_Structure
Data_Structure_32842_I
### Bogo Sort Deep Dive and Alternative **Scenario**: You are given a list of integers and asked to sort the list using the Bogo Sort algorithm. Given its inefficiency, you are also needed to compare its performance (in terms of steps) with a classical sorting algorithm like Quick Sort. **Task**: 1. **Implement `bog...
import random from typing import List, Tuple def is_sorted(arr: List[int]) -> bool: """Helper function to check if the list is sorted.""" for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort(arr: List[int], simulation: bool = False) -> Tuple[List...
import pytest from solution import bogo_sort, quick_sort, compare_sort_performance def test_bogo_sort_single_element(): arr = [1] sorted_arr, steps = bogo_sort(arr, simulation=True) assert sorted_arr == [1] assert steps == 0 # Already sorted in one step def test_bogo_sort_already_sorted(): arr = ...
[ { "docstring": "Helper function to check if the list is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts the array using Bogo Sort algorithm and returns the number of iterations.\n:param arr: The list of...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List, Tuple\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to check whether the array is sorted....
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00032842", "row_id": 32842, "seed_ids": "[16]" }
0.510878
Data_Structure_32842
I
[ "is_sorted", "bogo_sort", "partition", "quick_sort_recursive", "quick_sort", "compare_sort_performance" ]
6
[ [ "bogo_sort", "is_sorted" ], [ "compare_sort_performance", "bogo_sort" ], [ "compare_sort_performance", "quick_sort" ], [ "quick_sort", "quick_sort_recursive" ], [ "quick_sort_recursive", "partition" ] ]
5
[]
false
[]
false
pytest
true
[]
true
9608721b95b7fdddfb0c3b6a465d3a733bc0b6c5
46a5aa13d920dd1a73bedd1e18a72a5b49d52c1d
v1.0
instruct
Data_Structure
Data_Structure_32851_I
You are tasked with finding the maximum flow in a flow network represented by an adjacency matrix. The graph will have non-negative, integer capacities. **Function Signature:** ```python def maximum_flow(adjacency_matrix: List[List[int]]) -> int: pass ``` ### Input - `adjacency_matrix`: A square matrix representi...
from typing import List from collections import deque def bfs(residual_graph: List[List[int]], parent: List[int]) -> bool: """ A breadth-first search to find an augmenting path in the residual graph. Updates the parent list to store the found path. """ n = len(residual_graph) visited = [False] ...
from solution import maximum_flow def test_simple_graph(): graph = [ [0, 1], [0, 0] ] assert maximum_flow(graph) == 1 def test_medium_graph(): graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, ...
[ { "docstring": "A breadth-first search to find an augmenting path in the residual graph.\nUpdates the parent list to store the found path.", "function_declaration": "def bfs(residual_graph, parent):", "function_name": "bfs", "parameter_list": "(residual_graph, parent)" }, { "docstring": null...
[ 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(residual_graph: List[List[int]], parent: List[int]) -> bool:\n \"\"\"\n A breadth-firs...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00032851", "row_id": 32851, "seed_ids": "[229]" }
0.604251
Data_Structure_32851
I
[ "bfs", "maximum_flow" ]
2
[ [ "maximum_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
06c01cda40b89a519c02fd39c6c7b017d71cfcf5
fbc2900d2c5362694f58167767c0ab95bb48e255
v1.0
instruct
Data_Structure
Data_Structure_32859_I
### Question: You are tasked with implementing an improved version of the Insertion Sort based on the provided `search_insert` helper function. This function uses binary search to find the correct insertion point, thus reducing the number of comparisons needed during the sorting process. #### Function Signature: ```p...
from typing import List def search_insert(sorted_array: List[int], target: int) -> int: """ Helper function that uses binary search to find the correct insertion point for the target in the sorted part of the array. """ low, high = 0, len(sorted_array) - 1 while low <= high: mid = (low ...
import pytest from solution import binary_insertion_sort def test_binary_insertion_sort_simple_cases(): assert binary_insertion_sort([4, 2, 1, 3]) == [1, 2, 3, 4] assert binary_insertion_sort([5, 1, 12, -5, 16]) == [-5, 1, 5, 12, 16] assert binary_insertion_sort([7]) == [7] assert binary_insertion_sort...
[ { "docstring": "Helper function that uses binary search to find the correct insertion point\nfor the target in the sorted part of the array.", "function_declaration": "def search_insert(sorted_array, target):", "function_name": "search_insert", "parameter_list": "(sorted_array, target)" }, { ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef search_insert(sorted_list: List[int], value: int) -> int:\n \"\"\"\n Helper function using binary search to find the inde...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00032859", "row_id": 32859, "seed_ids": "[199]" }
0.603616
Data_Structure_32859
I
[ "search_insert", "binary_insertion_sort" ]
2
[ [ "binary_insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ce40b9567a824d61f4e69c11fa454e13004b535f
1ad12d1fc9f6745ccab78089bf620b5d22a08cb1
v1.0
instruct
Data_Structure
Data_Structure_33016_I
### Coding Task #### Scenario: You are designing a library of functions for performing common mathematical number theory operations, particularly focusing on efficient methods for determining relationships between integers. Your task is to implement functions for computing the greatest common divisor (GCD) using a bit...
def trailing_zero(x: int) -> int: """ Determines the number of trailing zeros in the binary representation of x. """ if x == 0: return 0 count = 0 while (x & 1) == 0: x >>= 1 count += 1 return count def gcd_bitwise(a: int, b: int) -> int: """ Computes the gre...
from solution import gcd_bitwise, lcm, trailing_zero def test_gcd_bitwise(): assert gcd_bitwise(18, 24) == 6 assert gcd_bitwise(48, 18) == 6 assert gcd_bitwise(101, 103) == 1 assert gcd_bitwise(0, 0) == 0 assert gcd_bitwise(0, 5) == 5 assert gcd_bitwise(5, 0) == 5 assert gcd_bitwise(1000000...
[ { "docstring": "Determines the number of trailing zeros in the binary representation of x.", "function_declaration": "def trailing_zero(x):", "function_name": "trailing_zero", "parameter_list": "(x)" }, { "docstring": "Computes the greatest common divisor using bitwise operations.", "fun...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def gcd_bitwise(a: int, b: int) -> int:\n \"\"\"\n Computes the greatest common divisor using bitwise operations.\n \"\"\"\n if a == 0:\n r...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033016", "row_id": 33016, "seed_ids": "[166]" }
0.599923
Data_Structure_33016
I
[ "trailing_zero", "gcd_bitwise", "lcm" ]
3
[ [ "gcd_bitwise", "trailing_zero" ], [ "lcm", "gcd_bitwise" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e95aeebaf796ff1a2227d88243ace320aea167e9
1ba26c8ac9ccb225dcabee1e54321f2e499d3011
v1.0
instruct
Data_Structure
Data_Structure_33020_I
### Quick Sort Analysis and Implementation **Objective**: Implement and analyze the Quick Sort algorithm and optimize its performance as required. **Problem Statement**: You are given an array of integers. Write a function `optimized_quick_sort` which sorts the array in non-decreasing order. To avoid the worst-case t...
from typing import List def partition(arr: List[int], low: int, high: int) -> int: mid = (low + high) // 2 pivot_candidates = [(arr[low], low), (arr[mid], mid), (arr[high], high)] pivot_candidates.sort() pivot = pivot_candidates[1][1] arr[pivot], arr[high] = arr[high], arr[pivot] # Move pivot...
from solution import optimized_quick_sort def test_optimized_quick_sort_with_positive_numbers(): assert optimized_quick_sort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10] def test_optimized_quick_sort_with_already_sorted_list(): assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_opt...
[ { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def optimized_quick_sort(arr):", "function_name": "optimized_quick_sort", "parameter_...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef partition(arr: List[int], low: int, high: int) -> int:\n mid = (low + high) // 2\n pivot_candidates = [(arr[low], low), (...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00033020", "row_id": 33020, "seed_ids": "[25]" }
0.58798
Data_Structure_33020
I
[ "partition", "optimized_quick_sort" ]
2
[ [ "optimized_quick_sort", "partition" ] ]
1
[]
false
[]
false
pytest
true
[]
true
76e6a0d85105c3fb9810e5705cce7af1799313dd
e3baba2db771d31083b1d15eac07a233c4553acb
v1.0
instruct
Data_Structure
Data_Structure_33022_I
### Intersection of Linked Lists #### Objective: Write a function that determines the intersection node of two singly linked lists. The intersection node is the node at which the two lists merge into one, and it must be returned. If there is no intersection, the function should return `None`. #### Task: Implement the...
class Node: def __init__(self, val=None): self.val = val self.next = None def get_length(head: Node) -> int: length = 0 current = head while current: length += 1 current = current.next return length def intersection(h1: Node, h2: Node) -> Node: len1 = get_length...
from solution import Node, intersection def test_intersection_no_intersection(): a1 = Node(1) b1 = Node(2) a1.next = b1 a2 = Node(3) b2 = Node(4) a2.next = b2 assert intersection(a1, a2) is None def test_intersection_at_start(): common = Node(1) a1 = common b1 = Node(...
[]
[ 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 intersection(h1: Node, h2: Node) -> Node:\n \"\"\"\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033022", "row_id": 33022, "seed_ids": "[245]" }
0.557863
Data_Structure_33022
I
[ "get_length", "intersection" ]
2
[ [ "intersection", "get_length" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
695f4cc41e4e75b32d047398a529bd9caa119e7f
e8b6ca62ab5bc5ba4e8c938f629a736f03e1acbd
v1.0
instruct
Data_Structure
Data_Structure_33025_I
You are given a training set of labeled points in a Euclidean space and an unlabeled point. Your task is to classify the unlabeled point using the nearest neighbor algorithm provided. #### Scenario You are aiding an autonomous drone navigation system that relies on sensor data to recognize obstacles in its path. Given...
import math def distance(point1, point2): """ Calculate the Euclidean distance between two points in 3D space. """ return math.sqrt(sum((a - b) ** 2 for a, b in zip(point1, point2))) def nearest_neighbor(point, obstacle_data): """ Find the nearest neighbor of the given point from the obstacle_...
from solution import distance, nearest_neighbor, classify_obstacle def test_distance(): assert distance((0, 0, 0), (1, 1, 1)) == math.sqrt(3) assert distance((1, 2, 3), (4, 5, 6)) == math.sqrt(27) assert distance((0, 0, 0), (0, 0, 0)) == 0.0 def test_nearest_neighbor(): obstacle_data = { (0.0,...
[ { "docstring": "Calculate the Euclidean distance between two points in 3D space.", "function_declaration": "def distance(point1, point2):", "function_name": "distance", "parameter_list": "(point1, point2)" }, { "docstring": "Find the nearest neighbor of the given point from the obstacle_data...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Computes the Euclidean distance between two 3D points.\n \"\"\"\n return math.sq...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033025", "row_id": 33025, "seed_ids": "[260]" }
0.603674
Data_Structure_33025
I
[ "distance", "nearest_neighbor", "classify_obstacle" ]
3
[ [ "classify_obstacle", "nearest_neighbor" ], [ "nearest_neighbor", "distance" ] ]
2
[]
false
[]
false
pytest
true
[]
true
eb70716b60566cabd9d472c08451c277d9a6e9ba
d552146421b30c9bdb643226bfa496ea2e9c76ab
v1.0
instruct
Data_Structure
Data_Structure_33045_I
Check if One Binary Tree is a Subtree of Another #### Objective You are tasked to write a function to check whether one binary tree (`t`) is a subtree of another binary tree (`s`). #### Function Signature ```python def is_subtree(s, t): pass ``` #### Input and Output - **Input**: Two binary trees `s` and `t`. ...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def is_same_tree(s, t): if not s and not t: return True if not s or not t: return False if s.val != t.val: return False return is_same_tree(s.left, t.left) and is_s...
from solution import TreeNode, is_subtree def test_is_subtree_true(): # Tree s: s = TreeNode(3) s.left = TreeNode(4) s.right = TreeNode(5) s.left.left = TreeNode(1) s.left.right = TreeNode(2) # Tree t: t = TreeNode(4) t.left = TreeNode(1) t.right = TreeNode(2) assert is_su...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef is_same_tree(s, t):\n if not ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033045", "row_id": 33045, "seed_ids": "[288]" }
0.63209
Data_Structure_33045
I
[ "is_same_tree", "is_subtree" ]
2
[ [ "is_subtree", "is_same_tree" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
75c9445f588996fbe38e85787faadc015fdfcf4a
2783ef95f903cdc9c37bf4c78652bf0dd33ab80e
v1.0
instruct
Data_Structure
Data_Structure_33065_I
### Pseudo-Perfect Numbers A "pseudo-perfect" number is a number whose digits can be raised to consecutive powers, starting at 1 for the left-most digit, and then summed to form the same number. For example: - 89 = 8^1 + 9^2 = 8 + 81 = 89 - 135 = 1^1 + 3^2 + 5^3 = 1 + 9 + 125 = 135 Write a function `find_pseudo_perf...
from typing import List def is_pseudo_perfect(n: int) -> bool: digits = list(map(int, str(n))) sum_of_powers = sum(digit ** (i + 1) for i, digit in enumerate(digits)) return sum_of_powers == n def find_pseudo_perfect_numbers(low: int, high: int) -> List[int]: pseudo_perfect_numbers = [] for num in...
from solution import find_pseudo_perfect_numbers def test_find_pseudo_perfect_numbers_single_digit(): assert find_pseudo_perfect_numbers(1, 9) == [1, 2, 3, 4, 5, 6, 7, 8, 9] def test_find_pseudo_perfect_numbers_within_range_1_100(): assert find_pseudo_perfect_numbers(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]...
[ { "docstring": null, "function_declaration": "def is_pseudo_perfect(n):", "function_name": "is_pseudo_perfect", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def find_pseudo_perfect_numbers(low, high):", "function_name": "find_pseudo_perfect_numbers", "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_pseudo_perfect(num: int) -> bool:\n digits = [int(digit) for digit in str(num)]\n sum_of_powers = sum(digit ** (i + 1)...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033065", "row_id": 33065, "seed_ids": "[135]" }
0.556081
Data_Structure_33065
I
[ "is_pseudo_perfect", "find_pseudo_perfect_numbers" ]
2
[ [ "find_pseudo_perfect_numbers", "is_pseudo_perfect" ] ]
1
[]
false
[]
false
pytest
true
[]
true
90df21b99a3d1076f68dec46d99c71ad58774087
6531c799346a62b5799aedd8fefb56cda44f047b
v1.0
instruct
Data_Structure
Data_Structure_33105_I
### RSA Encryption and Decryption Using Improved Key Generation You have been given snippets implementing RSA key generation, encryption, and decryption functions. In the current form, the code uses a simplified method for generating primes and computing the modular inverse, which can be inefficient for large key sizes...
import random def miller_rabin_is_prime(n, k=5): """ Implement the Miller-Rabin primality test to check if n is a prime number. :param n: integer, the number to test. :param k: integer, number of iterations for accuracy. :return: boolean, True if n is probably prime, False if n is composite. ""...
from solution import ( miller_rabin_is_prime, extended_gcd, modinv, generate_key, encrypt, decrypt ) def test_miller_rabin_is_prime(): assert miller_rabin_is_prime(2) is True assert miller_rabin_is_prime(3) is True assert miller_rabin_is_prime(11) is True assert miller_rabin_is_...
[ { "docstring": "Implement the Miller-Rabin primality test to check if n is a prime number.\n:param n: integer, the number to test.\n:param k: integer, number of iterations for accuracy.\n:return: boolean, True if n is probably prime, False if n is composite.", "function_declaration": "def miller_rabin_is_pr...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef miller_rabin_is_prime(n, k=5):\n \"\"\"\n Implement the Miller-Rabin primality test to check if n is a prime number.\n :param n:...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00033105", "row_id": 33105, "seed_ids": "[154]" }
0.586026
Data_Structure_33105
I
[ "miller_rabin_is_prime", "extended_gcd", "modinv", "generate_prime_candidate", "generate_prime_number", "generate_key", "encrypt", "decrypt" ]
8
[ [ "generate_key", "generate_prime_number" ], [ "generate_key", "modinv" ], [ "generate_prime_number", "generate_prime_candidate" ], [ "generate_prime_number", "miller_rabin_is_prime" ], [ "modinv", "extended_gcd" ] ]
5
[]
false
[]
false
pytest
true
[]
true
8dcebd3a97f99d58da19146eb5a129fc647a8e43
e8e674b4cb5dc408cee04dae86fced8ab127fe99
v1.0
instruct
Data_Structure
Data_Structure_33125_I
As a software developer, you are required to implement parts of the Huffman Coding algorithm. Specifically, you need to create functions to encode and decode text files using Huffman Coding. You can refer to the class templates provided but must write your own implementations. #### Requirements 1. **Character Frequen...
import heapq from collections import defaultdict, Counter import os class Node: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def calculate_frequency(file_...
import pytest from solution import calculate_frequency, build_huffman_tree, generate_codes, encode_file, decode_file import os def test_calculate_frequency(): with open('test.txt', 'w') as file: file.write("hello world") freq = calculate_frequency('test.txt') assert freq == {'h': 1, 'e': 1, 'l': 3,...
[]
[ 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 heapq\nimport os\nfrom collections import defaultdict, Counter\n\nclass Node:\n def __init__(self, char, freq):\n self.char = char\n s...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033125", "row_id": 33125, "seed_ids": "[335]" }
0.471568
Data_Structure_33125
I
[ "calculate_frequency", "build_huffman_tree", "generate_codes", "encode_file", "decode_file" ]
5
[ [ "decode_file", "build_huffman_tree" ], [ "decode_file", "calculate_frequency" ], [ "encode_file", "build_huffman_tree" ], [ "encode_file", "calculate_frequency" ], [ "encode_file", "generate_codes" ] ]
5
[]
false
[ "Node" ]
true
pytest
true
[]
true
600418bc61c3f17d9430ffd1014e9225589044da
a7877c4560333ff1104eb5211f2d375578ec6878
v1.0
instruct
Data_Structure
Data_Structure_33127_I
#### Scenario You are working on a recommendation system for a retail company where you need to suggest the most similar products based on feature vectors representing various product attributes such as weight, price, and user ratings. To accomplish this, you need to implement the following functionality: 1. A functi...
import math def euclidean_distance(x, y): """ Calculate the Euclidean distance between two vectors. Args: x (tuple): The first vector. y (tuple): The second vector. Returns: float: The Euclidean distance between the two vectors. """ # Check if the lengths of the two vector...
import pytest from solution import euclidean_distance, nearest_neighbor def test_euclidean_distance_same_vector(): assert euclidean_distance((1, 2, 3), (1, 2, 3)) == 0 def test_euclidean_distance_different_vectors(): assert math.isclose(euclidean_distance((1, 2, 3), (4, 6, 8)), 7.0710678118654755) def test_e...
[ { "docstring": "Calculate the Euclidean distance between two vectors.\n\nArgs:\nx (tuple): The first vector.\ny (tuple): The second vector.\n\nReturns:\nfloat: The Euclidean distance between the two vectors.", "function_declaration": "def euclidean_distance(x, y):", "function_name": "euclidean_distance"...
[ 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 math\n\ndef euclidean_distance(x, y):\n \"\"\"\n Calculate the Euclidean distance between two vectors.\n \n Args:\n x (tuple): The first...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033127", "row_id": 33127, "seed_ids": "[260]" }
0.61503
Data_Structure_33127
I
[ "euclidean_distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
60a8b8a822ee4ccbf16ee3217ecc59513497daa4
ea92a3023780b4462f967c09677e4b109cf1320a
v1.0
instruct
Data_Structure
Data_Structure_33172_I
You are tasked with implementing the Radix Sort algorithm. Your implementation should allow for an optional simulation mode that prints the intermediate steps of sorting arrays. Given an array of non-negative integers, sort the array in ascending order. ### Function Signature ```python def radix_sort(arr, simulation=F...
def counting_sort(arr, exp, simulation=False, iteration=0): n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = (arr[i] // exp) % 10 count[index] += 1 if simulation: print(f"Count array at iteration {iteration} for exp {exp}: {count}") for i in ra...
from solution import radix_sort def test_sort_regular_array(): arr = [170, 45, 75, 90, 802, 24, 2, 66] result = radix_sort(arr) assert result == [2, 24, 45, 66, 75, 90, 170, 802] def test_sort_single_element_array(): arr = [5] result = radix_sort(arr) assert result == [5] def test_sort_empty_...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp, simulation=False, iteration=0):", "function_name": "counting_sort", "parameter_list": "(arr, exp, simulation=False, iteration=0)" }, { "docstring": null, "function_declaration": "def radix_sort(arr, simulation=Fals...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def counting_sort(arr, exp, simulation=False, iteration=0):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n for i in range(n):\n i...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00033172", "row_id": 33172, "seed_ids": "[15]" }
0.619532
Data_Structure_33172
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
11274a347e3bb9dc7638e519dd6ad46ff5888ca6
c2e96436cd76afa23b5063b672ed3ddbfb01682c
v1.0
instruct
Data_Structure
Data_Structure_33273_I
### Maximum Flow in Transport Network You are responsible for managing traffic flow in a city's transport network represented as a directed graph in the form of an adjacency matrix. The nodes represent intersections, and the edges represent streets with capacities indicating the maximum number of vehicles that can pas...
from typing import List from collections import deque def bfs(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool: # Mark all vertices as not visited visited = [False] * len(residual_graph) # Create a queue for BFS queue = deque() # Mark the source node as ...
from solution import maximum_flow_bfs def test_basic_case(): graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] assert maximum_flow_bfs(graph) == 23 def test_no_flow_case(...
[ { "docstring": null, "function_declaration": "def bfs(residual_graph, source, sink, parent):", "function_name": "bfs", "parameter_list": "(residual_graph, source, sink, parent)" }, { "docstring": null, "function_declaration": "def maximum_flow_bfs(adjacency_matrix):", "function_name"...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n \"...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033273", "row_id": 33273, "seed_ids": "[229]" }
0.644253
Data_Structure_33273
I
[ "bfs", "maximum_flow_bfs" ]
2
[ [ "maximum_flow_bfs", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b5f759e71644d004aabba43cd2d9a904589f12d8
6619874106610f1ff4bd6c02df844f8a9bf7afd7
v1.0
instruct
Data_Structure
Data_Structure_33284_I
### Scenario You have been given two heap-sort implementations: one that utilizes a max heap and another that utilizes a min heap. Both have been designed to sort arrays in ascending order. Unfortunately, there is a requirement change, and now you need to enhance these functions to handle descending order sorting. ###...
def max_heapify(arr, n, i, simulation=False): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[i] < arr[left]: largest = left if right < n and arr[largest] < arr[right]: largest = right if largest != i: arr[i], arr[largest] = arr[largest], arr[i] ...
from solution import max_heap_sort_descending, min_heap_sort_descending def test_max_heap_sort_descending_basic(): arr = [4, 10, 3, 5, 1] sorted_arr = max_heap_sort_descending(arr.copy()) assert sorted_arr == [10, 5, 4, 3, 1] def test_max_heap_sort_descending_with_negatives(): arr = [2, -1, 3, 7, 3, 5...
[ { "docstring": null, "function_declaration": "def max_heapify(arr, n, i, simulation=False):", "function_name": "max_heapify", "parameter_list": "(arr, n, i, simulation=False)" }, { "docstring": null, "function_declaration": "def max_heap_sort_descending(arr, simulation=False):", "fun...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def max_heapify(arr, n, i, simulation=False):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n and arr[i] < arr[left]:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033284", "row_id": 33284, "seed_ids": "[8]" }
0.693672
Data_Structure_33284
I
[ "max_heapify", "max_heap_sort_descending", "min_heapify", "min_heap_sort_descending" ]
4
[ [ "max_heap_sort_descending", "max_heapify" ], [ "min_heap_sort_descending", "min_heapify" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c9e294091b9f10be5ce299c2f049de8a5c48c55a
89e766a2f5f42c0fc4130d48ced5e40b64d03e0b
v1.0
instruct
Data_Structure
Data_Structure_33308_I
Given a list of non-negative integer pairs, implement two functions to perform the following: 1. Compute the greatest common divisor (GCD) of each pair using bitwise operations. 2. Compute the lowest common multiple (LCM) of each pair using the Euclidean algorithm for GCD. ### Constraints: - All integers within pairs ...
from typing import List, Tuple def gcd_bitwise(a: int, b: int) -> int: """Compute GCD using bitwise operations.""" if a == 0: return b if b == 0: return a if a == b: return a if a % 2 == 0: if b % 2 == 0: return gcd_bitwise(a >> 1, b >> 1) << 1 ...
from solution import gcd_bitwise, lcm_using_gcd, process_pairs def test_gcd_bitwise(): assert gcd_bitwise(12, 15) == 3 assert gcd_bitwise(100, 150) == 50 assert gcd_bitwise(200, 300) == 100 assert gcd_bitwise(0, 5) == 5 assert gcd_bitwise(5, 0) == 5 assert gcd_bitwise(0, 0) == 0 assert gcd_...
[ { "docstring": "Compute GCD using bitwise operations.", "function_declaration": "def gcd_bitwise(a, b):", "function_name": "gcd_bitwise", "parameter_list": "(a, b)" }, { "docstring": "Compute LCM using the Euclidean algorithm's GCD.", "function_declaration": "def lcm_using_gcd(a, b):", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def gcd_bitwise(a: int, b: int) -> int:\n \"\"\"\n Compute GCD using bitwise operations.\n \"\"\"\n if a == 0:\n return b\n if b == 0:\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033308", "row_id": 33308, "seed_ids": "[166]" }
0.701932
Data_Structure_33308
I
[ "gcd_bitwise", "lcm_using_gcd", "process_pairs" ]
3
[ [ "lcm_using_gcd", "gcd_bitwise" ], [ "process_pairs", "gcd_bitwise" ], [ "process_pairs", "lcm_using_gcd" ] ]
3
[]
false
[]
false
pytest
true
[]
true
3990c260cc0558b5b5e1ccff1a44d79d6f5a0313
23ca5cd3c4d32960020ac212f870e97ae29cdd35
v1.0
instruct
Data_Structure
Data_Structure_33328_I
##### Context: You are tasked with implementing a custom sorting algorithm for a data processing system that handles a large and uniformly distributed dataset representing sensor measurements ranging from 0 to 1000. Your goal is to use the Bucket Sort algorithm with nested Insertion Sort to efficiently order these meas...
from typing import List def insertion_sort(bucket: List[int]) -> List[int]: for i in range(1, len(bucket)): key = bucket[i] j = i - 1 while j >= 0 and key < bucket[j]: bucket[j + 1] = bucket[j] j -= 1 bucket[j + 1] = key return bucket def bucket_sort(arr...
from solution import bucket_sort def test_bucket_sort_normal_case(): assert bucket_sort([29, 25, 3, 49, 9, 37, 21, 43]) == [3, 9, 21, 25, 29, 37, 43, 49] def test_bucket_sort_sorted_list(): assert bucket_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_bucket_sort_reverse_order(): assert bucket_sort([5,...
[ { "docstring": null, "function_declaration": "def insertion_sort(bucket):", "function_name": "insertion_sort", "parameter_list": "(bucket)" }, { "docstring": null, "function_declaration": "def bucket_sort(arr):", "function_name": "bucket_sort", "parameter_list": "(arr)" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef insertion_sort(bucket: List[int]) -> List[int]:\n for i in range(1, len(bucket)):\n key = bucket[i]\n j = i - ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033328", "row_id": 33328, "seed_ids": "[26]" }
0.497877
Data_Structure_33328
I
[ "insertion_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f3444d86c0c907252eed91180b9fa8d6eb193f25
629967f47fea7bc54e732bbb182902f7f512683c
v1.0
instruct
Data_Structure
Data_Structure_33344_I
Enhanced Sorting Assessment #### Context: Stooge Sort is a classic example of a highly inefficient sorting algorithm, primarily used for educational purposes. In this task, you will need to implement a much more efficient and commonly-used sorting algorithm called Merge Sort. Merge Sort is a divide-and-conquer algorit...
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts an array using the Merge Sort algorithm. Parameters: arr (List[int]): The array to be sorted. Returns: List[int]: The sorted array. """ if len(arr) <= 1: return arr mid = len(arr) /...
from solution import merge_sort def test_merge_sort_unsorted_array(): assert merge_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90] def test_merge_sort_sorted_array(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_sorted_array(): assert merge_sort([5,...
[ { "docstring": "Sorts an array using the Merge Sort algorithm.\n\nParameters:\narr (List[int]): The array to be sorted.\n\nReturns:\nList[int]: The sorted array.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merg...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half =...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033344", "row_id": 33344, "seed_ids": "[10]" }
0.674578
Data_Structure_33344
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d6917b7554ebae846a8f15692a054ae775547f1c
5834e03aa4aebb215fd363c962bd950cb113ecab
v1.0
instruct
Data_Structure
Data_Structure_33356_I
### Nearest Neighbor Classifier You have been tasked with implementing a simple nearest neighbor classifier. Given a set of training data points with labels and a query point, your classifier should return the label of the nearest training data point. ### Input - A dictionary where keys are tuples representing coordi...
import math def euclidean_distance(point1, point2): """ Calculate the Euclidean distance between two points in multi-dimensional space. """ return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2))) def nearest_neighbor(query_point, training_set): """ Find the label of the nearest nei...
from solution import nearest_neighbor def test_single_point_in_training_set(): training_set = {(2, 3): 'A'} query_point = (2, 3) assert nearest_neighbor(query_point, training_set) == 'A' def test_multiple_points_in_training_set(): training_set = { (1, 2): 'A', (3, 4): 'B', (5, ...
[ { "docstring": "Calculate the Euclidean distance between two points in multi-dimensional space.", "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Find the label of the nearest ne...
[ 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 math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points in multi-dimensional space.\n \...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033356", "row_id": 33356, "seed_ids": "[260]" }
0.675955
Data_Structure_33356
I
[ "euclidean_distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d7756e4b045643e4a34675bc302485f5bf55b464
b8382026c26b4de44e98c876678f18c992ffdbb0
v1.0
instruct
Data_Structure
Data_Structure_33369_I
#### Problem Statement You are given a universe of elements `U` and a collection of subsets `S` where each subset `Si` has an associated cost. Your task is to implement two functions: 1. **optimal_set_cover(U, S, costs)**: An optimal algorithm to find the minimum cost subcollection of `S` that covers all elements of `...
from itertools import chain, combinations def powerset(iterable): 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 for cover in powerset(subsets.keys()): ...
from solution import optimal_set_cover, greedy_set_cover def test_optimal_set_cover_example(): U = {1, 2, 3, 4, 5} S = {'S1': {4, 1, 3}, 'S2': {2, 5}, 'S3': {1, 4, 3, 2}} costs = {'S1': 5, 'S2': 10, 'S3': 3} assert optimal_set_cover(U, S, costs) == {'S2', 'S3'} def test_greedy_set_cover_example(): ...
[ { "docstring": null, "function_declaration": "def powerset(iterable):", "function_name": "powerset", "parameter_list": "(iterable)" }, { "docstring": null, "function_declaration": "def optimal_set_cover(universe, subsets, costs):", "function_name": "optimal_set_cover", "parameter...
[ 0, 0, 0, 1, 1, 0, 0, 0, 1, 1 ]
4
medium
0.4
{ "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 s = list(iterable)\n return chain.from_iterable(combinations(s, r) for r in range...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00033369", "row_id": 33369, "seed_ids": "[130]" }
0.54029
Data_Structure_33369
I
[ "powerset", "optimal_set_cover", "greedy_set_cover" ]
3
[ [ "optimal_set_cover", "powerset" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c9418a05a1689cfb95bd19b2d50ae2347aa50e9e
39d954cf68c6943a761ebf6ea74647cabe3f373e
v1.0
instruct
Data_Structure
Data_Structure_33380_I
### Question You are tasked with implementing an algorithm to solve the 2-Satisfiability (2-SAT) problem using the concept of Strongly Connected Components (SCC). Given a formula in conjunctive normal form (2-CNF), your program should find a way to assign True/False values to all variables to satisfy all clauses or rep...
def add_edge(graph, vertex_from, vertex_to): if vertex_from not in graph: graph[vertex_from] = [] graph[vertex_from].append(vertex_to) def build_graph(formula): graph = {} for (u, v) in formula: u_name, u_sign = u v_name, v_sign = v add_edge(graph, (u_name, not u_sign), ...
def test_solve_sat_possible(): formula = [ (('x', False), ('y', False)), (('y', True), ('y', True)), (('a', False), ('b', False)), (('a', True), ('c', True)), (('c', False), ('b', True)) ] result = solve_sat(formula) assert result is not None assert result['x'...
[ { "docstring": null, "function_declaration": "def add_edge(graph, vertex_from, vertex_to):", "function_name": "add_edge", "parameter_list": "(graph, vertex_from, vertex_to)" }, { "docstring": null, "function_declaration": "def build_graph(formula):", "function_name": "build_graph", ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def add_edge(graph, vertex_from, vertex_to):\n if vertex_from not in graph:\n graph[vertex_from] = []\n graph[vertex_from].append(vertex_to)\n\nd...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00033380", "row_id": 33380, "seed_ids": "[221]" }
0.458873
Data_Structure_33380
I
[ "add_edge", "build_graph", "dfs", "dfs_transposed", "scc", "solve_sat" ]
6
[ [ "build_graph", "add_edge" ], [ "scc", "add_edge" ], [ "scc", "dfs" ], [ "scc", "dfs_transposed" ], [ "solve_sat", "build_graph" ], [ "solve_sat", "scc" ] ]
6
[]
false
[]
false
pytest
false
[]
true
a20f06229b436a275e2be76b7384a12999efb255
7a7a856a1a1fa2b34cd153977200e0af039e8c0b
v1.0
instruct
Data_Structure
Data_Structure_33381_I
### Quick Sort Implementation and Analysis **Context**: You have been hired by a tech company to optimize and analyze the performance of various sorting algorithms. Your first task is to implement the Quick Sort algorithm from scratch and analyze its behavior on different types of input arrays. **Task**: Implement th...
from typing import List def quick_sort(arr: List[int], low: int, high: int, simulation: bool, depth: int = 0) -> None: if low < high: p = partition(arr, low, high, simulation, depth) quick_sort(arr, low, p - 1, simulation, depth + 1) quick_sort(arr, p + 1, high, simulation, depth + 1) def ...
from solution import analyze_quick_sort def test_analyze_quick_sort_basic(): assert analyze_quick_sort([3, 6, 8, 10, 1, 2, 1], simulation=False) == [1, 1, 2, 3, 6, 8, 10] def test_analyze_quick_sort_sorted_array(): assert analyze_quick_sort([1, 2, 3, 4, 5], simulation=False) == [1, 2, 3, 4, 5] def test_analy...
[ { "docstring": null, "function_declaration": "def quick_sort(arr, low, high, simulation, depth=0):", "function_name": "quick_sort", "parameter_list": "(arr, low, high, simulation, depth=0)" }, { "docstring": null, "function_declaration": "def partition(arr, low, high, simulation, depth):...
[ 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 quick_sort(arr: List[int], low: int, high: int, simulation: bool, iteration: int) -> int:\n if low < high:\n pi = par...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033381", "row_id": 33381, "seed_ids": "[25]" }
0.590993
Data_Structure_33381
I
[ "quick_sort", "partition", "analyze_quick_sort" ]
3
[ [ "analyze_quick_sort", "quick_sort" ], [ "quick_sort", "partition" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1197d3037a5fa59670bdeea85b580ff7967f3ad8
0ba0bb3d8d1d45d72905a16d4cbbda282532e8f5
v1.0
instruct
Data_Structure
Data_Structure_33385_I
Efficient Sorting Algorithm You are given an array of `n` integers. Your task is to implement an efficient sorting algorithm that sorts the array in ascending order. The current implementation using Stooge Sort has high time complexity and is inefficient for large datasets. You need to implement a more efficient sorti...
from typing import List def efficient_sort(arr: List[int]) -> List[int]: """ Sorts an array of integers in ascending order using Merge Sort algorithm. """ if len(arr) <= 1: return arr # Divide the array into two halves mid = len(arr) // 2 left_half = efficient_sort(arr[:mid]) r...
from solution import efficient_sort def test_efficient_sort_basic(): assert efficient_sort([1,3,64,5,7,8]) == [1,3,5,7,8,64] def test_efficient_sort_empty(): assert efficient_sort([]) == [] def test_efficient_sort_single_element(): assert efficient_sort([1]) == [1] def test_efficient_sort_already_sorted...
[ { "docstring": "Sorts an array of integers in ascending order using Merge Sort algorithm.", "function_declaration": "def efficient_sort(arr):", "function_name": "efficient_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "fun...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef efficient_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array of integers in ascending order using Quick Sort al...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033385", "row_id": 33385, "seed_ids": "[10]" }
0.606614
Data_Structure_33385
I
[ "efficient_sort", "merge" ]
2
[ [ "efficient_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5461f88718aa1e809c4235ef86ee4d5899a172c0
66de0869791a7c30a53bb1481f6616a10ac5a250
v1.0
instruct
Data_Structure
Data_Structure_33397_I
### Coding Task: Primitive Root Generator #### Problem Statement: You are asked to implement an efficient algorithm to find all primitive roots of a given integer `n`. To do this, you will use three helper functions: `find_order`, `euler_totient`, and `find_primitive_root`, which compute the mathematical properties ne...
def gcd(a, b): while b: a, b = b, a % b return a def find_order(a, n): if gcd(a, n) != 1: return -1 order = 1 current = a % n while current != 1: order += 1 current = (current * a) % n return order def euler_totient(n): result = n p = 2 while p *...
from solution import find_primitive_root, find_order, euler_totient # Test helper functions def test_find_order(): assert find_order(3, 10) == 4 assert find_order(2, 10) == -1 assert find_order(7, 10) == 4 assert find_order(2, 5) == 4 def test_euler_totient(): assert euler_totient(1) == 1 ...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def find_order(a, n):", "function_name": "find_order", "parameter_list": "(a, n)" }, { "docstring": null, ...
[ 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 gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef find_order(a, n):\n if gcd(a, n) != 1:\n return -1\n order = 1\n cu...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00033397", "row_id": 33397, "seed_ids": "[160]" }
0.473249
Data_Structure_33397
I
[ "gcd", "find_order", "euler_totient", "find_primitive_root" ]
4
[ [ "find_order", "gcd" ], [ "find_primitive_root", "euler_totient" ], [ "find_primitive_root", "find_order" ], [ "find_primitive_root", "gcd" ] ]
4
[]
false
[]
false
pytest
true
[]
true
7eeea6bf7b739e7417ec09577ebd37339ea276d6
b944076fb7bf10fca87b55c142aa900e3178a3ed
v1.0
instruct
Data_Structure
Data_Structure_33412_I
### Coding Challenge: Enhanced Bucket Sort **Context**: You are working on a project that requires efficient sorting of large datasets. Given the current implementation of Bucket Sort, you suspect that the worst-case performance is occasionally impacting the overall system efficiency. You decide to enhance the current...
def bucket_sort(arr): if len(arr) == 0: return arr # Create buckets and distribute the elements max_value = max(arr) size = max_value / len(arr) buckets = [[] for _ in range(len(arr))] for i in range(len(arr)): index = int(arr[i] / size) if index != len(arr): ...
from solution import bucket_sort, merge_sort def test_bucket_sort_basic(): assert bucket_sort([4, 1, 7, 3, 10]) == [1, 3, 4, 7, 10] assert bucket_sort([10, 4, 7, 1, 3]) == [1, 3, 4, 7, 10] def test_bucket_sort_empty(): assert bucket_sort([]) == [] def test_bucket_sort_single_element(): assert bucket_...
[ { "docstring": null, "function_declaration": "def bucket_sort(arr):", "function_name": "bucket_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "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": "def bucket_sort(arr):\n if len(arr) == 0:\n return arr\n\n min_value = min(arr)\n max_value = max(arr)\n bucket_range = (max_value - min_va...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033412", "row_id": 33412, "seed_ids": "[26]" }
0.552583
Data_Structure_33412
I
[ "bucket_sort", "merge_sort", "merge" ]
3
[ [ "bucket_sort", "merge_sort" ], [ "merge_sort", "merge" ] ]
2
[]
false
[]
false
pytest
true
[]
true
efd798288a6f0753dd0a056bd2bee672087483c8
aafbea27176557f0f39cf0b03d0b6d541fef28fd
v1.0
instruct
Data_Structure
Data_Structure_33413_I
Implement an improved sorting algorithm that demonstrates your understanding of advanced sorting techniques. Use the `bubble_sort` function provided as a reference, but enhance the algorithm to efficiently handle large datasets and improve its performance. ### Requirements * **Input/Output**: * Write a function `i...
def improved_sort(arr): """ This function implements the Merge Sort algorithm which provides better performance than O(n^2) in average and worst-case scenarios. Merge Sort also maintains the stability of the sorting algorithm. """ if len(arr) <= 1: return arr # Split the array into two ...
from solution import improved_sort def test_improved_sort_basic(): assert improved_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90] assert improved_sort([5, 1, 4, 2, 8]) == [1, 2, 4, 5, 8] def test_improved_sort_empty(): assert improved_sort([]) == [] def test_improved_sort_single_eleme...
[ { "docstring": "This function implements the Merge Sort algorithm which provides better performance than O(n^2)\nin average and worst-case scenarios. Merge Sort also maintains the stability of the sorting algorithm.", "function_declaration": "def improved_sort(arr):", "function_name": "improved_sort", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef improved_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Improved sorting algorithm using Merge Sort for better average tim...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033413", "row_id": 33413, "seed_ids": "[6]" }
0.610807
Data_Structure_33413
I
[ "improved_sort", "merge" ]
2
[ [ "improved_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
781b4be7fcbed2c59401d8d9aa4ea4536364fdcb
43aa78f84fdb9fb65f7e0e9ca54d47a3f606edbb
v1.0
instruct
Data_Structure
Data_Structure_33416_I
### Matrix Inversion Challenge You are tasked with implementing a function that computes the inverse of a given n x n matrix using the cofactor method. Your function should account for various edge cases and ensure it handles invalid inputs appropriately. **Function Signature:** ```python def invert_matrix(matrix: L...
from typing import List def determinant(matrix: List[List[float]], n: int) -> float: if n == 1: return matrix[0][0] if n == 2: return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0] det = 0 for c in range(n): det += ((-1) ** c) * matrix[0][c] * determinant(minor(matrix, 0...
from solution import invert_matrix def test_invert_matrix_successful_2x2(): matrix = [[4, 7], [2, 6]] expected = [[0.6, -0.7], [-0.2, 0.4]] result = invert_matrix(matrix) assert result == expected def test_invert_matrix_successful_3x3(): matrix = [[1, 2, 3], [0, 1, 4], [5, 6, 0]] expected = [[...
[ { "docstring": null, "function_declaration": "def determinant(matrix, n):", "function_name": "determinant", "parameter_list": "(matrix, n)" }, { "docstring": null, "function_declaration": "def minor(matrix, i, j):", "function_name": "minor", "parameter_list": "(matrix, i, j)" }...
[ 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 get_cofactor(matrix: List[List[float]], p: int, q: int) -> List[List[float]]:\n \"\"\"\n Helper function to get the cofac...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033416", "row_id": 33416, "seed_ids": "[347]" }
0.551302
Data_Structure_33416
I
[ "determinant", "minor", "cofactor", "transpose", "inverse", "invert_matrix" ]
6
[ [ "cofactor", "determinant" ], [ "cofactor", "minor" ], [ "determinant", "minor" ], [ "inverse", "cofactor" ], [ "inverse", "determinant" ], [ "inverse", "transpose" ], [ "invert_matrix", "inverse" ] ]
7
[]
false
[]
false
pytest
true
[]
true
c6ede5ec1da35e6119352182db10aa581bab4f65
4e459ffe80fde569cf5393982594ed23566341cf
v1.0
instruct
Data_Structure
Data_Structure_33419_I
You've been tasked with implementing a secure numerical computation system as part of a broader cryptographic module. One fundamental operation you need to implement is efficient exponentiation, given the frequent need to perform power calculations with high exponents and potentially large bases, often under a specifie...
def power_iter(a: int, n: int, mod: int = None) -> int: """ Efficiently computes a^n using an iterative version of binary exponentiation. If mod is specified, returns a^n % mod. Args: - a (int): The base integer. - n (int): The exponent integer. - mod (int, optional): The modulus intege...
from solution import power, power_recur def test_power_base_case(): assert power(2, 0) == 1 assert power(2, 1) == 2 assert power(0, 0) == 1 def test_power_no_mod(): assert power(2, 10) == 1024 assert power(3, 5) == 243 assert power(7, 3) == 343 def test_power_with_mod(): assert power(2, 1...
[ { "docstring": "Efficiently computes a^n using an iterative version of binary exponentiation.\nIf mod is specified, returns a^n % mod.\n\nArgs:\n- a (int): The base integer.\n- n (int): The exponent integer.\n- mod (int, optional): The modulus integer. Default is None.\n\nReturns:\n- int: The result of the expo...
[ 0, 0, 0, 0, 1, 1, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def power_iterative(a: int, n: int, mod: int = None) -> int:\n \"\"\"\n Iteratively computes a^n using binary exponentiation.\n \n Parameters:\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00033419", "row_id": 33419, "seed_ids": "[151]" }
0.593807
Data_Structure_33419
I
[ "power_iter", "power_recur", "power" ]
3
[ [ "power", "power_iter" ] ]
1
[]
false
[]
false
pytest
true
[]
true
86684995b7659687cb6eb5a17c331a7995578136
686956bd56b1f1d75fd15944e49fcdd1973d5683
v1.0
instruct
Data_Structure
Data_Structure_33434_I
### Question: Enhanced Quick Sort Implementation **Context:** You are hired by a tech company to improve the performance of their flagship sorting library. One of the popular methods in this library is Quick Sort. The current implementation has some performance issues with large and small datasets. **Task:** Implem...
def insertion_sort(arr, left, right): for i in range(left + 1, right + 1): key = arr[i] j = i - 1 while j >= left and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def median_of_three(arr, low, high): mid = (low + high) // 2 if arr[low] > ...
from solution import enhanced_quick_sort def test_enhanced_quick_sort_example(): arr = [34, 7, 23, 32, 5, 62] sorted_arr = [5, 7, 23, 32, 34, 62] assert enhanced_quick_sort(arr) == sorted_arr def test_enhanced_quick_sort_empty(): arr = [] assert enhanced_quick_sort(arr) == [] def test_enhanced_qu...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr, left, right):", "function_name": "insertion_sort", "parameter_list": "(arr, left, right)" }, { "docstring": null, "function_declaration": "def median_of_three(arr, low, high):", "function_name": "median_of_three", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def median_of_three(arr, low, high):\n mid = (low + high) // 2\n if arr[low] > arr[mid]:\n arr[low], arr[mid] = arr[mid], arr[low]\n if arr[lo...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033434", "row_id": 33434, "seed_ids": "[25]" }
0.533339
Data_Structure_33434
I
[ "insertion_sort", "median_of_three", "partition", "quick_sort", "enhanced_quick_sort" ]
5
[ [ "enhanced_quick_sort", "quick_sort" ], [ "partition", "median_of_three" ], [ "quick_sort", "insertion_sort" ], [ "quick_sort", "partition" ] ]
4
[]
false
[]
false
pytest
true
[]
true
4cee0f0e4deba42a785aa718ed57e81c71d9349d
7f20b6ef196370d9cafa7ef87b306f77f8c9b684
v1.0
instruct
Data_Structure
Data_Structure_33503_I
You are tasked with developing a comprehensive utility that leverages fundamental algorithms like the Euclidean method for GCD, incorporates bitwise operations for efficient computation, and counts trailing zeros in binary numbers to facilitate various number theoretical operations. This utility will contain three main...
def compute_gcd(a, b): """ Compute the GCD of two integers using the Euclidean algorithm. """ while b: a, b = b, a % b return a def compute_lcm(a, b): """ Compute the LCM of two integers. """ return abs(a * b) // compute_gcd(a, b) def count_trailing_zeros(x): """ Co...
from solution import compute_gcd, compute_lcm, count_trailing_zeros def test_compute_gcd(): assert compute_gcd(48, 18) == 6 assert compute_gcd(101, 103) == 1 assert compute_gcd(56, 98) == 14 assert compute_gcd(100000000000003, 100000000000007) == 1 assert compute_gcd(0, 1) == 1 assert compute_g...
[ { "docstring": "Compute the GCD of two integers using the Euclidean algorithm.", "function_declaration": "def compute_gcd(a, b):", "function_name": "compute_gcd", "parameter_list": "(a, b)" }, { "docstring": "Compute the LCM of two integers.", "function_declaration": "def compute_lcm(a, ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def compute_gcd(a, b):\n \"\"\"\n Compute the GCD of two integers using the Euclidean algorithm.\n \"\"\"\n while b:\n a, b = b, a % b\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00033503", "row_id": 33503, "seed_ids": "[166]" }
0.618672
Data_Structure_33503
I
[ "compute_gcd", "compute_lcm", "count_trailing_zeros" ]
3
[ [ "compute_lcm", "compute_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
add116ce0bc6771e9f8257ddbdad09804aff80a3
4b3cf8f1ba484467f6a85206bf76ca63e74537c9
v1.0
instruct
Data_Structure
Data_Structure_33533_I
### Question: Extended Insertion Search Using Binary Search Using the given binary search helper function, `search_insert`, write a function `insert_and_search` that first ensures the array is sorted, inserts a new value into the array in the correct position, and then searches for another given target value using the...
from typing import List def search_insert(array: List[int], target: int) -> int: """ A helper function that performs binary search to find the target or the insertion index. """ left, right = 0, len(array) - 1 while left <= right: mid = (left + right) // 2 if array[mid] == target: ...
from solution import insert_and_search def test_insert_and_search(): assert insert_and_search([3, 5, 7, 9], 6, 8) == 4 assert insert_and_search([1, 3, 5, 6], 5, 2) == 1 assert insert_and_search([1, 3, 5, 6], 7, 7) == 4 assert insert_and_search([1, 2, 4, 5, 6], 3, 5) == 4 assert insert_and_search([]...
[ { "docstring": "A helper function that performs binary search to find the target or the insertion index.", "function_declaration": "def search_insert(array, target):", "function_name": "search_insert", "parameter_list": "(array, target)" }, { "docstring": "Inserts a new value into the sorted...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef search_insert(array: List[int], target: int) -> int:\n \"\"\"\n This helper function performs binary search on the array ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033533", "row_id": 33533, "seed_ids": "[199]" }
0.616213
Data_Structure_33533
I
[ "search_insert", "insert_and_search" ]
2
[ [ "insert_and_search", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
490613b408725fd447935d87efdddf269770c32a
2e69319ebeb4db0a0dc02e17223078358f615f45
v1.0
instruct
Data_Structure
Data_Structure_33554_I
<|Analysis Begin|> ### Algorithm Analysis #### Core Identification * **Algorithm/Data Structure**: The provided code utilizes a **backtracking algorithm** to construct word squares. * **Complexity**: * **Time Complexity**: In the worst case, the time complexity of the algorithm is \(O(N \cdot 26^L)\), where \(N\) ...
from typing import List, Dict from collections import defaultdict def build_prefix_dict(words: List[str]) -> Dict[str, List[str]]: prefix_dict = defaultdict(list) for word in words: for i in range(len(word)): prefix = word[:i] prefix_dict[prefix].append(word) return prefix_d...
from solution import word_squares def test_example_case_1(): words = ["area","lead","wall","lady","ball"] output = [ ["wall","area","lead","lady"], ["ball","area","lead","lady"] ] result = word_squares(words) assert len(result) == len(output) for word_square in output: a...
[ { "docstring": null, "function_declaration": "def build_prefix_dict(words):", "function_name": "build_prefix_dict", "parameter_list": "(words)" }, { "docstring": null, "function_declaration": "def backtrack(step, word_len, words, square, result, prefix_dict):", "function_name": "back...
[ 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 word_squares(words):\n def build_prefix_dict(words):\n prefix_dict = {}\n for word in words:\n for i in range(len(word)):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033554", "row_id": 33554, "seed_ids": "[87]" }
0.520764
Data_Structure_33554
I
[ "build_prefix_dict", "backtrack", "word_squares" ]
3
[ [ "word_squares", "backtrack" ], [ "word_squares", "build_prefix_dict" ] ]
2
[]
false
[]
false
pytest
true
[]
true
fbc74db5522c5f86df114651be4bb97c8c0265a6
35600202c65bcf4f12fc00b7a656c7c7c2c74325
v1.0
instruct
Data_Structure
Data_Structure_33660_I
## Problem Statement Given a square matrix `mat` of size \( n \times n \) and an integer `exp`, write a function `power_matrix(mat: List[List[int]], exp: int) -> List[List[int]]` that returns the matrix raised to the power of `exp`. ### Input - A square matrix `mat` of size \( n \times n \), where \( 1 \leq n \leq 100...
from typing import List def multiply_matrices(A: List[List[int]], B: List[List[int]]) -> List[List[int]]: n = len(A) result = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): for k in range(n): result[i][j] += A[i][k] * B[k][j] return result def ide...
from solution import power_matrix def test_power_matrix_example1(): mat = [ [1, 2], [3, 4] ] exp = 2 expected = [ [7, 10], [15, 22] ] assert power_matrix(mat, exp) == expected def test_power_matrix_example2(): mat = [ [2, 0], [0, 2] ] ...
[ { "docstring": null, "function_declaration": "def multiply_matrices(A, B):", "function_name": "multiply_matrices", "parameter_list": "(A, B)" }, { "docstring": null, "function_declaration": "def identity_matrix(size):", "function_name": "identity_matrix", "parameter_list": "(size...
[ 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 identity_matrix(n: int) -> List[List[int]]:\n \"\"\"Generates an identity matrix of size nxn.\"\"\"\n return [[1 if i == ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033660", "row_id": 33660, "seed_ids": "[340]" }
0.541822
Data_Structure_33660
I
[ "multiply_matrices", "identity_matrix", "power_matrix" ]
3
[ [ "power_matrix", "identity_matrix" ], [ "power_matrix", "multiply_matrices" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5dc20b9040443892f0d04c0a7dcb75cc6eb96608
bdb1b4f4e31fa5bbce312b380181bddbfa28efac
v1.0
instruct
Data_Structure
Data_Structure_33661_I
### Question: Bitwise Array Sum #### Context You are working on a low-level system programming task where you need to perform additions without using the arithmetic '+' operator. Let's extend this need to an array of numbers instead of just two integers. #### Task Write a function `sum_array_bitwise(arr)` that takes ...
def bitwise_add(a, b): """ Helper function to add two integers using bitwise operations. """ while b != 0: carry = a & b a = a ^ b b = carry << 1 return a def sum_array_bitwise(arr): """ Returns the sum of the elements in array `arr` using bitwise operations. """...
from solution import sum_array_bitwise def test_sum_single_element(): assert sum_array_bitwise([5]) == 5 def test_sum_two_elements(): assert sum_array_bitwise([1, 2]) == 3 def test_sum_multiple_elements(): assert sum_array_bitwise([1, 2, 3, 4, 5]) == 15 def test_sum_with_zero(): assert sum_array...
[ { "docstring": "Helper function to add two integers using bitwise operations.", "function_declaration": "def bitwise_add(a, b):", "function_name": "bitwise_add", "parameter_list": "(a, b)" }, { "docstring": "Returns the sum of the elements in array `arr` using bitwise operations.", "func...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def add_bitwise(a, b):\n \"\"\"\n Helper function that adds two numbers using bitwise operations.\n \"\"\"\n while b != 0:\n carry = a & b\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033661", "row_id": 33661, "seed_ids": "[209]" }
0.628505
Data_Structure_33661
I
[ "bitwise_add", "sum_array_bitwise" ]
2
[ [ "sum_array_bitwise", "bitwise_add" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d3da87395e4376f7370bbc6d51627ba94fa44954
c3418e38c67c85e93245521c0eba4ecfdfd0e0ae
v1.0
instruct
Data_Structure
Data_Structure_33780_I
#### Scenario You've been provided a set of matrix transformation functions which include rotating and inverting the matrix. Your goal is to implement a new function that performs a chain of these transformations efficiently as specified by a command list. #### Problem Write a function `transform_matrix(matrix: List[L...
from typing import List def rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]: n = len(matrix) return [[matrix[n - j - 1][i] for j in range(n)] for i in range(n)] def rotate_counterclockwise(matrix: List[List[int]]) -> List[List[int]]: n = len(matrix) return [[matrix[j][n - i - 1] for j in ...
from solution import transform_matrix def test_rotate_clockwise(): matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] commands = ["rotate_clockwise"] expected = [ [7, 4, 1], [8, 5, 2], [9, 6, 3] ] assert transform_matrix(matrix, commands) == expected d...
[ { "docstring": null, "function_declaration": "def rotate_clockwise(matrix):", "function_name": "rotate_clockwise", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def rotate_counterclockwise(matrix):", "function_name": "rotate_counterclockwise", "par...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:\n return [list(row) for row in zip(*matrix[::-1])]\n\ndef rota...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033780", "row_id": 33780, "seed_ids": "[337]" }
0.556431
Data_Structure_33780
I
[ "rotate_clockwise", "rotate_counterclockwise", "top_left_invert", "bottom_left_invert", "transform_matrix" ]
5
[ [ "transform_matrix", "bottom_left_invert" ], [ "transform_matrix", "rotate_clockwise" ], [ "transform_matrix", "rotate_counterclockwise" ], [ "transform_matrix", "top_left_invert" ] ]
4
[]
false
[]
false
pytest
true
[]
true
a4e7a71eb82f8d6bc3fb1b7b8e5bc04a65ac4be0
410554dbb1a657f730f7838e4d67aa5cdd9ef504
v1.0
instruct
Data_Structure
Data_Structure_33793_I
Implement a Recursive Merge Sort #### Objective: Implement a Merge Sort algorithm to sort an array of integers, showcasing your understanding of divide-and-conquer strategies, recursive function implementation, and array manipulation. #### Description: Write a function `merge_sort(arr)` that sorts the given list of ...
from typing import List def merge_sort(arr: List[int]) -> List[int]: if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(left: List[int], right: List[int]) -> List[int]: sorted_array = [] ...
from solution import merge_sort def test_merge_sort_basic(): assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] def test_merge_sort_empty(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_already_sorted(): ...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n def merge(left: List[int], right: Li...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033793", "row_id": 33793, "seed_ids": "[12]" }
0.667237
Data_Structure_33793
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1f7bb1b8924c0a7afeb8ffb768333c31f1ea1f14
5cda5f023c778e79e8d91d4bc7974e891fd765b0
v1.0
instruct
Data_Structure
Data_Structure_33861_I
Heap Sort is a well-known sorting algorithm that can be implemented using either a max heap or a min heap. Based on the provided explanation and analysis, your task is to complete the implementation of the `min_heap_sort` function to sort an array in ascending order using a min heap. Complete the `min_heap_sort` func...
def min_heap_sort(arr, simulation=False): """ Heap Sort that uses a min heap to sort an array in ascending order. Args: - arr (List[int]): The list of integers to be sorted. - simulation (bool): If True, print the array at each iteration. Returns: - List[int]: Sorted list of integers...
from solution import min_heap_sort def test_min_heap_sort_empty(): assert min_heap_sort([]) == [] def test_min_heap_sort_single_element(): assert min_heap_sort([1]) == [1] def test_min_heap_sort_sorted(): assert min_heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_min_heap_sort_reverse_sorted(): ...
[ { "docstring": "Heap Sort that uses a min heap to sort an array in ascending order.\nArgs:\n - arr (List[int]): The list of integers to be sorted.\n - simulation (bool): If True, print the array at each iteration.\nReturns:\n - List[int]: Sorted list of integers.", "function_declaration": "def min_...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def min_heap_sort(arr, simulation=False):\n \"\"\"\n Heap Sort that uses a min heap to sort an array in ascending order.\n \n Args:\n - arr...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033861", "row_id": 33861, "seed_ids": "[8]" }
0.748386
Data_Structure_33861
I
[ "min_heap_sort", "heapify" ]
2
[ [ "min_heap_sort", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
82eb07a353ac71d852b5416828b895ec943a183a
f195e5536289355861ee272f1407580c69cdcc36
v1.0
instruct
Data_Structure
Data_Structure_33869_I
Implement and Optimize Radix Sort You are tasked with implementing an optimized version of Radix Sort. Given an input list of non-negative integers, your goal is to sort the list efficiently. You are required to demonstrate a good grasp of the Radix Sort algorithm, handling various edge cases effectively. #### Functi...
from typing import List def counting_sort(arr: List[int], exp: int, simulation: bool) -> None: n = len(arr) output = [0] * n # output array that will have sorted arr count = [0] * 10 # count array to store count of occurrences of digits # Store count of occurrences in count[] for i in range(n): ...
def test_sorted_sequence(): assert optimized_radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sequence(): assert optimized_radix_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_mixed_sequence(): assert optimized_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170,...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp, simulation):", "function_name": "counting_sort", "parameter_list": "(arr, exp, simulation)" }, { "docstring": null, "function_declaration": "def optimized_radix_sort(arr, simulation=False):", "function_name": "...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool) -> None:\n n = len(arr)\n output = [0] * n # output array that...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00033869", "row_id": 33869, "seed_ids": "[15]" }
0.602404
Data_Structure_33869
I
[ "counting_sort", "optimized_radix_sort" ]
2
[ [ "optimized_radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
false
[]
true
9901400b33738d16435abdf9711439f012ecc649
c88cbc7f197931f9e20c7c1c760db4d65adad7a7
v1.0
instruct
Data_Structure
Data_Structure_33910_I
We have discussed the Extended Euclidean Algorithm and how it can be used to find the modular inverse of a number. Now it's time to implement this to solve a real-world problem in cryptography. #### Problem Statement Alice wants to encrypt a message using the RSA algorithm. For this, she needs to generate a public a...
def extended_gcd(a, b): """ Extended Euclidean Algorithm. It returns a tuple (g, x, y) such that g = gcd(a, b) and a*x + b*y = g """ if b == 0: return a, 1, 0 g, x1, y1 = extended_gcd(b, a % b) x = y1 y = x1 - (a // b) * y1 return g, x, y def find_modular_inverse(e, phi_...
from solution import find_modular_inverse def test_find_modular_inverse_example1(): e = 3 phi_n = 26 d = find_modular_inverse(e, phi_n) assert (d * e) % phi_n == 1 assert 1 < d < phi_n def test_find_modular_inverse_example2(): e = 17 phi_n = 3120 d = find_modular_inverse(e, phi_n) ...
[ { "docstring": "Extended Euclidean Algorithm.\nIt returns a tuple (g, x, y) such that g = gcd(a, b) and a*x + b*y = g", "function_declaration": "def extended_gcd(a, b):", "function_name": "extended_gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the modular inverse 'd' of 'e' mod...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_modular_inverse(e: int, phi_n: int) -> int:\n def extended_gcd(a, b):\n if b == 0:\n return a, 1, 0\n gcd, x1, y1 = exten...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00033910", "row_id": 33910, "seed_ids": "[161]" }
0.553192
Data_Structure_33910
I
[ "extended_gcd", "find_modular_inverse" ]
2
[ [ "find_modular_inverse", "extended_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9de67ff6b2516ae4d1678b2122630a1a02ee7438
8246b6925a9313c28d8e63317f8f9057c8474574
v1.0
instruct
Data_Structure
Data_Structure_33920_I
**Scenario**: Alice and Bob work in a company that needs to securely exchange sensitive data. They decide to use Diffie-Hellman Key Exchange to generate a shared secret key. You need to help implement the system that will allow them to safely generate and exchange this key. **Task**: Write a Python function `secure_ke...
import random def is_prime(n): """Check if a number is a prime number.""" if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 ...
from solution import secure_key_exchange def test_basic_case(): assert secure_key_exchange(23, 5) == True def test_wrong_prime(): assert secure_key_exchange(15, 5) == False # 15 is not a prime number def test_wrong_primitive_root(): assert secure_key_exchange(23, 10) == False # 10 is not a primitive ro...
[ { "docstring": "Check if a number is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Find the smallest primitive root of a prime number p.", "function_declaration": "def primitive_root(p):", "functi...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_prime(n):\n \"\"\"Check if a number is a prime number.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00033920", "row_id": 33920, "seed_ids": "[146]" }
0.467915
Data_Structure_33920
I
[ "is_prime", "primitive_root", "gcd", "secure_key_exchange" ]
4
[ [ "primitive_root", "gcd" ], [ "primitive_root", "is_prime" ], [ "secure_key_exchange", "is_prime" ], [ "secure_key_exchange", "primitive_root" ] ]
4
[]
false
[]
false
pytest
true
[]
true
6ae99eb310993c2518ef58cb747905bcae564c4a
3f4a9ff3c03991dc6bd201d455feccd38d3f3174
v1.0
instruct
Data_Structure
Data_Structure_33932_I
### Question: Advanced GCD Calculation You are given two non-negative integers `a` and `b`. Your task is to implement two functions: 1. `gcd_advanced(a, b)`: This function should compute the greatest common divisor (GCD) of `a` and `b` using the bitwise operations strategy, incorporating all necessary error handling. ...
def gcd_advanced(a, b): """ Computes the greatest common divisor of a and b using bitwise operations. """ if a == 0: return b if b == 0: return a # Find the greatest power of 2 that divides both a and b shift = 0 while ((a | b) & 1) == 0: a >>= 1 b >>= 1 ...
from solution import gcd_advanced, lcm_advanced def test_gcd_advanced(): assert gcd_advanced(48, 18) == 6 assert gcd_advanced(0, 5) == 5 assert gcd_advanced(7, 0) == 7 assert gcd_advanced(24, 36) == 12 assert gcd_advanced(101, 103) == 1 def test_gcd_advanced_edge_cases(): assert gcd_advanced(0...
[ { "docstring": "Computes the greatest common divisor of a and b using bitwise operations.", "function_declaration": "def gcd_advanced(a, b):", "function_name": "gcd_advanced", "parameter_list": "(a, b)" }, { "docstring": "Computes the least common multiple of a and b using the gcd_advanced f...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def gcd_advanced(a, b):\n \"\"\"\n Computes the GCD of a and b using bitwise operations.\n \"\"\"\n if a == 0: return b\n if b == 0: return a\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033932", "row_id": 33932, "seed_ids": "[166]" }
0.703507
Data_Structure_33932
I
[ "gcd_advanced", "lcm_advanced" ]
2
[ [ "lcm_advanced", "gcd_advanced" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c4a9d67fceaf7163af64d97875cf4c1fdc2cfdd8
2a0c46e7a5a0cd37ddb1bfb82559cc8911d5209f
v1.0
instruct
Data_Structure
Data_Structure_33937_I
### Prime Validator Function Given the code snippet for checking if a number is prime, we want to extend its functionality. Write a function `prime_sum(start, end)` that calculates the sum of all prime numbers within a given inclusive range [start, end]. #### Input * An integer `start` (0 <= start <= 10^6) * An integ...
def prime_check(n): """ Check if a number is prime or not. Parameters: n (int): The number to check if prime Returns: bool: True if n is a prime number, False otherwise. """ if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 ...
from solution import prime_sum def test_prime_sum_case1(): assert prime_sum(10, 20) == 60 # Primes are 11, 13, 17, 19 def test_prime_sum_case2(): assert prime_sum(1, 10) == 17 # Primes are 2, 3, 5, 7 def test_prime_sum_case3(): assert prime_sum(20, 20) == 0 # There are no primes def test_prime_sum_si...
[ { "docstring": "Check if a number is prime or not.\n\nParameters:\nn (int): The number to check if prime\n\nReturns:\nbool: True if n is a prime number, False otherwise.", "function_declaration": "def prime_check(n):", "function_name": "prime_check", "parameter_list": "(n)" }, { "docstring":...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def prime_check(n):\n \"\"\"\n Check if the number 'n' is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ret...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033937", "row_id": 33937, "seed_ids": "[143]" }
0.640231
Data_Structure_33937
I
[ "prime_check", "prime_sum" ]
2
[ [ "prime_sum", "prime_check" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d3e27a05505e8a64b97d1b6fad0f6842be1d6a39
81a8f656834c4962e0e160bc004a1bfa189bda6d
v1.0
instruct
Data_Structure
Data_Structure_33986_I
### Question: Implement a More Efficient Sorting Algorithm You have seen an example of the Bogo Sort algorithm, a highly inefficient sorting method. Your task is to demonstrate your understanding of sorting algorithms by implementing a more efficient algorithm: Merge Sort. Merge Sort is a highly efficient, comparison...
def merge_sort(arr): """ Sorts an array of integers using the Merge Sort algorithm. Parameters: arr (list): A list of integers to be sorted. Returns: list: A new list of integers, sorted in ascending order. """ if len(arr) <= 1: return arr mid = len(arr) // 2 l...
from solution import merge_sort def test_merge_sort_empty(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_sorted_array(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_sorted_array(): assert me...
[ { "docstring": "Sorts an array of integers using the Merge Sort algorithm.\n\nParameters:\narr (list): A list of integers to be sorted.\n\nReturns:\nlist: A new list of integers, sorted in ascending order.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_li...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array of integers using the Merge Sort algorithm.\n \n Parameters:\n arr (list): A list of integers to...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033986", "row_id": 33986, "seed_ids": "[16]" }
0.621957
Data_Structure_33986
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6529c02e078e2a2726620414c1d8c76db82eabdc
ff3835b35d15e51f8d950e640a303e6b5653ea34
v1.0
instruct
Data_Structure
Data_Structure_34007_I
### Coding Assessment: Enhanced Quick Sort #### Context: Quick Sort is an efficient, general-purpose, comparison-based sorting algorithm. This assessment checks your understanding and ability to implement optimizations to the Quick Sort algorithm to handle edge cases effectively and improve overall performance. #### ...
import random def insertion_sort(arr, left, right): for i in range(left + 1, right + 1): key = arr[i] j = i - 1 while j >= left and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def enhanced_quick_sort(arr, threshold=10): if len(arr) <= 1: ...
from solution import enhanced_quick_sort def test_empty_array(): assert enhanced_quick_sort([]) == [] def test_single_element_array(): assert enhanced_quick_sort([1]) == [1] def test_sorted_array(): assert enhanced_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): asser...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr, left, right):", "function_name": "insertion_sort", "parameter_list": "(arr, left, right)" }, { "docstring": null, "function_declaration": "def enhanced_quick_sort(arr, threshold=10):", "function_name": "enhanced_qu...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef insertion_sort(arr, left, right):\n \"\"\"\n Sorts a portion of the array in place using Insertion Sort.\n \"\"\"\n for i in ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00034007", "row_id": 34007, "seed_ids": "[25]" }
0.606559
Data_Structure_34007
I
[ "insertion_sort", "enhanced_quick_sort" ]
2
[ [ "enhanced_quick_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7e7abcfe2e942720d6d5d73daf636d521f6a32f8
a87e64a5336f0186b255057a90ddbbbdb29ce09c
v1.0
instruct
Data_Structure
Data_Structure_34015_I
### Question: Implement Matrix Operations You are required to implement two key operations involving matrices: matrix exponentiation and determinant calculation. The provided implementations for matrix multiplication and identity matrix may be useful. #### Task 1: Matrix Exponentiation Write a function `matrix_power(m...
def multiply(mat1, mat2): """ Multiplies two matrices mat1 and mat2. """ n = len(mat1) result = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): for k in range(n): result[i][j] += mat1[i][k] * mat2[k][j] return result def identity(n): ...
from solution import matrix_power, determinant def test_matrix_power(): mat1 = [ [1, 2], [3, 4] ] assert matrix_power(mat1, 2) == [[7, 10], [15, 22]] mat2 = [ [2, 0], [0, 2] ] assert matrix_power(mat2, 3) == [[8, 0], [0, 8]] mat3 = [ [5] ...
[ { "docstring": "Multiplies two matrices mat1 and mat2.", "function_declaration": "def multiply(mat1, mat2):", "function_name": "multiply", "parameter_list": "(mat1, mat2)" }, { "docstring": "Returns an identity matrix of size n.", "function_declaration": "def identity(n):", "function...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def identity(size):\n \"\"\"\n Creates an identity matrix of given size\n \"\"\"\n return [[1 if i == j else 0 for j in range(size)] for i in rang...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00034015", "row_id": 34015, "seed_ids": "[340]" }
0.478619
Data_Structure_34015
I
[ "multiply", "identity", "matrix_power", "determinant" ]
4
[ [ "matrix_power", "identity" ], [ "matrix_power", "multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
8550cdb7c6d604f58e96ad7fce7cc724c879c6de
89c14d063f89fe701b1b4f50a29e56a0a095778e
v1.0
instruct
Data_Structure
Data_Structure_34019_I
### Sorting Algorithm Challenge: Stooge Sort Enhancement **Context**: You have been provided with the Stooge Sort algorithm which is a recursive sorting algorithm having a worst-case time complexity of O(n^2.709). Despite its inefficiency in sorting large arrays, it offers a fundamental learning opportunity for unde...
from typing import List def is_sorted(arr: List[int], l: int, h: int) -> bool: for i in range(l, h): if arr[i] > arr[i + 1]: return False return True def optimized_stoogesort(arr: List[int], l: int, h: int) -> List[int]: # Base case: if the subarray has one or no elements, it's already...
from solution import optimized_stoogesort def test_empty_array(): assert optimized_stoogesort([], 0, -1) == [] def test_single_element_array(): arr = [1] assert optimized_stoogesort(arr, 0, 0) == [1] def test_sorted_array(): arr = [1, 2, 3, 4, 5] assert optimized_stoogesort(arr, 0, 4) == [1, 2, 3...
[ { "docstring": null, "function_declaration": "def is_sorted(arr, l, h):", "function_name": "is_sorted", "parameter_list": "(arr, l, h)" }, { "docstring": null, "function_declaration": "def optimized_stoogesort(arr, l, h):", "function_name": "optimized_stoogesort", "parameter_list...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef optimized_stoogesort(arr: List[int], l: int, h: int) -> List[int]:\n \"\"\"\n Sorts the subarray arr[l:h+1] using the opt...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00034019", "row_id": 34019, "seed_ids": "[10]" }
0.609046
Data_Structure_34019
I
[ "is_sorted", "optimized_stoogesort" ]
2
[ [ "optimized_stoogesort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4cce0dc11b9ed80de0b55bd72d2f26611d5bc970
9d2818caeceac1dca7dbb89bcd7e591f7517b8b7
v1.0
instruct
Data_Structure
Data_Structure_34113_I
You are required to implement a sorting function that sorts an array of integers using the Radix Sort algorithm. Additionally, your function should be able to handle some potential edge cases and ensure stability during sorting. ### Function Signature ```python def radix_sort(arr: List[int]) -> List[int]: ``` ### In...
from typing import List def counting_sort(arr: List[int], exp: int) -> List[int]: n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = arr[i] // exp count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] for i in range(n - 1, -1, -...
from solution import radix_sort def test_radix_sort_example(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802], "Error in test case example" def test_radix_sort_all_same(): assert radix_sort([3, 3, 3, 3]) == [3, 3, 3, 3], "Error in test case with all same elements" d...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp):", "function_name": "counting_sort", "parameter_list": "(arr, exp)" }, { "docstring": null, "function_declaration": "def radix_sort(arr):", "function_name": "radix_sort", "parameter_list": "(arr)" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef radix_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of integers using the Radix Sort algorithm.\n \"\"\"\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00034113", "row_id": 34113, "seed_ids": "[15]" }
0.621814
Data_Structure_34113
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7e950775ad2c31e4cec2d74c0f6ef53a86459546
b27f836313ec85282a9837acb76d1ad3fb44196a
v1.0
instruct
Data_Structure
Data_Structure_34123_I
### Nearest Neighbor Classification Challenge #### Background In pattern recognition, a simple yet powerful algorithm is the Nearest Neighbor algorithm. Given a set of training data, where each data point is a vector assigned to a class or label, the algorithm determines the class of a new point by finding the class o...
import math def distance(x, y): """ Calculate the Euclidean distance between vectors x and y. """ assert len(x) == len(y), "The vectors must have the same length" return math.sqrt(sum((a - b) ** 2 for a, b in zip(x, y))) def nearest_neighbor(x, tSet): """ Classify a new data point x by fin...
from solution import nearest_neighbor def test_nearest_neighbor_single_entry(): tSet = { (2.0, 3.0): 'Class_A' } assert nearest_neighbor((1.0, 2.0), tSet) == 'Class_A' def test_nearest_neighbor_multiple_entries(): tSet = { (2.0, 3.0): 'Class_A', (1.0, 2.0): 'Class_B', (...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef distance(x, y):\n \"\"\"\n Calculate the Euclidean distance between vectors x and y.\n\n Arguments:\n x, y: Tuple of numeri...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00034123", "row_id": 34123, "seed_ids": "[260]" }
0.668375
Data_Structure_34123
I
[ "distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0f3ffc19cd22a1cebdd697a0506ee7389abe20bc
c253c3b558fa4dec7ee0f280ff1f0d671dc8b7f6
v1.0
instruct
Data_Structure
Data_Structure_34159_I
#### Scenario You are tasked with automating a pattern recognition system for a playlist application. Your system needs to identify repeated patterns within a list of song titles. Specifically, you need a function that determines how many times a given list of song titles needs to be repeated such that a target sequenc...
def minimum_repeats(song_list, target_sequence): """ Returns the minimum number of times the song_list needs to be repeated so that the target_sequence appears as a subgroup in the repeated list. If no such repetition can achieve this, return -1. """ n = len(song_list) m = len(target_se...
def test_minimum_repeats_example(): assert minimum_repeats(["hello", "world"], ["world", "hello", "world"]) == 2 def test_minimum_repeats_no_repeats_needed(): assert minimum_repeats(["a", "b", "c"], ["b", "c"]) == 1 def test_minimum_repeats_needs_repeating(): assert minimum_repeats(["a", "b"], ["b", "a", ...
[ { "docstring": "Returns the minimum number of times the song_list needs to be repeated\nso that the target_sequence appears as a subgroup in the repeated list.\n\nIf no such repetition can achieve this, return -1.", "function_declaration": "def minimum_repeats(song_list, target_sequence):", "function_na...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def minimum_repeats(song_list, target_sequence):\n \"\"\"\n Returns the minimum number of repetitions of song_list\n such that target_sequence is a s...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00034159", "row_id": 34159, "seed_ids": "[97]" }
0.594164
Data_Structure_34159
I
[ "minimum_repeats", "list_contains_sublist" ]
2
[ [ "minimum_repeats", "list_contains_sublist" ] ]
1
[]
false
[]
false
pytest
false
[]
true
2444793b4e65f0d0cb4efd1853b0ea1429a68f04
624ec87b991d73947f92147dbf0d39ec89785729
v1.0
instruct
Data_Structure
Data_Structure_34183_I
### Bucket Sort Enhancement You are provided with an implementation of the Bucket Sort algorithm which uses `next_sort` (insertion sort) to sort elements within each bucket. This implementation has a time complexity of O(n^2) in the worst case due to the use of insertion sort. Your task is to improve the performance o...
def optimized_sort(arr): """ Sort the input list using Timsort (as implemented by Python's sorted function) and return the sorted list. """ return sorted(arr) def bucket_sort(arr): if not arr: return arr num_buckets = len(arr) max_value = max(arr) buckets = [[] for _ in range(n...
from solution import optimized_sort, bucket_sort def test_optimized_sort_empty(): assert optimized_sort([]) == [] def test_optimized_sort_single_element(): assert optimized_sort([1]) == [1] def test_optimized_sort_already_sorted(): assert optimized_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_optim...
[ { "docstring": "Sort the input list using Timsort (as implemented by Python's sorted function) and return the sorted list.", "function_declaration": "def optimized_sort(arr):", "function_name": "optimized_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "d...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def optimized_sort(arr):\n \"\"\"\n Sort the input list using a Timsort (via sorted() function) and return the sorted list.\n \"\"\"\n return sort...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00034183", "row_id": 34183, "seed_ids": "[26]" }
0.572227
Data_Structure_34183
I
[ "optimized_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "optimized_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1c26ab42ba539600e8637cba8c256e8e7be99c4c
8ecf31e5da48a45a44e77864c5c711039b1cf4a8
v1.0
instruct
Data_Structure
Data_Structure_34212_I
### Scenario A digital signature algorithm requires the use of modular inverses to secure data. Given integers \( a \) and \( m \), you need to compute the modular inverse of \( a \) modulo \( m \). If the modular inverse doesn't exist (i.e., \( a \) and \( m \) are not coprime), the function should return -1. ### Tas...
def extended_gcd(a, b): """ Extended Euclidean Algorithm to find the coefficients x and y such that: ax + by = gcd(a, b) """ if a == 0: return b, 0, 1 gcd, x1, y1 = extended_gcd(b % a, a) x = y1 - (b // a) * x1 y = x1 return gcd, x, y def compute_modular_inverse(a: int, m: i...
from solution import compute_modular_inverse def test_inverse_exists(): assert compute_modular_inverse(3, 11) == 4 # Explanation: 3 * 4 = 12, 12 % 11 = 1 assert compute_modular_inverse(7, 26) == 15 # Explanation: 7 * 15 = 105, 105 % 26 = 1 def test_inverse_not_exists(): assert compute_modular_inverse(10...
[ { "docstring": "Extended Euclidean Algorithm to find the coefficients x and y such that:\nax + by = gcd(a, b)", "function_declaration": "def extended_gcd(a, b):", "function_name": "extended_gcd", "parameter_list": "(a, b)" }, { "docstring": "Computes the modular inverse of `a` modulo `m` usi...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def extended_gcd(a, b):\n \"\"\"\n Extended Euclidean Algorithm to find the coefficients x and y such that:\n ax + by = gcd(a, b)\n \"\"\"\n if...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00034212", "row_id": 34212, "seed_ids": "[161]" }
0.570996
Data_Structure_34212
I
[ "extended_gcd", "compute_modular_inverse" ]
2
[ [ "compute_modular_inverse", "extended_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
592008546864692928686e5b80ed98ef11c49e1a
09052e9816c0b0bb7359dc13306e9f3d8a539668
v1.0
instruct
Data_Structure
Data_Structure_34219_I
### Binary Search Tree Balanced Insertion Algorithm #### Context A Binary Search Tree (BST) is effective but can degenerate into a linked list in the worst case, especially with sequential data insertions. To mitigate this, we need to implement a balanced insertion mechanism. This ensures that the height of the tree r...
class TreeNode: def __init__(self, key): self.left = None self.right = None self.height = 1 # Height of node in the AVL tree self.key = key class BST: def __init__(self): self.root = None def insert(self, key): if self.root is None: self.roo...
import pytest from solution import BST, bst_insert_balanced def test_empty_tree_insertion(): tree = BST() tree.insert(10) assert tree.root is not None assert tree.root.key == 10 assert tree.root.left is None assert tree.root.right is None assert tree.root.height == 1 def test_insert_mainta...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n self.height = 1 # Height ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00034219", "row_id": 34219, "seed_ids": "[318]" }
0.616693
Data_Structure_34219
I
[ "bst_insert_balanced", "rotate_left", "rotate_right", "get_height", "get_balance" ]
5
[ [ "bst_insert_balanced", "get_balance" ], [ "bst_insert_balanced", "get_height" ], [ "bst_insert_balanced", "rotate_left" ], [ "bst_insert_balanced", "rotate_right" ], [ "get_balance", "get_height" ], [ "rotate_left", "get_height" ], [ "rot...
7
[]
false
[ "TreeNode", "BST" ]
true
pytest
true
[]
true
5d42353daddf82779b8b02ba55594bb0744731dd
d870ebcd29a39d4122ea6385cd700778d6ea91e5
v1.0
instruct
Data_Structure
Data_Structure_34251_I
### Word Squares Construction **Objective**: Implement a function to find all possible word squares from a given list of words. **Scenario**: You are designing a crossword puzzle and need to ensure that certain word sequences form valid word squares. Each word sequence must have its k-th row and column reading the ex...
from typing import List, Dict from collections import defaultdict def build_prefix_dict(words: List[str], word_length: int) -> Dict[str, List[str]]: prefix_dict = defaultdict(list) for word in words: for i in range(word_length): prefix_dict[word[:i]].append(word) return prefix_dict def...
from solution import word_squares def test_example_case(): words = ["area", "lead", "wall", "lady", "ball"] result = word_squares(words) expected = [ ["wall", "area", "lead", "lady"], ["ball", "area", "lead", "lady"] ] assert sorted(result) == sorted(expected) def test_single_word(...
[ { "docstring": null, "function_declaration": "def build_prefix_dict(words, word_length):", "function_name": "build_prefix_dict", "parameter_list": "(words, word_length)" }, { "docstring": null, "function_declaration": "def backtrack(step, word_length, square, prefix_dict, results):", ...
[ 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\nfrom collections import defaultdict\n\ndef word_squares(words: List[str]) -> List[List[str]]:\n def build_prefix_dict(words):\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00034251", "row_id": 34251, "seed_ids": "[87]" }
0.56417
Data_Structure_34251
I
[ "build_prefix_dict", "backtrack", "word_squares" ]
3
[ [ "word_squares", "backtrack" ], [ "word_squares", "build_prefix_dict" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f022c797fcea4fd96e5dc81d723c7e3dbdda993b
708216a92452b65c05d4fd103df79f9e454f3405
v1.0
instruct
Data_Structure
Data_Structure_34267_I
Your task is to implement the insertion sort algorithm using a helper function that uses binary search to determine the correct insertion point for the next element in the partially sorted array. This will help minimize comparisons needed to find the correct position of the element. **Function Signature**: ```python ...
from typing import List def binary_search_insert_position(array: List[int], left: int, right: int, key: int) -> int: """ Perform binary search to find the correct insertion point for the key in the subarray array[left:right+1]. """ while left <= right: mid = left + (right - left) // 2 i...
from solution import binary_insertion_sort def test_binary_insertion_sort_example_case(): assert binary_insertion_sort([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13] def test_binary_insertion_sort_empty(): assert binary_insertion_sort([]) == [] def test_binary_insertion_sort_sorted(): assert binary_insertion_...
[ { "docstring": "Perform binary search to find the correct insertion point for the key in the subarray array[left:right+1].", "function_declaration": "def binary_search_insert_position(array, left, right, key):", "function_name": "binary_search_insert_position", "parameter_list": "(array, left, right...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport bisect\n\ndef binary_insertion_sort(array: List[int]) -> List[int]:\n \"\"\"\n Sort the array using binary insertion sor...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00034267", "row_id": 34267, "seed_ids": "[199]" }
0.573891
Data_Structure_34267
I
[ "binary_search_insert_position", "binary_insertion_sort" ]
2
[ [ "binary_insertion_sort", "binary_search_insert_position" ] ]
1
[]
false
[]
false
pytest
true
[]
true
40471d01cc521bf39c442162a2bc1d92ad7abbca
d465e1477e3d17925b77555a57d67f65ddede34c
v1.0
instruct
Data_Structure
Data_Structure_34268_I
Improved Bucket Sort Implementation You are tasked with implementing a more robust and efficient version of the Bucket Sort algorithm. The current implementation uses Insertion Sort to sort the elements within each bucket, which can be inefficient for larger datasets. Moreover, the current approach does not handle edg...
from typing import List def quicksort(arr): """Helper function to sort a given list using QuickSort algorithm.""" if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] ...
from solution import improved_bucket_sort def test_improved_bucket_sort_empty_array(): assert improved_bucket_sort([]) == [] def test_improved_bucket_sort_all_identical_elements(): assert improved_bucket_sort([0.23, 0.23, 0.23, 0.23]) == [0.23, 0.23, 0.23, 0.23] def test_improved_bucket_sort_example_case(): ...
[ { "docstring": "Helper function to sort a given list using QuickSort algorithm.", "function_declaration": "def quicksort(arr):", "function_name": "quicksort", "parameter_list": "(arr)" }, { "docstring": "Sort the array using the improved bucket sort algorithm.", "function_declaration": "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport math\n\ndef improved_bucket_sort(arr: List[float]) -> List[float]:\n \"\"\"\n Sorts a list of floating point numbers bet...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00034268", "row_id": 34268, "seed_ids": "[26]" }
0.557416
Data_Structure_34268
I
[ "quicksort", "improved_bucket_sort" ]
2
[ [ "improved_bucket_sort", "quicksort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4a881e0bc06bb39bce5f849e8e14c2b71444e3bf
d14a4d50d150f4f78dfccf974968d238eec18efd
v1.0
instruct
Data_Structure
Data_Structure_34284_I
### Context Alice and Bob want to communicate securely using the Diffie-Hellman key exchange algorithm. They must ensure their exchange is protected by using a large prime number and its primitive root. The key exchange will involve both parties keeping their private keys secret while sharing their respective public ke...
from sympy.ntheory import isprime, totient from random import randint def find_primitive_root(p): if not isprime(p): return -1 phi = p - 1 primitive_roots = [] for a in range(1, p): is_primitive_root = True for q in set(factorize(phi)): if pow(a, phi // q, p) ==...
def test_secure_diffie_hellman_key_exchange_valid_key(): assert secure_diffie_hellman_key_exchange(5, 23) == True def test_secure_diffie_hellman_key_exchange_not_primitive_root(): assert secure_diffie_hellman_key_exchange(2, 23) == False # 2 is not a primitive root mod 23 def test_secure_diffie_hellman_key_e...
[ { "docstring": null, "function_declaration": "def find_primitive_root(p):", "function_name": "find_primitive_root", "parameter_list": "(p)" }, { "docstring": "Returns a list of prime factors of the given number `n` ", "function_declaration": "def factorize(n):", "function_name": "fac...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, totient\n\ndef is_primitive_root(a, p):\n if not isprime(p):\n return False\n \n required_set = set(...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00034284", "row_id": 34284, "seed_ids": "[146]" }
0.445553
Data_Structure_34284
I
[ "find_primitive_root", "factorize", "secure_diffie_hellman_key_exchange" ]
3
[ [ "find_primitive_root", "factorize" ], [ "secure_diffie_hellman_key_exchange", "find_primitive_root" ] ]
2
[]
false
[]
false
pytest
false
[ "sympy" ]
false
52329b74a672c243ec006500e83315206f835a5e
3f3cf13dbb2b4cb7acda15fb753645ff38c9ce10