version
stringclasses
1 value
style
stringclasses
2 values
subset
stringclasses
12 values
question_id
stringlengths
9
23
question
stringlengths
27
8.13k
solution
stringlengths
99
5.97k
test
stringlengths
105
4.45k
test_info
listlengths
0
13
gpt_pass_sequence
listlengths
1
10
gpt_pass_trial_num
int64
1
10
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
trials
dict
chosen_trial
stringclasses
10 values
metadata
dict
benchmark_similarity
float64
0.16
0.93
benchmark_instruction
stringclasses
1 value
benchmark_task_id
stringclasses
1 value
filter_reason
stringclasses
1 value
base_id
stringlengths
7
21
variant
stringclasses
2 values
top_function_names
listlengths
2
13
n_top_functions
int64
2
13
helper_call_edges
listlengths
1
16
n_helper_call_edges
int64
1
16
harness_functions
listlengths
0
3
structural_wrapper
bool
1 class
class_names
listlengths
0
5
has_class
bool
2 classes
test_kind
stringclasses
1 value
test_has_solution_import
bool
2 classes
third_party_imports
listlengths
0
5
stdlib_only
bool
2 classes
question_norm_sha1
stringlengths
40
40
solution_ast_sha1
stringlengths
40
40
v1.0
complete
Data_Structure
Data_Structure_30103_C
def compute_max_flow(network: list[list[int]]) -> int: """ Calculates the maximum flow of data from the source (0) to the target (last node) in a flow network. :param network: A 2D list of integers representing the adjacency matrix of the flow network. network[i][j] is the capacity ...
from collections import deque def bfs(rGraph, s, t, parent): visited = [False] * len(rGraph) queue = deque([s]) visited[s] = True while queue: u = queue.popleft() for v, capacity in enumerate(rGraph[u]): if not visited[v] and capacity > 0: # Not yet visited and there's ca...
from solution import compute_max_flow def test_simple_network(): network = [ [0, 10, 0, 0], [0, 0, 4, 6], [0, 0, 0, 10], [0, 0, 0, 0] ] assert compute_max_flow(network) == 10 def test_medium_network(): network = [ [0, 10, 10, 0], [0, 0, 10, 10], ...
[ { "docstring": null, "function_declaration": "def bfs(rGraph, s, t, parent):", "function_name": "bfs", "parameter_list": "(rGraph, s, t, parent)" }, { "docstring": null, "function_declaration": "def compute_max_flow(network):", "function_name": "compute_max_flow", "parameter_list...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef bfs(residual_graph, source, sink, parent):\n \"\"\"\n Standard BFS to find if there is a path from source to sink i...
trial_gpt4o_2
{ "original_instruction": "### Problem: Max Flow in An Augmented Flow Network\n\nAs a network engineer, you are given a task to determine the maximum flow of data that can be pushed from a source server to a target server in a data center. The network architecture can be represented as a directed graph, where each no...
0.552376
Data_Structure_30103
C
[ "bfs", "compute_max_flow" ]
2
[ [ "compute_max_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c83c0cb86964dd24ecf66f5c5f09c4a56c7721e3
a38e50fc9ead44fc5f9433bb6c3384d71ecf9501
v1.0
complete
Data_Structure
Data_Structure_30203_C
from typing import List def is_self_descriptive_number(n: int) -> bool: """ Checks if a number is a self-descriptive power sum number. """ digits = [int(d) for d in str(n)] power_sum = sum(digit ** (i + 1) for i, digit in enumerate(digits)) return power_sum == n def find_self_descriptive_numbe...
from typing import List def is_self_descriptive_number(n: int) -> bool: """ Checks if a number is a self-descriptive power sum number. """ digits = [int(d) for d in str(n)] power_sum = sum(digit ** (i + 1) for i, digit in enumerate(digits)) return power_sum == n def find_self_descriptive_numbe...
from solution import find_self_descriptive_numbers, is_self_descriptive_number def test_is_self_descriptive_number(): assert is_self_descriptive_number(89) == True assert is_self_descriptive_number(135) == True assert is_self_descriptive_number(1) == True assert is_self_descriptive_number(12) == False ...
[ { "docstring": "Checks if a number is a self-descriptive power sum number.", "function_declaration": "def is_self_descriptive_number(n):", "function_name": "is_self_descriptive_number", "parameter_list": "(n)" }, { "docstring": "Returns a list of self-descriptive power sum numbers in the ran...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_self_descriptive_number(n: int) -> bool:\n \"\"\"\n Checks if a number is a self-descriptive power sum number.\n \"...
trial_gpt4o_0
{ "original_instruction": "In number theory, a self-descriptive power sum number is a number in which the sum of its digits raised to consecutive powers equals the number itself. For example, 89 is a self-descriptive power sum number because \\(8^1 + 9^2 = 89\\), and 135 is another such number since \\(1^1 + 3^2 + 5^...
0.607813
Data_Structure_30203
C
[ "is_self_descriptive_number", "find_self_descriptive_numbers" ]
2
[ [ "find_self_descriptive_numbers", "is_self_descriptive_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
69461f260d2372241f8c1092bb83562b6b5068ac
17bddf73c3a3d1f3646e810e048b6bd3ab3b9ac3
v1.0
complete
Data_Structure
Data_Structure_30061_C
from typing import List def enhanced_radix_sort(arr: List[int], simulation: bool = False) -> List[int]: """ Enhanced Radix Sort function to sort a list of non-negative integers. Arguments: arr: List[int] -- a list of non-negative integers to be sorted. simulation: bool (optional) -- flag to print the a...
from typing import List def enhanced_radix_sort(arr: List[int], simulation: bool = False) -> List[int]: if not arr: return [] max_num = max(arr) exp = 1 base = 10 while max_num // exp > 0: arr = counting_sort_by_digit(arr, exp, base) if simulation: print(f"...
from solution import enhanced_radix_sort def test_enhanced_radix_sort_empty_list(): assert enhanced_radix_sort([]) == [] def test_enhanced_radix_sort_single_element(): assert enhanced_radix_sort([1]) == [1] def test_enhanced_radix_sort_duplicates(): assert enhanced_radix_sort([5, 5, 5, 5]) == [5, 5, 5, 5...
[ { "docstring": null, "function_declaration": "def enhanced_radix_sort(arr, simulation=False):", "function_name": "enhanced_radix_sort", "parameter_list": "(arr, simulation=False)" }, { "docstring": null, "function_declaration": "def counting_sort_by_digit(arr, exp, base):", "function...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef enhanced_radix_sort(arr: List[int], simulation: bool = False) -> List[int]:\n if len(arr) == 0:\n return arr\n\n b...
trial_gpt4o_2
{ "original_instruction": "### Programming Task: Implementing Enhanced Radix Sort\n\n#### Scenario\nRadix Sort is especially useful for sorting large datasets of non-negative integers. You've been assigned to improve the radix sort implementation for an even distribution of numbers and ensure it handles the edge case...
0.67184
Data_Structure_30061
C
[ "enhanced_radix_sort", "counting_sort_by_digit" ]
2
[ [ "enhanced_radix_sort", "counting_sort_by_digit" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dd7bfef873c90ca09cdd9f56b347f946baaf6329
417006eb84587f82d5e558ef60ac929e1870c1bf
v1.0
complete
Data_Structure
Data_Structure_30246_C
from typing import List def enhanced_pancake_sort(arr: List[int]) -> List[int]: """ Sorts a given list of integers (representing pancake sizes) using the pancake sort algorithm and handles specific error scenarios. >>> enhanced_pancake_sort([3, 6, 2, 5, 8]) [2, 3, 5, 6, 8] >>> enhanced_pa...
from typing import List def flip(arr: List[int], k: int) -> None: """ Function to reverse the first k elements of the array """ arr[:k] = arr[:k][::-1] def find_max_index(arr: List[int], n: int) -> int: """ Function to find the index of the maximum element in arr[0:n] """ max_index = 0...
from solution import enhanced_pancake_sort import pytest def test_empty_list(): assert enhanced_pancake_sort([]) == [] def test_single_element_list(): assert enhanced_pancake_sort([5]) == [5] def test_sorted_list(): assert enhanced_pancake_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted...
[ { "docstring": "Function to reverse the first k elements of the array", "function_declaration": "def flip(arr, k):", "function_name": "flip", "parameter_list": "(arr, k)" }, { "docstring": "Function to find the index of the maximum element in arr[0:n]", "function_declaration": "def find_...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def enhanced_pancake_sort(arr):\n def flip(arr, k):\n return arr[:k+1][::-1] + arr[k+1:]\n\n def find_max_index(arr, n):\n max_index = 0\n...
trial_gpt4o_2
{ "original_instruction": "### Pancake Sorting with Error Handling\n\n**Context**:\nYou are developing a feature for a bakery’s inventory management system. The bakery wants to organize the pancakes by size, from the smallest on top to the largest at the bottom, using a series of pancake flips.\n\n**Problem**:\nImple...
0.737364
Data_Structure_30246
C
[ "flip", "find_max_index", "enhanced_pancake_sort" ]
3
[ [ "enhanced_pancake_sort", "find_max_index" ], [ "enhanced_pancake_sort", "flip" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c3f65143eb26003fcea78b15eb5a87313c2f62cb
63f83682d8fa734a127c554c6fc144c7501ca0cf
v1.0
complete
Data_Structure
Data_Structure_30263_C
def merge_sort(arr: list) -> list: """ Sorts the input list using merge sort in descending order. >>> merge_sort([34, 7, 23, 32, 5, 62]) [62, 34, 32, 23, 7, 5] >>> merge_sort([1, 4, 5, 7]) [7, 5, 4, 1] >>> merge_sort([10]) [10] >>> merge_sort([]) [] """ # Logic...
def merge_sort(arr): """ Sorts the input list using merge sort in descending order. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) merged = [None] * (len(left) + len(right)) merge(left, right, merged) retu...
import pytest from solution import merge_sort def test_merge_sort_multiple_elements(): assert merge_sort([34, 7, 23, 32, 5, 62]) == [62, 34, 32, 23, 7, 5] def test_merge_sort_sorted_asc(): assert merge_sort([1, 4, 5, 7]) == [7, 5, 4, 1] def test_merge_sort_sorted_desc(): assert merge_sort([7, 5, 4, 1]) =...
[ { "docstring": "Sorts the input list using merge sort in descending order.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merges two sorted lists into one in descending order.", "function_declaration": "def me...
[ 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: list) -> list:\n \"\"\"\n Perform merge sort on the given list in descending order.\n \"\"\"\n if len(arr) <= 1:\n retu...
trial_gpt4o_2
{ "original_instruction": "### Scenario\nYou are given the task of sorting a list of students' scores. These scores can range from 0 to 100. You'll use the merge sort algorithm provided in the code snippets, but with an added constraint: you need to sort them in descending order, rather than ascending order.\n\n### T...
0.595756
Data_Structure_30263
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4d9ebebfc94ba2992aba2975c60eab4d5b390124
eb4563b5a26d11124aa49ba666371cb210919844
v1.0
complete
Data_Structure
Data_Structure_29916_C
from typing import List def compute_maximum_water_flow(adj_matrix: List[List[int]]) -> int: """ Compute the maximum amount of water that can be pushed from the source node to the sink node in the city's pipeline system, represented using an adjacency matrix. >>> adj_matrix = [ ... [0, 16, 13,...
from collections import deque from typing import List def bfs(residual_graph, source, sink, parent): visited = [False] * len(residual_graph) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() for ind, val in enumerate(residual_graph[u]): if not...
from solution import compute_maximum_water_flow def test_case_1(): adj_matrix = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] assert compute_maximum_water_flow(adj_matrix) == 2...
[ { "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 compute_maximum_water_flow(adj_matrix):", "function_n...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(residual_capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n ...
trial_gpt4o_2
{ "original_instruction": "**Context**: You are given the task of designing a network flow system that can handle water distribution in a city. The city has different junctions (nodes) and pipes (edges) with varying capacities.\n\n**Problem**: Implement a function to compute the maximum amount of water that can be pu...
0.641584
Data_Structure_29916
C
[ "bfs", "compute_maximum_water_flow" ]
2
[ [ "compute_maximum_water_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
618de58132e1bd860d96b85cd34e8f3913cab107
98d767c9180f4755e519cf4ee2788a99da501e3c
v1.0
complete
Data_Structure
Data_Structure_30254_C
import heapq from collections import Counter from typing import Any, Dict, List, Tuple class Node: def __init__(self, char: str, freq: int): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def ...
import heapq from collections import defaultdict, Counter from typing import Any, Dict, List, Tuple class Node: def __init__(self, char: str, freq: int): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < oth...
from solution import Node, perform_huffman_encoding def validate_huffman_tree(node: Node, expected_nodes: List[Tuple[str, int]]): result_nodes = [] def traverse(node: Node): if node is None: return if node.char: result_nodes.append((node.char, node.freq)) travers...
[]
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\nfrom collections import defaultdict\nfrom typing import Tuple, Any\n\nclass Node:\n def __init__(self, char: Any, freq: int):\n self.c...
trial_gpt4o_6
{ "original_instruction": "#### Scenario\nYou are tasked with creating a custom file compression system using Huffman Coding. The files to be compressed consist of plain text files which may contain any dictionary-based language text input. \n\n#### Requirements\nThe goal is to implement a function `perform_huffman_e...
0.483594
Data_Structure_30254
C
[ "build_huffman_tree", "generate_huffman_codes", "perform_huffman_encoding" ]
3
[ [ "perform_huffman_encoding", "build_huffman_tree" ], [ "perform_huffman_encoding", "generate_huffman_codes" ] ]
2
[]
false
[ "Node" ]
true
pytest
true
[]
true
72fc89116d4766a27887aeaa7f1e3d46bdd83185
ab15c0ab37008dd7ceb0c5deb18ad2d2c95128cc
v1.0
complete
Data_Structure
Data_Structure_29937_C
from typing import List def search_insert(arr: List[int], num: int) -> int: """ Uses binary search to find the index where 'num' should be inserted in 'arr' to maintain sorted order. """ low, high = 0, len(arr) while low < high: mid = (low + high) // 2 if arr[mid] < num: ...
from typing import List def search_insert(arr: List[int], num: int) -> int: """ Uses binary search to find the index where 'num' should be inserted in 'arr' to maintain sorted order. """ low, high = 0, len(arr) while low < high: mid = (low + high) // 2 if arr[mid] < num: ...
from solution import insertion_sort def test_insertion_sort_sample_cases(): assert insertion_sort([3, 1, 4, 1, 5]) == [1, 1, 3, 4, 5] assert insertion_sort([0, -1, 2, -3, 5, 6, -7]) == [-7, -3, -1, 0, 2, 5, 6] assert insertion_sort([10, 20, 30, 10, 5]) == [5, 10, 10, 20, 30] assert insertion_sort([]) =...
[ { "docstring": "Uses binary search to find the index where 'num' should be inserted in 'arr' to maintain sorted order.", "function_declaration": "def search_insert(arr, num):", "function_name": "search_insert", "parameter_list": "(arr, num)" }, { "docstring": "Sorts a list of integers in non...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef search_insert(arr: List[int], low: int, high: int, key: int) -> int:\n while low < high:\n mid = (low + high) // 2\n ...
trial_gpt4o_2
{ "original_instruction": "You have been tasked with completing the implementation of the insertion sort algorithm using the provided helper method `search_insert`. The goal is to sort a given list of integers in non-decreasing order efficiently.\n\n### Function Signature\n```python\ndef insertion_sort(arr: List[int]...
0.66864
Data_Structure_29937
C
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
624cd3b3af176e4df4d5681efb849c6755e281f8
14cece4cd78041ca7f66ee167bcbe2f518eedab5
v1.0
complete
Data_Structure
Data_Structure_29994_C
import random def guided_bogo_sort(arr: list) -> list: """ Sorts an array using a guided bogo sort mechanism. Instead of purely random shuffling, it introduces a guided shuffle that aims to reduce some level of randomness by leveraging partial order knowledge. The guided shuffle attempts to maintain ...
import random def is_sorted(arr): """ Checks if the array is sorted in ascending order. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def guided_shuffle(arr): """ Performs a guided shuffle by randomly swapping adjacent elements. ...
from solution import guided_bogo_sort def test_small_sorted_list(): assert guided_bogo_sort([1, 2, 3]) == [1, 2, 3] def test_small_random_list(): assert guided_bogo_sort([3, 1, 2]) == [1, 2, 3] def test_repeated_elements(): assert guided_bogo_sort([10, -10, 10]) == [-10, 10, 10] def test_single_element(...
[ { "docstring": "Checks if the array is sorted in ascending order.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Performs a guided shuffle by randomly swapping adjacent elements.", "function_declaration": "def g...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if the list is sorted.\n \"\"\"\n for i in range(len(arr) - 1):\n ...
trial_gpt4o_2
{ "original_instruction": "**Coding Assessment Question**\n\n### Context\nYou are tasked with improving an ancient sorting machine lying in the archives of your comp-sci department—an archaic Bogo Sort machine. While it's understood that Bogo Sort is impractical for large datasets, your goal is to enhance its efficie...
0.606795
Data_Structure_29994
C
[ "is_sorted", "guided_shuffle", "guided_bogo_sort" ]
3
[ [ "guided_bogo_sort", "guided_shuffle" ], [ "guided_bogo_sort", "is_sorted" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6f937b52b11ae752d78d8dbd71526650afd7dd21
02007845f4b5382ebc58ebf6316784148513fadb
v1.0
complete
Data_Structure
Data_Structure_30054_C
def fib_matrix(n: int) -> int: """ Computes the n-th Fibonacci number using matrix exponentiation. Parameters: n (int): The position in the Fibonacci sequence to compute. Returns: int: The n-th Fibonacci number. >>> fib_matrix(10) 55 >>> fib_matrix(100) 35422484817...
def multiply_matrices(A, B): return [ [ A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1], ], [ A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1], ], ] def matrix_power(matrix, ...
from solution import fib_matrix def test_fib_matrix_basic(): assert fib_matrix(0) == 0 assert fib_matrix(1) == 1 assert fib_matrix(2) == 1 assert fib_matrix(3) == 2 assert fib_matrix(4) == 3 assert fib_matrix(5) == 5 assert fib_matrix(6) == 8 def test_fib_matrix_large(): # Test with la...
[ { "docstring": null, "function_declaration": "def multiply_matrices(A, B):", "function_name": "multiply_matrices", "parameter_list": "(A, B)" }, { "docstring": null, "function_declaration": "def matrix_power(matrix, power):", "function_name": "matrix_power", "parameter_list": "(m...
[ 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 fib_matrix(n: int) -> int:\n \"\"\"\n Computes the n-th Fibonacci number using matrix exponentiation.\n \n Parameters:\n n (int): The posit...
trial_gpt4o_2
{ "original_instruction": "Compute the n-th Fibonacci Number Using Matrix Exponentiation\n\n#### Objective:\nYou are required to implement a function to compute the n-th Fibonacci number using matrix exponentiation.\n\n#### Scenario:\nFibonacci numbers have applications in different areas such as algorithms involving...
0.725716
Data_Structure_30054
C
[ "multiply_matrices", "matrix_power", "fib_matrix" ]
3
[ [ "fib_matrix", "matrix_power" ], [ "matrix_power", "multiply_matrices" ] ]
2
[]
false
[]
false
pytest
true
[]
true
456bdc302bf32b5f746e2c61899ec52b875e8ae8
e378332d9a23d99c2ebcf9f942a0af4edb75c5c8
v1.0
complete
Data_Structure
Data_Structure_30198_C
def rle_operations(operation: str, data: str) -> str: """ Run-Length Encoding and Decoding Perform Run-Length Encoding or Decoding based on the specified operation. Args: operation (str): Mode of operation, either "encode" or "decode". data (str): The data to be encoded or decoded. ...
def rle_operations(operation: str, data: str) -> str: if operation == "encode": return rle_encode(data) elif operation == "decode": return rle_decode(data) else: raise ValueError("Unknown operation. Use 'encode' or 'decode'.") def rle_encode(data: str) -> str: if not data: ...
from solution import rle_operations def test_encode_basic(): assert rle_operations("encode", "aaabbccaaa") == "3a2b2c3a" def test_decode_basic(): assert rle_operations("decode", "3a2b2c3a") == "aaabbccaaa" def test_encode_empty(): assert rle_operations("encode", "") == "" def test_decode_empty(): as...
[ { "docstring": null, "function_declaration": "def rle_operations(operation, data):", "function_name": "rle_operations", "parameter_list": "(operation, data)" }, { "docstring": null, "function_declaration": "def rle_encode(data):", "function_name": "rle_encode", "parameter_list": ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def rle_operations(operation: str, data: str) -> str:\n if operation == \"encode\":\n return rle_encode(data)\n elif operation == \"decode\":\n ...
trial_gpt4o_0
{ "original_instruction": "## Run-Length Encoding and Decoding\n\n### Scenario\nYou are working as a software developer in a data storage company. Your task is to enhance the company's storage efficiency by implementing a Run-Length Encoding (RLE) algorithm, which is a form of lossless data compression. With RLE, you...
0.694611
Data_Structure_30198
C
[ "rle_operations", "rle_encode", "rle_decode" ]
3
[ [ "rle_operations", "rle_decode" ], [ "rle_operations", "rle_encode" ] ]
2
[]
false
[]
false
pytest
true
[]
true
bb4e3282159c981a4adff9b88ce4ce4615c47567
9d0057669a67d0b78d1c5c2fd93f8ccc43742287
v1.0
complete
Data_Structure
Data_Structure_29680_C
from typing import List def merge_sort(arr: List[float]) -> List[float]: if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] merge_sort(L) merge_sort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: ...
def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] merge_sort(L) merge_sort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else...
from solution import bucket_sort def test_bucket_sort_basic(): assert bucket_sort([0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]) == [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94] assert bucket_sort([0.56, 0.32, 0.22, 0.84, 0.76]) == [0.22, 0.32, 0.56, 0.76, 0.84] def test_bucket_s...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def bucket_sort(arr):", "function_name": "bucket_sort", "parameter_list": "(arr)" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n L = arr[:mid]\n R = arr[mid:]\n\n merge_sort(L)\n merge_...
trial_gpt4o_1
{ "original_instruction": "Implementing Optimized Bucket Sort\n\n#### Scenario\nYou are an engineer working on a large-scale data analysis platform that processes millions of data points daily. One of your tasks is to implement an efficient sorting mechanism for a dataset that contains uniformly distributed real numb...
0.558308
Data_Structure_29680
C
[ "merge_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "merge_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b47db4ed189e5e7610859b2612383c36aa1d892d
b9c20297c51f6bd03c8818e04ab0e5af78c9475c
v1.0
complete
Data_Structure
Data_Structure_30004_C
def gcd_bit_enhanced(a: int, b: int) -> int: """ Computes the greatest common divisor (GCD) of two non-negative integers a and b using bitwise operations. This function should also handle edge cases effectively. Parameters: a (int): First non-negative integer b (int): Second non-negative intege...
def gcd_bit_enhanced(a, b): """ Computes the greatest common divisor (GCD) of two non-negative integers a and b using bitwise operations. This function should also handle edge cases effectively. """ if a == 0: return b if b == 0: return a # Reduce any common factors of 2 ...
from solution import gcd_bit_enhanced, lcm_optimized def test_gcd_bit_enhanced(): assert gcd_bit_enhanced(48, 18) == 6 assert gcd_bit_enhanced(0, 0) == 0 assert gcd_bit_enhanced(0, 18) == 18 assert gcd_bit_enhanced(18, 0) == 18 assert gcd_bit_enhanced(42, 56) == 14 assert gcd_bit_enhanced(100_0...
[ { "docstring": "Computes the greatest common divisor (GCD) of two non-negative integers a and b\nusing bitwise operations. This function should also handle edge cases effectively.", "function_declaration": "def gcd_bit_enhanced(a, b):", "function_name": "gcd_bit_enhanced", "parameter_list": "(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_bit_enhanced(a: int, b: int) -> int:\n \"\"\"\n Computes the greatest common divisor (GCD) of two non-negative integers a and b\n using bitwi...
trial_gpt4o_2
{ "original_instruction": "### Problem: Optimized Least Common Multiple Calculation with Edge Case Handling\n\nYou are provided with two functions that compute the greatest common divisor (gcd) using different approaches and a function to compute the least common multiple (lcm) using the gcd. Your task is to optimize...
0.723691
Data_Structure_30004
C
[ "gcd_bit_enhanced", "lcm_optimized" ]
2
[ [ "lcm_optimized", "gcd_bit_enhanced" ] ]
1
[]
false
[]
false
pytest
true
[]
true
48793b08ade1d50d947cb268aacedaf5963c821a
0f2b54b14b9cdc7557164484d85bbf63b34dedda
v1.0
complete
Data_Structure
Data_Structure_30249_C
def generate_rsa_keys(p: int, q: int) -> (int, int, int, int, int): """ Generate the public and private keys for RSA encryption using two prime numbers p and q. Args: p (int): A prime number. q (int): Another prime number distinct from p. Returns: tuple: (n, phi_n, e, d, max_pq) ...
import math def extended_gcd(a, b): """ Extended Euclidean Algorithm: Given two integers a and b, return a tuple (g, x, y), where g is gcd(a, b) and x,y are such that ax + by = g. """ if a == 0: return (b, 0, 1) g, x1, y1 = extended_gcd(b % a, a) x = y1 - (b // a) * x1 y = x...
from solution import generate_rsa_keys def test_generate_rsa_keys_basic(): p = 61 q = 53 n, phi_n, e, d, max_pq = generate_rsa_keys(p, q) assert n == 61 * 53 assert phi_n == (61 - 1) * (53 - 1) assert e == 65537 assert (e * d) % phi_n == 1 assert max_pq == 61 def test_generate_rsa_keys...
[ { "docstring": "Extended Euclidean Algorithm:\nGiven two integers a and b, return a tuple (g, x, y), where g is gcd(a, b) and x,y are such that\nax + by = g.", "function_declaration": "def extended_gcd(a, b):", "function_name": "extended_gcd", "parameter_list": "(a, b)" }, { "docstring": "Co...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl", "solution_code": "import math\n\ndef extended_gcd(a, b):\n \"\"\"\n Extended Euclidean Algorithm:\n Given two integers a and b, return a tuple...
trial_gpt4o_1
{ "original_instruction": "RSA Encryption Key Calculation\n\nRSA encryption heavily relies on the modular inverse operation. Given two prime numbers \\( p \\) and \\( q \\), you can generate the public and private keys for RSA encryption by following specific steps.\n\n**Scenario**: You are to write a function that, ...
0.657338
Data_Structure_30249
C
[ "extended_gcd", "modular_inverse", "generate_rsa_keys" ]
3
[ [ "generate_rsa_keys", "extended_gcd" ], [ "generate_rsa_keys", "modular_inverse" ], [ "modular_inverse", "extended_gcd" ] ]
3
[]
false
[]
false
pytest
true
[]
true
dcaa17248e33c2faee880687ec7a86cf9abdbf44
b6ad39a5dc9cf1f9054978eb840cf17f779e6c44
v1.0
complete
Data_Structure
Data_Structure_29897_C
import random def generate_key(k: int, seed: int = None) -> (int, int, int): """Generates an RSA key with a modulus of bit-length k. Parameters: - k: Bit-length of the RSA modulus n. - seed: Optional parameter to seed the random number generator. Returns: A tuple with the three integers (n,...
import random from sympy import isprime, mod_inverse def generate_prime_candidate(bits): """Generates an odd integer randomly.""" p = random.getrandbits(bits) # Apply a mask to set MSB and LSB to 1 to ensure proper bit length. p |= (1 << bits - 1) | 1 return p def generate_prime(bits): """Gene...
from solution import generate_key, encrypt, decrypt def test_generate_key(): n, e, d = generate_key(16, seed=42) assert type(n) == int assert type(e) == int assert type(d) == int def test_encrypt_decrypt(): n, e, d = generate_key(16, seed=42) data = 20 encrypted = encrypt(data, e, n) d...
[ { "docstring": "Generates an odd integer randomly.", "function_declaration": "def generate_prime_candidate(bits):", "function_name": "generate_prime_candidate", "parameter_list": "(bits)" }, { "docstring": "Generate a prime number of 'bits' bit length.", "function_declaration": "def gene...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime(bit_length, seed=None):\n if seed is not None:\n random.seed(seed)\n ...
trial_gpt4o_3
{ "original_instruction": "### Scenario\n\nYou work as a software engineer for a company that ensures secure communication between its clients. To achieve robust security, you are tasked with implementing a basic version of an RSA encryption algorithm provided to you in pseudocode. You've decided to complete the RSA ...
0.699188
Data_Structure_29897
C
[ "generate_prime_candidate", "generate_prime", "generate_key", "encrypt", "decrypt" ]
5
[ [ "generate_key", "generate_prime" ], [ "generate_prime", "generate_prime_candidate" ] ]
2
[]
false
[]
false
pytest
true
[ "sympy" ]
false
92dde7650ed56a23cdfbc6598fed814d9409970c
f29f15a06f76f708b36afa89d28146ae718a25f7
v1.0
complete
Data_Structure
Data_Structure_30364_C
def recommend_movie(user_profile, movies): """ Recommends the movie that is nearest to the user profile based on Euclidean distance. :param user_profile: tuple, represents the user's preferences as a vector of floats :param movies: dict, where keys are tuples representing movie feature vectors, an...
import math def euclidean_distance(x, y): """ Computes the Euclidean distance between two vectors. :param x: tuple of floats :param y: tuple of floats :return: float representing the Euclidean distance """ return math.sqrt(sum((xi - yi) * (xi - yi) for xi, yi in zip(x, y))) def recomm...
from solution import recommend_movie def test_recommend_movie_single_movie(): user_profile = (1.0, 2.0, 3.0) movies = {(1.0, 2.0, 3.0): "Movie A"} assert recommend_movie(user_profile, movies) == "Movie A" def test_recommend_movie_multiple_movies(): user_profile = (1.2, 3.4, 5.6) movies = { ...
[ { "docstring": "Computes the Euclidean distance between two vectors.\n\n:param x: tuple of floats\n:param y: tuple of floats\n:return: float representing the Euclidean distance", "function_declaration": "def euclidean_distance(x, y):", "function_name": "euclidean_distance", "parameter_list": "(x, y)...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from math import sqrt\n\ndef euclidean_distance(vec1, vec2):\n return sqrt(sum((a - b)**2 for a, b in zip(vec1, vec2)))\n\ndef recommend_movie(user_profile...
trial_gpt4o_2
{ "original_instruction": "### Scenario\nYou are developing a recommendation system for a movie streaming service. Given a user's preference profile - represented as a vector of features (like genres, language, release year, etc.), you need to suggest a movie that best matches the user's profile from a collection of ...
0.542625
Data_Structure_30364
C
[ "euclidean_distance", "recommend_movie" ]
2
[ [ "recommend_movie", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dcd37a0746217b440e4550c3176b8080f655fd97
358f47643b493fe6bed7d880d0add2b7df92f0a3
v1.0
complete
Data_Structure
Data_Structure_30178_C
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(text): ...
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(text): ...
import pytest from solution import encode_file, decode_file, huffman_encode, huffman_decode, build_huffman_tree, build_codes, HuffmanNode def write_file(filename, content): with open(filename, 'w') as file: file.write(content) def read_file(filename): with open(filename, 'r') as file: return f...
[]
[ 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 heapq import heappush, heappop, heapify\nfrom collections import defaultdict\nimport os\nimport struct\n\nclass HuffmanNode:\n def __init__(self, char...
trial_gpt4o_1
{ "original_instruction": "## Huffman Coding Challenge\n\nHuffman Coding is a popular algorithm used for lossless data compression. Your task is to implement both the encoding and decoding functions for Huffman Coding. Given a file, your function should be able to read the file, compress it using the Huffman Coding a...
0.529414
Data_Structure_30178
C
[ "build_huffman_tree", "build_codes", "huffman_encode", "huffman_decode", "encode_file", "decode_file" ]
6
[ [ "decode_file", "huffman_decode" ], [ "encode_file", "huffman_encode" ], [ "huffman_encode", "build_codes" ], [ "huffman_encode", "build_huffman_tree" ] ]
4
[]
false
[ "HuffmanNode" ]
true
pytest
true
[]
true
97c5ba90b56fb64b128cd9eb368482acb3d86032
ac99d7b73cf17276d18b6fcf99b2241784290fe4
v1.0
complete
Data_Structure
Data_Structure_30158_C
def matrix_power(mat: list, power: int) -> list: """ Raises the square matrix `mat` to the power `power` using exponentiation by squaring. Parameters: - mat (list of list of int): A square matrix of dimensions d x d. - power (int): The exponent to which the matrix should be raised. Ret...
def matrix_multiply(A, B): """ Multiplies 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): result[i][j] = sum(A[i][k] * B[k][j] for k in range(n)) return result def matrix_power(mat, power): """ ...
from solution import matrix_power def test_matrix_power_base_case(): mat = [[2]] power = 0 result = matrix_power(mat, power) assert result == [[1]] # Any matrix to the power of 0 should be the identity matrix of same size def test_matrix_power_identity(): mat = [ [1, 0], [0, 1] ...
[ { "docstring": "Multiplies two square matrices A and B.", "function_declaration": "def matrix_multiply(A, B):", "function_name": "matrix_multiply", "parameter_list": "(A, B)" }, { "docstring": "Raises the square matrix `mat` to the power `power` using exponentiation by squaring.", "funct...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def matrix_multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B.\n \"\"\"\n n = len(A)\n result = [[0] * n for _ in range(n)]\n for i ...
trial_gpt4o_1
{ "original_instruction": "### Matrix Exponentiation by Squaring\n\n### Context\nMatrix exponentiation is an important technique with various applications in algorithms, such as in graph theory and cryptography. Implementing it efficiently can save a significant amount of computational resources.\n\n### Task\nYou are...
0.549451
Data_Structure_30158
C
[ "matrix_multiply", "matrix_power" ]
2
[ [ "matrix_power", "matrix_multiply" ] ]
1
[]
false
[]
false
pytest
true
[]
true
aa7d58bf9443c90811030edfaab20f05c08874dc
1f70942d7882faa1e53a0d87b5a615bf06d7244a
v1.0
complete
Data_Structure
Data_Structure_30184_C
import random def enhanced_bogo_sort(arr: list, max_attempts: int) -> list: """ Sorts the given array using Bogo Sort to a limited extent, switching to another sorting algorithm if max_attempts is exhausted. Parameters: arr (list): List of integers to be sorted. max_attempts (int): Maximum number ...
import random def is_sorted(arr): """ Helper function to check if the array is sorted. """ return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) def bogo_sort(arr): """ Performs a single attempt of Bogo Sort by shuffling. """ random.shuffle(arr) return arr def enhanced_bog...
def test_is_sorted(): assert is_sorted([1, 2, 3]) == True assert is_sorted([3, 2, 1]) == False assert is_sorted([]) == True assert is_sorted([1]) == True def test_enhanced_bogo_sort(): # Testing with small inputs assert enhanced_bogo_sort([3, 2, 1], 10) == [1, 2, 3] assert enhanced_bogo_sor...
[ { "docstring": "Helper function to check if the array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Performs a single attempt of Bogo Sort by shuffling.", "function_declaration": "def bogo_sort(arr):...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\" Check if the array is sorted in ascending order \"\"\"\n for i in range(len(arr) - 1):\n if arr[i] ...
trial_gpt4o_2
{ "original_instruction": "### Bogo Sort Analysis and Enhancement\n\nAs a novice algorithm designer, you are tasked with analyzing the Bogo Sort algorithm provided and suggesting enhancements for practical use. Although the Bogo Sort algorithm is theoretically interesting, it is impractical for any substantial applic...
0.572559
Data_Structure_30184
C
[ "is_sorted", "bogo_sort", "enhanced_bogo_sort" ]
3
[ [ "enhanced_bogo_sort", "bogo_sort" ], [ "enhanced_bogo_sort", "is_sorted" ] ]
2
[]
false
[]
false
pytest
false
[]
true
80ec31f30ae20a16acc1bd26de6bd7251497a1a4
d9d013a5af59457c6ddc4e3afe8c0109e427c8e7
v1.0
complete
Data_Structure
Data_Structure_30639_C
def spell_checker(word: str, dictionary: List[str]) -> str: """ Suggests the correct word from the dictionary with the minimum edit distance. >>> spell_checker("speling", ["spelling", "spewing", "spieling"]) "spelling" >>> spell_checker("pythin", ["python", "typhon", "jython"]) "python" """
from typing import List def edit_distance(word1: str, word2: str) -> int: """Compute the edit distance between two words using dynamic programming.""" m, n = len(word1), len(word2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == ...
from solution import spell_checker def test_spell_checker_basic(): assert spell_checker("speling", ["spelling", "spewing", "spieling"]) == "spelling" def test_spell_checker_with_identical_words(): assert spell_checker("rate", ["rate", "rate", "sample"]) == "rate" def test_spell_checker_with_tie(): assert...
[ { "docstring": "Compute the edit distance between two words using dynamic programming.", "function_declaration": "def edit_distance(word1, word2):", "function_name": "edit_distance", "parameter_list": "(word1, word2)" }, { "docstring": "Suggests the correct word from the dictionary with the ...
[ 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 edit_distance(word1: str, word2: str) -> int:\n \"\"\"Compute the edit distance between two words using dynamic programming....
trial_gpt4o_0
{ "original_instruction": "### Problem: Text Editor Spell Correction\n\nYou are tasked with implementing a spell checker for a simple text editor. The spell checker needs to suggest corrections for misspelled words by computing the edit distance between the misspelled word and potential correct words from a dictionar...
0.50511
Data_Structure_30639
C
[ "edit_distance", "spell_checker" ]
2
[ [ "spell_checker", "edit_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d003052698583422056fbdbe8e47d9e58e126bb1
d1c37e3a2a3122d33a072fcfc341862b327b7221
v1.0
complete
Data_Structure
Data_Structure_30501_C
from typing import List, Tuple def find_transitive_closure(vertices: int, edges: List[Tuple[int, int]]) -> List[List[int]]: """ Computes the transitive closure matrix of a directed graph. Args: vertices (int): The number of vertices in the graph, denoted by V. edges (List[Tuple[int, int]]): A list...
from typing import List, Tuple def dfs(graph, source, vertex, reachable): reachable[source][vertex] = 1 for neighbor in graph[vertex]: if not reachable[source][neighbor]: dfs(graph, source, neighbor, reachable) def find_transitive_closure(vertices: int, edges: List[Tuple[int, int]]) -> Lis...
from solution import find_transitive_closure def test_find_transitive_closure_simple(): vertices = 2 edges = [(0, 1)] expected_result = [[1, 1], [0, 1]] assert find_transitive_closure(vertices, edges) == expected_result def test_find_transitive_closure_no_edges(): vertices = 3 edges = [] e...
[ { "docstring": null, "function_declaration": "def dfs(graph, source, vertex, reachable):", "function_name": "dfs", "parameter_list": "(graph, source, vertex, reachable)" }, { "docstring": null, "function_declaration": "def find_transitive_closure(vertices, edges):", "function_name": ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\ndef dfs(graph, source, vertex, reachable):\n reachable[source][vertex] = 1\n for neighbor in graph[vertex]:\n i...
trial_gpt4o_0
{ "original_instruction": "#### Scenario\nYou are a software developer at a logistics company. Your company is developing an application that analyzes the reachability of delivery locations within a city. The city is modeled as a directed graph, where vertices represent locations and edges represent direct roads betw...
0.554415
Data_Structure_30501
C
[ "dfs", "find_transitive_closure" ]
2
[ [ "find_transitive_closure", "dfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c170ee4b12e8d7627ec0a2b474292a21ace1ec29
1f377371918fba74f3d6c64e2296d83142c0c7d2
v1.0
complete
Data_Structure
Data_Structure_30565_C
def insertion_sort(bucket): """ Sorts a bucket using the insertion sort algorithm. """ 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 bucke...
def insertion_sort(bucket): """ Sorts a bucket using the insertion sort algorithm. """ 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 bucke...
from solution import bucket_sort def test_bucket_sort_normal_case(): assert bucket_sort([4, 1, 7, 3, 2, 9, 0, 6]) == [0, 1, 2, 3, 4, 6, 7, 9] def test_bucket_sort_single_element(): assert bucket_sort([5]) == [5] def test_bucket_sort_empty_list(): assert bucket_sort([]) == [] def test_bucket_sort_identic...
[ { "docstring": "Sorts a bucket using the insertion sort algorithm.", "function_declaration": "def insertion_sort(bucket):", "function_name": "insertion_sort", "parameter_list": "(bucket)" }, { "docstring": "Sorts an array of non-negative integers using the bucket sort algorithm.\n\nArgs:\nar...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def insertion_sort(arr):\n \"\"\"\n Helper function to sort a list using insertion sort.\n \"\"\"\n for i in range(1, len(arr)):\n key = ar...
trial_gpt4o_2
{ "original_instruction": "### Bucket Sort Implementation\n\n#### Problem Statement\nImplement the bucket sort algorithm. Your implementation should divide input data into a specific number of buckets, sort each bucket individually using insertion sort, and then concatenate the buckets to create the final sorted list...
0.593121
Data_Structure_30565
C
[ "insertion_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
df143ea00ecef60baf472c892ce2ef7756e9fd11
b8cb5c3a423fb22705af3e57ffd13bfc4502d1d0
v1.0
complete
Data_Structure
Data_Structure_30650_C
import random def is_sorted(arr): """ Helper function to check if the array is sorted. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort_enhanced(arr: list[int]) -> tuple[list[int], int]: """ Enhanced Bogo Sort that returns...
import random def is_sorted(arr): """ Helper function to check if the array is sorted. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort_enhanced(arr: list[int]) -> tuple[list[int], int]: """ Enhanced Bogo Sort that returns...
from solution import bogo_sort_enhanced def test_bogo_sort_enhanced_single_element(): assert bogo_sort_enhanced([1]) == ([1], 0) def test_bogo_sort_enhanced_already_sorted(): result = bogo_sort_enhanced([1, 2, 3]) assert result[0] == [1, 2, 3] assert result[1] >= 0 # Count can vary, but must be a...
[ { "docstring": "Helper function to check if the array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Enhanced Bogo Sort that returns the sorted list and the number of shuffles performed.", "function_d...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef bogo_sort_enhanced(arr: list[int]) -> tuple[list[int], int]:\n \"\"\"\n Sort the array using Bogo Sort and count the number of shuf...
trial_gpt4o_2
{ "original_instruction": "Enhanced Bogo Sort with Simulation Counter\n\nGiven the inefficiency of Bogo Sort, your task is to implement an enhanced version of Bogo Sort that includes a simulation counter to keep track of the number of shuffles performed. Additionally, your implementation should return the sorted list...
0.665145
Data_Structure_30650
C
[ "is_sorted", "bogo_sort_enhanced" ]
2
[ [ "bogo_sort_enhanced", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2f0d7832f2a3d8123bf2e1a398ace2906027167e
1d1278e58a230e4b4f075311009a399a4961f743
v1.0
complete
Data_Structure
Data_Structure_30720_C
import sympy import random def is_primitive_root(a, p): """ Check if `a` is a primitive root of `p`. """ pass def secure_diffie_hellman_key_exchange(a, p, verbose=False): """ Performs the Diffie-Hellman key exchange if the following conditions are met: 1. `p` is a prime number. 2. `a` is a pri...
import sympy import random def is_primitive_root(a, p): """ Check if `a` is a primitive root of `p`. """ required_set = set(num for num in range(1, p) if sympy.gcd(num, p) == 1) actual_set = set((a ** powers) % p for powers in range(1, p)) return required_set == actual_set def secure_diffie_he...
from solution import secure_diffie_hellman_key_exchange def test_secure_diffie_hellman_key_exchange_successful(): shared_key = secure_diffie_hellman_key_exchange(2, 11, False) assert isinstance(shared_key, int) def test_secure_diffie_hellman_key_exchange_non_prime(): result = secure_diffie_hellman_key_exc...
[ { "docstring": "Check if `a` is a primitive root of `p`.", "function_declaration": "def is_primitive_root(a, p):", "function_name": "is_primitive_root", "parameter_list": "(a, p)" }, { "docstring": "Performs the Diffie-Hellman key exchange if the following conditions are met:\n1. `p` is a pr...
[ 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(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\...
trial_gpt4o_2
{ "original_instruction": "### Question: Implement Enhanced Diffie-Hellman Key Exchange with Additional Constraints\n\n**Objective**: Implement Diffie-Hellman Key Exchange algorithm with enhanced features to address additional constraints such as verifying if `p` is prime and if `a` is a valid primitive root of `p`.\...
0.498386
Data_Structure_30720
C
[ "is_primitive_root", "secure_diffie_hellman_key_exchange" ]
2
[ [ "secure_diffie_hellman_key_exchange", "is_primitive_root" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
4d63c0c1186c41310a7db2cababc5d898e1034b2
55b6fa9562f04281cc1c17d3c468f3d1fb1bbc78
v1.0
complete
Data_Structure
Data_Structure_30821_C
from typing import List def edit_distance(word_a, word_b): length_a, length_b = len(word_a) + 1, len(word_b) + 1 edit = [[0 for _ in range(length_b)] for _ in range(length_a)] for i in range(1, length_a): edit[i][0] = i for j in range(1, length_b): edit[0][j] = j for i in range(...
from typing import List def edit_distance(word_a, word_b): length_a, length_b = len(word_a) + 1, len(word_b) + 1 edit = [[0 for _ in range(length_b)] for _ in range(length_a)] for i in range(1, length_a): edit[i][0] = i for j in range(1, length_b): edit[0][j] = j for i in range(...
from solution import find_closest_word def test_find_closest_word_example_1(): assert find_closest_word(["food", "money", "mood", "hone"], "foond") == "food" def test_find_closest_word_example_2(): assert find_closest_word(["spelling", "checker", "correct"], "cheker") == "checker" def test_find_closest_word_...
[ { "docstring": null, "function_declaration": "def edit_distance(word_a, word_b):", "function_name": "edit_distance", "parameter_list": "(word_a, word_b)" }, { "docstring": null, "function_declaration": "def find_closest_word(dictionary, query):", "function_name": "find_closest_word",...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef edit_distance(word_a, word_b):\n length_a, length_b = len(word_a) + 1, len(word_b) + 1\n\n edit = [[0 for _ in range(leng...
trial_gpt4o_2
{ "original_instruction": "### Context\nSpell checkers are a common tool in text editors to help users identify and correct spelling mistakes. A critical component of a spell checker is to measure how close a given word is to the correctly spelled words in its dictionary.\n\n### Task\nWrite a function `find_closest_w...
0.615651
Data_Structure_30821
C
[ "edit_distance", "find_closest_word" ]
2
[ [ "find_closest_word", "edit_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0d15242dac01cc6a4d47886ac1aa29363f27d81f
6a9e9ff57fbd3ad670ffd24dd0e8052c0758affc
v1.0
complete
Data_Structure
Data_Structure_31163_C
def encode_data(input_file: str, output_file: str) -> None: """ Compresses the content of an input file using Huffman coding and writes the compressed data to an output file. >>> encode_data("input.txt", "encoded.bin") """ def decode_data(input_file: str, output_file: str) -> None: """ Decompresses the...
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": "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. \n\n### Requirements\n\n1. **Encoding**: Implement a function `encode_data(input_f...
0.589087
Data_Structure_31163
C
[ "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
e586b9f51762f8b4b0cb1067fa4089b688e0c915
813ef6d1e49b37bcb52e4c1250a5a4e64bb8d94d
v1.0
complete
Data_Structure
Data_Structure_30872_C
def base_converter(value, base, convert_back=False): """ Convert an integer to its string representation in any given base (between 2 and 36). Convert a base-represented string back to its decimal integer equivalent. :type value: str or int :type base: int :type convert_back: bool :rtyp...
def int_to_base(n, base): """Helper function to convert an integer to a given base.""" if n == 0: return "0" digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" result = "" negative = n < 0 n = abs(n) while n: result = digits[n % base] + result n //= base ...
def test_int_to_base(): assert int_to_base(5, 2) == '101' assert int_to_base(255, 16) == 'FF' assert int_to_base(-10, 2) == '-1010' assert int_to_base(0, 2) == '0' def test_base_to_int(): assert base_to_int('101', 2) == 5 assert base_to_int('FF', 16) == 255 assert base_to_int('-1010', 2) ==...
[ { "docstring": "Helper function to convert an integer to a given base.", "function_declaration": "def int_to_base(n, base):", "function_name": "int_to_base", "parameter_list": "(n, base)" }, { "docstring": "Helper function to convert a base string to an integer.", "function_declaration":...
[ 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 base_converter(value, base, convert_back=False):\n \"\"\"\n :type value: str or int\n :type base: int\n :type convert_back: bool\n :rtype: ...
trial_gpt4o_2
{ "original_instruction": "### Base Conversion Challenge\n\nYou have been provided with two functions, `int_to_base` and `base_to_int`, that convert integers to different base representations and vice versa. Your task is to extend these functionalities with additional features and handle different edge cases.\n\n####...
0.820217
Data_Structure_30872
C
[ "int_to_base", "base_to_int", "base_converter" ]
3
[ [ "base_converter", "base_to_int" ], [ "base_converter", "int_to_base" ] ]
2
[]
false
[]
false
pytest
false
[]
true
d6c379566e31b8d23bd55188fa41fb3631bc2033
134f1e6a1c5a99cf551ee20a5929756509d5566f
v1.0
complete
Data_Structure
Data_Structure_30734_C
def prime_check(num: int) -> bool: """ Checks if the given number is a prime number. >>> prime_check(23) True >>> prime_check(20) False """ def euler_totient(n: int) -> int: """ Computes Euler's totient function for the given number. >>> euler_totient(9) 6 >>> euler_...
import random from math import gcd def prime_check(num): """ Returns True if num is a prime number, else False. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 ...
from solution import diffie_hellman_key_exchange, prime_check, euler_totient, find_order, find_primitive_root def test_prime_check(): assert prime_check(23) == True assert prime_check(20) == False assert prime_check(2) == True assert prime_check(1) == False assert prime_check(0) == False assert...
[ { "docstring": "Returns True if num is a prime number, else False.", "function_declaration": "def prime_check(num):", "function_name": "prime_check", "parameter_list": "(num)" }, { "docstring": "Returns the value of Euler's Totient function for n.", "function_declaration": "def euler_tot...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def prime_check(num: int) -> bool:\n \"\"\"\n Returns True if num is a prime number else False.\n \"\"\"\n if num <= 1:\n return False\n ...
trial_gpt4o_3
{ "original_instruction": "Alice and Bob want to securely exchange keys over an insecure network using the Diffie-Hellman Key Exchange method. Your task is to implement their key exchange process. You need to ensure that the prime number \\(p\\) and primitive root \\(a\\) are validated correctly and then perform the ...
0.590888
Data_Structure_30734
C
[ "prime_check", "euler_totient", "find_order", "find_primitive_root", "diffie_hellman_key_exchange" ]
5
[ [ "diffie_hellman_key_exchange", "find_primitive_root" ], [ "diffie_hellman_key_exchange", "prime_check" ], [ "find_order", "euler_totient" ], [ "find_primitive_root", "prime_check" ] ]
4
[]
false
[]
false
pytest
true
[]
true
ec1dcdd6f39888ca55662816739f6382b261cac6
b41ba123b9ae5b5707f6e85acdc0fb48cd69a29a
v1.0
complete
Data_Structure
Data_Structure_30481_C
def large_matrix_exponentiation(mat: list, power: int) -> list: """ Compute the power-th exponent of a given square matrix using repeated squaring. Args: mat (list of list of int): A square matrix of dimensions d x d. power (int): A non-negative integer representing the power to which the matrix is...
def matrix_mult(A, B): """ Multiplies two square matrices A and B. """ size = len(A) result = [[0] * size for _ in range(size)] for i in range(size): for j in range(size): result[i][j] = sum(A[i][k] * B[k][j] for k in range(size)) return result def large_matrix_exponenti...
from solution import large_matrix_exponentiation, matrix_mult def test_large_matrix_exponentiation_example(): mat = [ [1, 1], [1, 0] ] power = 5 expected_output = [ [8, 5], [5, 3] ] assert large_matrix_exponentiation(mat, power) == expected_output def test_large...
[ { "docstring": "Multiplies two square matrices A and B.", "function_declaration": "def matrix_mult(A, B):", "function_name": "matrix_mult", "parameter_list": "(A, B)" }, { "docstring": "Computes mat^power using repeated squaring method.", "function_declaration": "def large_matrix_exponen...
[ 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_multiply(mat1, mat2):\n \"\"\"\n Multiplies two square matrices mat1 and mat2.\n \"\"\"\n n = len(mat1)\n result = [[0] * n for _ in...
trial_gpt4o_2
{ "original_instruction": "### Problem Context\nYou are developing a simulation for a system that involves a large number of state transitions represented by matrices. To optimize the performance of your simulation, it is crucial to efficiently compute the exponentiation of state transition matrices.\n\n### Task\nWri...
0.529576
Data_Structure_30481
C
[ "matrix_mult", "large_matrix_exponentiation" ]
2
[ [ "large_matrix_exponentiation", "matrix_mult" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6385e4b77ec10487252e1fc845618b7aafe35cac
24d07de6b4b2f9ee14dd63d2b29bcf0e2c3d2f0b
v1.0
complete
Data_Structure
Data_Structure_31125_C
def hybrid_heap_sort(arr, use_max_heap: bool, simulation: bool=False) -> list: """ Sorts an array of integers using either max-heap sort or min-heap sort. Args: arr (list): List of integers to be sorted. use_max_heap (bool): If True, use max-heap sort; otherwise, use min-heap sort. simulation ...
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": "### **Heap Sort Implementation**\n\nYou 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 ...
0.615548
Data_Structure_31125
C
[ "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
84b0ca65ae4473e4d86f6a6a52b2bfc2bf989627
2b97a11249702cef02d21c45c89344b3fe95f6a1
v1.0
complete
Data_Structure
Data_Structure_30632_C
def calculate_max_flow(capacity: List[List[int]], source: int, sink: int) -> int: """ Calculate the maximum flow in a network graph from a given source to a sink. >>> calculate_max_flow( ... [ ... [0, 16, 13, 0, 0, 0], ... [0, 0, 10, 12, 0, 0], ... [0, 4, 0, 0, 14, 0]...
from typing import List from collections import deque def bfs(residual_capacity, source, sink, parent): visited = [False] * len(residual_capacity) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() for v, cap in enumerate(residual_capacity[u]):...
from solution import calculate_max_flow def test_calculate_max_flow_simple(): 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 calcul...
[ { "docstring": null, "function_declaration": "def bfs(residual_capacity, source, sink, parent):", "function_name": "bfs", "parameter_list": "(residual_capacity, source, sink, parent)" }, { "docstring": null, "function_declaration": "def calculate_max_flow(capacity, source, sink):", "...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\nfrom typing import List\n\ndef bfs(capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n visited ...
trial_gpt4o_2
{ "original_instruction": "### Maximum Flow Calculation in a Network Graph\n\nYou are tasked with implementing a function to calculate the maximum flow in a network graph from a given source to a sink using one of the provided algorithms.\n\n#### Function Signature\n```python\ndef calculate_max_flow(capacity: List[Li...
0.609253
Data_Structure_30632
C
[ "bfs", "calculate_max_flow" ]
2
[ [ "calculate_max_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c7ce70d9085ebfd4b0d0de6084070db60072237e
86587c7c7d47e0b559e840fb4630ea39947f302d
v1.0
complete
Data_Structure
Data_Structure_30843_C
from typing import List def gcd_euclid(a: int, b: int) -> int: """Compute the GCD of two numbers using Euclid's Algorithm. >>> gcd_euclid(48, 18) 6 >>> gcd_euclid(101, 103) 1 """ pass def gcd_bitwise(a: int, b: int) -> int: """Compute the GCD of two numbers using Bitwise Operations. ...
from functools import reduce from math import gcd def gcd_euclid(a, b): while b: a, b = b, a % b return a def gcd_bitwise(a, b): if a == 0: return b if b == 0: return a if a == b: return a if a & 1 == 0: # a is even if b & 1: # b is odd return gcd_bitwise(a >> 1, ...
from solution import array_gcd_euclid, array_gcd_bitwise, array_lcm, trailing_zero def test_array_gcd_euclid(): assert array_gcd_euclid([24, 36, 48]) == 12 assert array_gcd_euclid([1, 2, 3, 4, 5]) == 1 assert array_gcd_euclid([12, 15, 18, 21]) == 3 assert array_gcd_euclid([3, 9, 27]) == 3 assert ar...
[ { "docstring": null, "function_declaration": "def gcd_euclid(a, b):", "function_name": "gcd_euclid", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def gcd_bitwise(a, b):", "function_name": "gcd_bitwise", "parameter_list": "(a, b)" }, { "docst...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from functools import reduce\n\ndef gcd_euclid(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef array_gcd_euclid(arr):\n return reduce(gc...
trial_gpt4o_1
{ "original_instruction": "You are required to implement a function that calculates the greatest common divisor (GCD) of an array of non-negative integers using two different algorithms: Euclid's Algorithm and Bitwise Operations. Additionally, you will need to compute the least common multiple (LCM) and the number of...
0.721733
Data_Structure_30843
C
[ "gcd_euclid", "gcd_bitwise", "array_gcd_euclid", "array_gcd_bitwise", "array_lcm", "trailing_zero" ]
6
[ [ "array_gcd_bitwise", "gcd_bitwise" ], [ "array_gcd_euclid", "gcd_euclid" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3d2278191b0c1f0f7ff7c3906f5b73fba95d40ba
c750a18d62443316c24e77478d79387aff144f18
v1.0
complete
Data_Structure
Data_Structure_31247_C
def stoogesort(arr, l, h): """ Function to perform Stooge Sort on the array >>> arr = [3, 1, 4, 1, 5, 9, 2, 6] >>> stoogesort(arr, 0, len(arr) - 1) >>> arr [1, 1, 2, 3, 4, 5, 6, 9] """ if l >= h: return if arr[l] > arr[h]: arr[l], arr[h] = arr[h], arr[l] if...
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": "### Objective\nAssume 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. ...
0.635436
Data_Structure_31247
C
[ "stoogesort", "check_sort", "compare_to_builtin_sort" ]
3
[ [ "compare_to_builtin_sort", "stoogesort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ab922954045e62aa792663266fb693f01a6ab28b
7c65b084ad5f393db50340801a6fe9466e2aa1a9
v1.0
complete
Data_Structure
Data_Structure_30902_C
def pratt_shell_sort(arr: List[int]) -> List[int]: """ Sorts the given list of integers using the Shell Sort algorithm with Pratt's gap sequence. Pratt's sequence for gaps is defined by all products of powers of 2 and 3. This function efficiently sorts the array using these gaps. Input: - '...
from typing import List def generate_pratt_sequence(n: int) -> List[int]: """ Generates Pratt's sequence up to the maximum value less than n. Pratt's gaps are all products of powers of 2 and 3. """ gaps = set() k = 1 while k < n: m = k while m < n: gaps.add(m) ...
from solution import pratt_shell_sort def test_pratt_shell_sort_unsorted(): assert pratt_shell_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9] def test_pratt_shell_sort_random(): assert pratt_shell_sort([20, 35, -15, 7, 55, 1, -22]) == [-22, -15, 1, 7, 20, 35, 55] def test_pratt_shell_sort_reverse(): asse...
[ { "docstring": "Generates Pratt's sequence up to the maximum value less than n.\nPratt's gaps are all products of powers of 2 and 3.", "function_declaration": "def generate_pratt_sequence(n):", "function_name": "generate_pratt_sequence", "parameter_list": "(n)" }, { "docstring": "Sorts the g...
[ 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 generate_pratt_sequence(n: int) -> List[int]:\n \"\"\"\n Generate Pratt's sequence up to n (the length of the array to be...
trial_gpt4o_2
{ "original_instruction": "Enhanced Shell Sort Implementation\n\n#### Context\nShell Sort is a generalization of insertion sort that allows the exchange of items that are far apart. The algorithm sorts elements by comparing them with each other at a certain gap and reduces this gap sequentially following a specific p...
0.657967
Data_Structure_30902
C
[ "generate_pratt_sequence", "pratt_shell_sort" ]
2
[ [ "pratt_shell_sort", "generate_pratt_sequence" ] ]
1
[]
false
[]
false
pytest
true
[]
true
854053be28e4241eec9029f7fe1b1cf0e2bd4a7d
a544e7e592d22570c238003a9f003b1ce45ecda0
v1.0
complete
Data_Structure
Data_Structure_30787_C
from typing import List def invert_matrix(matrix: List[List[float]]) -> List[List[float]]: """ Return the inverse of the input matrix or specific codes for invalid/singular matrices. Args: matrix (List[List[float]]): An n x n matrix with float or integer elements (2 ≤ n ≤ 10). Returns...
from typing import List def determinant(matrix: List[List[float]]) -> float: """Calculate the determinant of a matrix.""" n = len(matrix) if n == 1: return matrix[0][0] if n == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] det = 0 for c in range(n): ...
import pytest from solution import invert_matrix def test_valid_2x2_matrix(): matrix = [ [4, 7], [2, 6] ] inverse = invert_matrix(matrix) expected = [[0.6, -0.7], [-0.2, 0.4]] for i in range(2): for j in range(2): assert abs(inverse[i][j] - expected[i][j]) < 1e-9...
[ { "docstring": "Calculate the determinant of a matrix.", "function_declaration": "def determinant(matrix):", "function_name": "determinant", "parameter_list": "(matrix)" }, { "docstring": "Return the Minor of the matrix by removing the specified row and column.", "function_declaration": ...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef determinant(matrix: List[List[float]]) -> float:\n n = len(matrix)\n if n == 2:\n return matrix[0][0] * matrix[1][...
trial_gpt4o_4
{ "original_instruction": "You are required to implement a function for matrix inversion that handles both 2x2 matrices and larger n x n matrices using the determinant-based method. Your function should follow the general steps used in the provided code, such as computing the matrix of minors and cofactors, adjugatin...
0.552452
Data_Structure_30787
C
[ "determinant", "minor", "transpose", "cofactor", "invert_matrix" ]
5
[ [ "cofactor", "determinant" ], [ "cofactor", "minor" ], [ "determinant", "minor" ], [ "invert_matrix", "cofactor" ], [ "invert_matrix", "determinant" ], [ "invert_matrix", "transpose" ] ]
6
[]
false
[]
false
pytest
true
[]
true
e56998252149beb8b2222d9be30c521285e9a9ca
8942a5565e730a300794ffe61810518a33ca29f2
v1.0
complete
Data_Structure
Data_Structure_31491_C
from typing import List def invert_matrix(matrix: List[List[float]]) -> List[List[float]]: """ Finds the inverse of a given n x n invertible matrix. If the input matrix is not squared, return [[-2]] If the matrix is singular (determinant = 0), return [[-4]] >>> invert_matrix([ ... [4, ...
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": "### Inverse Matrix Finder\n\nYou 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.\n\n### Function Signature\n\n```python\ndef invert_mat...
0.57618
Data_Structure_31491
C
[ "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
2c13f20e742e147eca35f4afaa57ad7f89e7c7c0
33918ea5b1b86624a6054df79a5102322c5bb0a1
v1.0
complete
Data_Structure
Data_Structure_30866_C
def enhanced_stoogesort(arr: list, l: int, h: int) -> None: """ Implement the Stooge Sort algorithm and enhance it with early stopping conditions. Stooge Sort is an inefficient sorting algorithm used for educational purposes. This function sorts a given segment of an array in place using the Stooge Sort t...
def is_sorted(arr, l, h): """Helper function to check if a segment of the array is sorted.""" for i in range(l, h): if arr[i] > arr[i + 1]: return False return True def enhanced_stoogesort(arr, l, h): """Function to perform enhanced Stooge Sort on a segment of the array.""" if l...
from solution import enhanced_stoogesort def test_sorted_array(): arr = [1, 2, 3, 4, 5] enhanced_stoogesort(arr, 0, len(arr) - 1) assert arr == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): arr = [5, 4, 3, 2, 1] enhanced_stoogesort(arr, 0, len(arr) - 1) assert arr == [1, 2, 3, 4, 5] def te...
[ { "docstring": "Helper function to check if a segment of the array is sorted.", "function_declaration": "def is_sorted(arr, l, h):", "function_name": "is_sorted", "parameter_list": "(arr, l, h)" }, { "docstring": "Function to perform enhanced Stooge Sort on a segment of the array.", "fun...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_sorted(arr, l, h):\n \"\"\"\n Helper function to check if the segment of the array is sorted.\n \"\"\"\n for i in range(l, h):\n if ...
trial_gpt4o_2
{ "original_instruction": "### Question: Implement and Enhance Stooge Sort\n\n#### Background\nStooge Sort is an inefficient recursive sorting algorithm with very poor performance characteristics. Despite its impracticality for large data sets, it is a useful tool for educational purposes to understand recursive sort...
0.650959
Data_Structure_30866
C
[ "is_sorted", "enhanced_stoogesort" ]
2
[ [ "enhanced_stoogesort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a9be84bd9c41deef09892486ba813e1496fd3684
de6c558d6e8ec059c0a4f8bcae93a59aed07fe34
v1.0
complete
Data_Structure
Data_Structure_31643_C
from typing import List, Tuple def selection_sort_and_count_primes(arr: List[int]) -> Tuple[List[int], int]: """ Sort the input list 'arr' using the Selection Sort algorithm. Count and return the number of prime numbers in the list after sorting. >>> selection_sort_and_count_primes([29, 10, 14, 37...
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": "### Selection Sort and Prime Check Integration\n\n#### Objective\nYour task is to combine the Selection Sort algorithm with a functionality to check the prime numbers within the list. \n\n#### Problem Statement\nImplement a function `selection_sort_and_count_primes(arr: List[int]) -> Tuple[...
0.728439
Data_Structure_31643
C
[ "is_prime", "selection_sort_and_count_primes" ]
2
[ [ "selection_sort_and_count_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
25cf22a3bde9af32b6f5bfcca8aa301b2c0a3f8c
7ce3810910f1954b2fddc623ff994ac9a843a499
v1.0
complete
Data_Structure
Data_Structure_31104_C
import random from typing import List, Tuple def is_sorted(arr: List[int]) -> bool: """ Helper function to determine if the array is sorted. """ return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) def bogo_sort_probability(arr: List[int], max_iterations: int) -> Tuple[bool, int]: """ ...
import random from typing import List, Tuple def is_sorted(arr: List[int]) -> bool: """ Helper function to determine if the array is sorted. """ return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) def bogo_sort_probability(arr: List[int], max_iterations: int) -> Tuple[bool, int]: """ ...
from solution import bogo_sort_probability def test_sorted_array(): assert bogo_sort_probability([1, 2, 3], 1000) == (True, 0) def test_reverse_sorted_array(): sorted_status, iterations = bogo_sort_probability([3, 2, 1], 1000) assert sorted_status == False or (sorted_status == True and iterations < 1000) ...
[ { "docstring": "Helper function to determine if the array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Attempts to sort the array using Bogo Sort for a specified number of iterations.\nReturns:\n- True ...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List, Tuple\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to determine if the array is sorted.\...
trial_gpt4o_0
{ "original_instruction": "### Question: Large Number Bogo Sort Probability Simulation\n\nGiven the highly inefficient nature of the Bogo Sort algorithm, simulate how unlikely it is to sort even a small list of elements within a reasonable timeframe. Write a function that calculates the probability of Bogo Sort succe...
0.604611
Data_Structure_31104
C
[ "is_sorted", "bogo_sort_probability" ]
2
[ [ "bogo_sort_probability", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c30998076f5f96caff4bb74b783d816169a8d1fa
12716075288c1e9589ec286e1f75aa523943dd80
v1.0
complete
Data_Structure
Data_Structure_30970_C
def enhanced_diffie_hellman(a: int, p: int) -> bool: """ Perform Diffie-Hellman Key Exchange with validation and logging. This function ensures `p` is a prime number and `a` is its primitive root. It generates private keys for Alice and Bob, computes their public keys, derives the shared secret keys, a...
import random import sympy def is_prime(num): """ Check if the number is a prime. """ return sympy.isprime(num) def find_primitive_root(p): """ Find a primitive root modulo p. """ if not is_prime(p): return -1 phi = p - 1 factors = sympy.ntheory.factor_.factorint(p...
from solution import enhanced_diffie_hellman def test_enhanced_diffie_hellman_valid_primitive_root(): # p = 23 (prime), a = 5 (primitive root of 23) assert enhanced_diffie_hellman(5, 23) == True def test_enhanced_diffie_hellman_invalid_prime(): # p = 24 (not a prime) assert enhanced_diffie_hellman(5, ...
[ { "docstring": "Check if the number is a prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Find a primitive root modulo p.", "function_declaration": "def find_primitive_root(p):", "function_name": "find_pr...
[ 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\nimport sympy\n\ndef is_prime(num):\n \"\"\"\n Check if the number is a prime.\n \"\"\"\n return sympy.isprime(num)\n\ndef find_prim...
trial_gpt4o_0
{ "original_instruction": "### Question: Implement Enhanced Diffie-Hellman Key Exchange\nYou are tasked with implementing an enhanced version of the Diffie-Hellman key exchange algorithm. Your version needs to include additional validation checks and logging functionalities to help in debugging and understanding the ...
0.472483
Data_Structure_30970
C
[ "is_prime", "find_primitive_root", "enhanced_diffie_hellman" ]
3
[ [ "enhanced_diffie_hellman", "find_primitive_root" ], [ "enhanced_diffie_hellman", "is_prime" ], [ "find_primitive_root", "is_prime" ] ]
3
[]
false
[]
false
pytest
true
[ "sympy" ]
false
96a9b76c97f9f3837f63929b646dfe91f36c6e22
70a258ed8746540b82e94dc65ddec45e187eee00
v1.0
complete
Data_Structure
Data_Structure_31775_C
def iterative_merge_sort(arr: List[int]) -> List[int]: """ 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 >>> iterative_merge_sort([38, 27, 43, 3, 9, 82, 10]) [3, 9, 10, 27, 38, 43, 8...
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": "**Merge Sort Variation Implementation**\n\nYou 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 merg...
0.60806
Data_Structure_31775
C
[ "iterative_merge_sort", "merge" ]
2
[ [ "iterative_merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0f56baf252ad770af0036e931ec6026ad9ebcd27
a1a151a02b754c2b7948331b3c8fd5bb4835b4ce
v1.0
complete
Data_Structure
Data_Structure_31242_C
from typing import List import math def _l2_distance(vec: List[float]) -> float: """ Calculate the L2 norm (Euclidean norm) of a vector. """ pass def cosine_similarity(vec1: List[float], vec2: List[float]) -> float: """ Calculate the cosine similarity between two word frequency vectors. >...
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": "### Scenario:\nYou 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....
0.696297
Data_Structure_31242
C
[ "_l2_distance", "cosine_similarity" ]
2
[ [ "cosine_similarity", "_l2_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ff75c888d6646eb285abb08f311fe6608b9146bd
9227d70e22f34fce66098f867549eea13bb32e29
v1.0
complete
Data_Structure
Data_Structure_31170_C
import random def is_prime(n: int) -> bool: """ Test if a number is a prime number. >>> is_prime(2) True >>> is_prime(4) False >>> is_prime(7919) True """ pass def find_primitive_root(p: int) -> int: """ Find a primitive root for prime p. >>> find_primitive_root(23) 5 >>> find_prim...
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": "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.\n\n### Function Signature\n```python\ndef diffie_hellman_secure_key_exchange(a: int, p: int,...
0.566282
Data_Structure_31170
C
[ "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
5abebcecde4b76b9ff5e56f6bf7fdafcb7d05602
1db546efbc29cace3ee628a4033b36c433286af8
v1.0
complete
Data_Structure
Data_Structure_31546_C
from typing import List def multiply(matA: List[List[int]], matB: List[List[int]]) -> List[List[int]]: """ Multiply two n x n square matrices. Args: - matA: List of List of integers, first matrix - matB: List of List of integers, second matrix Returns: - A new matrix, product of matA and ...
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": "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 b...
0.543985
Data_Structure_31546
C
[ "multiply", "identity", "matrix_exponentiation" ]
3
[ [ "matrix_exponentiation", "identity" ], [ "matrix_exponentiation", "multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9b8a9c7886081d6a6c5be9410bf979059850b386
337a8ac17a665e31c0289cc6262aedc12c7bc248
v1.0
complete
Data_Structure
Data_Structure_31887_C
from typing import List def invert_matrix(matrix: List[List[float]]) -> List[List[float]]: """Given a square matrix, compute its inverse. Parameters: matrix (List[List[float]]): A list of lists representing an n x n square matrix of floats. Returns: List[List[float]]: Returns an n x n matrix ...
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": "**Matrix Inversion Function**\n\nGiven 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. \n\n### Function S...
0.55863
Data_Structure_31887
C
[ "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
61a720a853ed62b1afe446c2ca066fa4576c62c5
ec617099bd7fc7693a671467bb6aef607d1383b1
v1.0
complete
Data_Structure
Data_Structure_31993_C
def sum_and_count_primes(numbers: list) -> tuple: """ Identifies prime numbers from a list and computes the sum and count of primes. Args: numbers: List of integers. Returns: A tuple containing the sum of prime numbers and the count of prime numbers in the list. >>> sum_and_count_...
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": "#### Prime Number Summation and Count\n\nIntroduction:\nPrime 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 s...
0.780681
Data_Structure_31993
C
[ "prime_check", "sum_and_count_primes" ]
2
[ [ "sum_and_count_primes", "prime_check" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9c498e3484990925520cdcabc1c92365ccddc773
bd292b9003aea174023ad0b96c5ce83962af8b91
v1.0
complete
Data_Structure
Data_Structure_32035_C
def invert_matrix(matrix: List[List[float]]) -> List[List[float]]: """Invert a given square matrix (n x n). The function returns the inverse of the matrix if it exists; otherwise, it returns an error code matrix based on the following conditions: - [[-1]] if the input is not a valid matrix. - [[-2]...
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": "### Scenario:\nYou 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 optimal...
0.56501
Data_Structure_32035
C
[ "determinant", "get_minor", "invert_matrix" ]
3
[ [ "determinant", "get_minor" ], [ "invert_matrix", "determinant" ], [ "invert_matrix", "get_minor" ] ]
3
[]
false
[]
false
pytest
true
[]
true
52d6dded1a0b1368a2e60a12884ac00d802490f0
b315322914cdb85289ea8792ae4f10a311b44f25
v1.0
complete
Data_Structure
Data_Structure_31632_C
def gcd(a: int, b: int) -> int: """ Computes the greatest common divisor of a and b using the Euclidean algorithm >>> gcd(48, 18) == 6 >>> gcd(-48, 18) == 6 >>> gcd(0, 18) == 18 >>> gcd(18, 0) == 18 >>> gcd(0, 0) == 0 """ pass def lcm(a: int, b: int) -> int: """ Computes the least c...
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": "**Title**: Efficient GCD and LCM with Edge Case Handling\n\n**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 ...
0.755218
Data_Structure_31632
C
[ "gcd", "lcm", "trailing_zeroes", "gcd_bit" ]
4
[ [ "gcd_bit", "trailing_zeroes" ], [ "lcm", "gcd" ] ]
2
[]
false
[]
false
pytest
true
[]
true
17631c2276f94f165aea4b733cf5fc7753ef2633
b876ad1e717f78787fb0ca6b6364aad4e3e557e1
v1.0
complete
Data_Structure
Data_Structure_32175_C
def house_robber_circular(houses: List[int]) -> int: """Determine the maximum amount of money you can rob tonight without alerting the police on a circular street. >>> house_robber_circular([2, 3, 2]) 3 >>> house_robber_circular([1, 2, 3, 1]) 4 >>> house_robber_circular([]) 0 >>> house_r...
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": "### House Robber Problem with Enhanced Challenge\n\nYou 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,...
0.5359
Data_Structure_32175
C
[ "house_robber_linear", "house_robber_circular" ]
2
[ [ "house_robber_circular", "house_robber_linear" ] ]
1
[]
false
[]
false
pytest
true
[]
true
23623b02ed56f8cd3cdaf391c3d9c4013b10e0c3
d655939be6d773a2740d6ceb502a2666c3fc58ae
v1.0
complete
Data_Structure
Data_Structure_32091_C
def nearest_neighbor_improved(x: tuple, tSet: dict) -> str: """ Classify the input vector x by finding the nearest neighbor in tSet. Arguments: x -- A tuple representing the feature vector to classify. tSet -- A dictionary where keys are tuples representing training feature vectors, ...
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": "### Nearest Neighbor Classification\n\nGiven 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 traini...
0.569643
Data_Structure_32091
C
[ "euclidean_distance", "nearest_neighbor_improved" ]
2
[ [ "nearest_neighbor_improved", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e56204a1b706e1ebb7e25e1391f663017e0bbeae
059c365bad8045b1c779326ca46ede69eb22f7fc
v1.0
complete
Data_Structure
Data_Structure_31817_C
import random from sympy import isprime def diffie_hellman_secure(a: int, p: int, verbose: bool = False) -> None: """ Ensures secure key exchange using the Diffie-Hellman protocol. Input: - a (int): An integer candidate for the primitive root. - p (int): A prime number acting as the modulo base. ...
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": "### Diffie-Hellman with Error Handling\n\nYou 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 i...
0.579777
Data_Structure_31817
C
[ "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
8a0df20e124f888d06312a7656f02c994f64352d
a3e2328a79dc2128a8a9fc8bd3fc6c23a57d5c82
v1.0
complete
Data_Structure
Data_Structure_32117_C
def gcd(a: int, b: int) -> int: """ Compute the GCD of two integers using the Euclidean algorithm. """ pass 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) """ pass def trailing_zero(x: int) ...
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": "### Question: Computing Extended GCD and LCM with Additional Functionalities\n\nYou 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, y...
0.714566
Data_Structure_32117
C
[ "gcd", "lcm", "trailing_zero", "gcd_bit" ]
4
[ [ "gcd_bit", "trailing_zero" ], [ "lcm", "gcd" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6733773c0e8de19ce36a91aabd5b90190a3fb34a
3c76e3a0c0384ecd24d2ec3cde64fad2f54bd1c5
v1.0
complete
Data_Structure
Data_Structure_32241_C
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. """ def euler_totient(n: int) -> int: """ Returns the Euler's Totient function value φ(n) which counts the number ...
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": "### Advanced Cryptographic Algorithm Assessment\n\nYou 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 t...
0.574967
Data_Structure_32241
C
[ "find_order", "euler_totient", "find_primitive_root" ]
3
[ [ "find_primitive_root", "euler_totient" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bd14690013d313c1fd5b1ad06fc3d30b92f7ad27
9c652a57dddc48cef10a21bd48bccc6fd57755e1
v1.0
complete
Data_Structure
Data_Structure_32396_C
def optimized_multiply(multiplicand: list, multiplier: list) -> list: """Multiply two matrices using an optimized approach. :param multiplicand: List of lists representing the multiplicand matrix (m x n). :param multiplier: List of lists representing the multiplier matrix (n x p). :return: List of list...
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": "### Task\n\nYou'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...
0.531149
Data_Structure_32396
C
[ "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
c61de5557bda5e7a8a64a61c5041961a8438b5a7
6fab18126687bd22b38e4c4dce317824daae8c07
v1.0
complete
Data_Structure
Data_Structure_32096_C
def generate_key(k: int, seed: int = None) -> tuple: """Generate key pair for RSA encryption. Args: k (int): Number of bits in n. seed (int, optional): Seed for randomization. Returns: tuple: (n, e, d) as RSA keys. """ pass def encrypt(data: int, e: int, n: int) -> int: """Encr...
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": "### Context:\nAs 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.\n\n### Task...
0.738512
Data_Structure_32096
C
[ "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
1f31663b1145a45151392f0b8ff63360be53d8ec
ec03c7930eb71a50524361ae576f9dc31408f43a
v1.0
complete
Data_Structure
Data_Structure_32426_C
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...
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": "Enhanced Bogo Sort Analysis\n\n#### Context:\nImagine 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...
0.594522
Data_Structure_32426
C
[ "quick_sort", "bogo_sort", "compare_sorts" ]
3
[ [ "compare_sorts", "bogo_sort" ], [ "compare_sorts", "quick_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b5d311fe578590c8a7628159c8b31d51cdbbc7b7
b7f1f0b231a15b82a1436c448d42a8555767c0b4
v1.0
complete
Data_Structure
Data_Structure_32075_C
def diffie_hellman_key_exchange_v2(a: int, p: int) -> bool: """ Implement a more secured version of the Diffie-Hellman Key Exchange, ensuring both `p` (prime number) and `a` (primitive root) are appropriately validated. The goal is to complete the key exchange between two parties (Alice and Bob) and ...
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": "### Diffie-Hellman Key Exchange Implementation\n\n#### Background:\nDiffie-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.\n\n##...
0.490335
Data_Structure_32075
C
[ "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
8cd613e41346e131471b37efde19d74c3ceb4b6b
7520150068e60dd1501af87add39615f5a06076c
v1.0
complete
Data_Structure
Data_Structure_31891_C
def identity_matrix(size): """Creates an identity matrix of given size.""" pass def matrix_multiply(A, B): """Multiplies two matrices A and B.""" pass def matrix_exponentiation(matrix: list, exponent: int) -> list: """Computes the matrix to the power of the exponent using repeated squaring.""" ...
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": "### Context\nYou 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 m...
0.493891
Data_Structure_31891
C
[ "identity_matrix", "matrix_multiply", "matrix_exponentiation" ]
3
[ [ "matrix_exponentiation", "identity_matrix" ], [ "matrix_exponentiation", "matrix_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1ded044f7e955fd6ed1b94a0d79ede647bff5c51
6343e1376dbee6e19d4350168f513aad79eb3749
v1.0
complete
Data_Structure
Data_Structure_32310_C
def decimal_to_binary_util(val: str) -> str: """ Convert an 8-bit decimal number to its 8-bit binary representation. :param val: A string representing a decimal number in the range 0-255. :return: A string representing the binary format of the input number, padded to 8 bits. Example: >>> decim...
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": "### IP Address Binary Representation\n\n**Context**\nYou 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 manage...
0.635349
Data_Structure_32310
C
[ "decimal_to_binary_util", "decimal_to_binary_ip" ]
2
[ [ "decimal_to_binary_ip", "decimal_to_binary_util" ] ]
1
[]
false
[]
false
pytest
true
[]
true
52465a1db5b03a29058e1bc0c1c7c7144dfe4e34
16ef430d9454b28f39c7f236eb15497ee7a13f3d
v1.0
complete
Data_Structure
Data_Structure_32084_C
import math from typing import List, Optional def l2_distance(vec: List[float]) -> float: """ Compute the L2 distance (Euclidean norm) of a vector. >>> l2_distance([3, 4]) 5.0 """ pass def optimized_cosine_similarity(vec1: List[float], vec2: List[float], norm1: Optional[float] = None, norm2: Optio...
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": "### Question\nImplement 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...
0.572888
Data_Structure_32084
C
[ "l2_distance", "optimized_cosine_similarity" ]
2
[ [ "optimized_cosine_similarity", "l2_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
43bb2d6453a967c355f96e8814ba0f1fffb15158
6a28c135d9a048daef9b69e776fde7e496fdc1db
v1.0
complete
Data_Structure
Data_Structure_32547_C
import time from typing import List, Dict def stooge_sort(arr: List[int], l: int, h: int) -> List[int]: """ Sort the array `arr` from index `l` to `h` using Stooge sort. >>> stooge_sort([1, 3, 64, 5, 7, 8], 0, 5) [1, 3, 5, 7, 8, 64] >>> stooge_sort([1], 0, 0) [1] """ pass def optimized_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": "#### Scenario:\nYou'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. \n\n#### Problem Statem...
0.587824
Data_Structure_32547
C
[ "stooge_sort", "optimized_sort", "compare_performance" ]
3
[ [ "compare_performance", "optimized_sort" ], [ "compare_performance", "stooge_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
faf5adf3e35c1e239e15aca8186875e73675602c
452667c8d190694e8ac574062f162f0bae3b626b
v1.0
complete
Data_Structure
Data_Structure_32683_C
def gcd_bit_optimized(a: int, b: int) -> int: """ Returns the greatest common divisor (GCD) of two integers a and b using bitwise operations. >>> gcd_bit_optimized(48, 18) 6 >>> gcd_bit_optimized(17, 0) 17 >>> gcd_bit_optimized(0, 31) 31 """ def lcm_optimized(a: int, b: int) -> int...
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": "### Question: Efficient Calculation of LCM and Bitwise GCD\n\n#### Context\nYou 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...
0.751563
Data_Structure_32683
C
[ "gcd_bit_optimized", "lcm_optimized" ]
2
[ [ "lcm_optimized", "gcd_bit_optimized" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e0d1a12ce138a03eb52fae3629a81f108b9e68b5
d4f7cf29c4f77f677346fda28fd631f966d6d9df
v1.0
complete
Data_Structure
Data_Structure_32496_C
import math from typing import Tuple, Dict def find_nearest_neighbor(x: Tuple[float, ...], tSet: Dict[Tuple[float, ...], str]) -> str: """ Find the nearest neighbor of a given vector from a set of training vectors based on Euclidean distance. Args: x (tuple): A tuple representing the target vector. ...
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": "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...
0.691976
Data_Structure_32496
C
[ "euclidean_distance", "find_nearest_neighbor" ]
2
[ [ "find_nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7c9c399db628b322ff876850cc12a84be8d654fc
8a82e58fa6efce985a429e1616b142f756f6716c
v1.0
complete
Data_Structure
Data_Structure_32661_C
from typing import List, Dict def topological_sort(graph: Dict[int, List[int]]) -> List[int]: """ Perform topological sorting on a directed graph. This function should use both recursive and iterative approaches to implement topological sorting. It should raise a ValueError with the message "cycle" ...
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": "### Topological Sort Implementation\n\nTopological 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...
0.457008
Data_Structure_32661
C
[ "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
f37bdc27554b21f4bb09888f281f2f7aeef881bd
7c3c8b887a2b881306e204bf36393f09e515300f
v1.0
complete
Data_Structure
Data_Structure_32631_C
def matrix_power(mat: list, p: int) -> list: """ Compute the matrix raised to the power of p using the matrix exponentiation technique. Args: mat: A square matrix represented as a list of lists of integers. p: A positive integer representing the power to which the matrix mat is to be raised. ...
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": "#### Context\nMatrix 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.\n\n#### Tas...
0.504965
Data_Structure_32631
C
[ "multiply_matrices", "matrix_power" ]
2
[ [ "matrix_power", "multiply_matrices" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f0b4cc46a879a60d8991e16bcdece1b7429a0ef5
5c17c89bc5d646d95c330bab7461cb2bd4441c8f
v1.0
complete
Data_Structure
Data_Structure_32603_C
from typing import List def custom_invert_matrix(matrix: List[List[float]]) -> List[List[float]]: """ Inverts a given n x n matrix with custom constraints. Args: - matrix (List[List[float]]): A list of lists representing an n x n matrix where 2 <= n <= 10 and all elements are floats. Returns:...
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": "### Matrix Inversion with Custom Constraints\n\nYour 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 cof...
0.510498
Data_Structure_32603
C
[ "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
2ad03a13471d5a96273912cb4ff89a3a229ef0c5
b8529edbec24aeca31ba599a6522ee283df2880b
v1.0
complete
Data_Structure
Data_Structure_32648_C
from typing import List def enhanced_bubble_sort(arr: List[int], use_quick_sort_above: int = 20) -> List[int]: """ Sort a list of integers using an optimized version of the Bubble Sort algorithm. If the list size exceeds the given threshold, switch to Quick Sort for efficiency. Parameters: arr...
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": "### Question:\n\nYou 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 ...
0.638445
Data_Structure_32648
C
[ "bubble_sort", "quick_sort", "enhanced_bubble_sort" ]
3
[ [ "enhanced_bubble_sort", "bubble_sort" ], [ "enhanced_bubble_sort", "quick_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1041146d22becba4cdc9284cd6df7147d3bc4009
f7b2625d919de59f5ae4fd886faebbb092b97bd3
v1.0
complete
Data_Structure
Data_Structure_32405_C
import random def is_prime(n: int) -> bool: """ Function to check if a given number n is prime. Parameters: n (int): The number to check for primality. Returns: bool: True if n is a prime number, False otherwise. >>> is_prime(2) True >>> is_prime(4) False >>> is_prime...
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": "### Diffie-Hellman Key Exchange with Additional Security\n\nIn 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, whil...
0.608961
Data_Structure_32405
C
[ "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
0c43306d0e16bf3ac3e6495b76ede83394314a33
0550805f0408a7d431a6c8a35e18ebac5af20c32
v1.0
complete
Data_Structure
Data_Structure_32611_C
from typing import List def max_water_flow(capacity: List[List[int]], source: int, sink: int) -> int: """ Calculates the maximum flow from source to sink in a flow network using the Ford-Fulkerson algorithm. Parameters: capacity (List[List[int]]): A 2D list representing the capacity of each edge i...
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": "### Maximum Flow with Specific Constraints\n\n**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 maxim...
0.639427
Data_Structure_32611
C
[ "bfs", "max_water_flow" ]
2
[ [ "max_water_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a5173b8fe808ec4cbfbbd31a5e5f756956ee09d5
8568209b918e2278f30da654da482a062f846140
v1.0
complete
Data_Structure
Data_Structure_33020_C
from typing import List def optimized_quick_sort(arr: List[int]) -> List[int]: """ Implement the Quick Sort algorithm with the median-of-three pivot selection method. >>> optimized_quick_sort([3, 6, 8, 10, 1, 2, 1]) [1, 1, 2, 3, 6, 8, 10] >>> optimized_quick_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] ...
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": "### Quick Sort Analysis and Implementation\n\n**Objective**: Implement and analyze the Quick Sort algorithm and optimize its performance as required.\n\n**Problem Statement**:\nYou are given an array of integers. Write a function `optimized_quick_sort` which sorts the array in non-decreasin...
0.615487
Data_Structure_33020
C
[ "partition", "optimized_quick_sort" ]
2
[ [ "optimized_quick_sort", "partition" ] ]
1
[]
false
[]
false
pytest
true
[]
true
383d4bd491c301ebe47f56d26e52f715b522e30b
e3baba2db771d31083b1d15eac07a233c4553acb
v1.0
complete
Data_Structure
Data_Structure_32584_C
from typing import List def invert_matrix(matrix: List[List[float]]) -> List[List[float]]: """ Implement a function to invert an n x n invertible matrix. The function validation should handle specific error codes and return appropriate responses: - [[-1]] if the input is not a matrix. - [[-2]] if t...
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": "### Matrix Inversion Assessment Task\n\n#### Objective\nImplement 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.\n\n#### Requirements\n- Write a function `invert_matrix(m...
0.512372
Data_Structure_32584
C
[ "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
c36395f91474c6d52abae01547ca3e92398e90e1
3267dd84e1bf824e977c7fd8293261a4eefbbdad
v1.0
complete
Data_Structure
Data_Structure_33022_C
class Node: def __init__(self, val=None): self.val = val self.next = None def intersection(h1: Node, h2: Node) -> Node: """ Determine the intersection node of two singly linked lists. The intersection node is where the two lists merge into one. If there is no intersection, the function ...
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": "### Intersection of Linked Lists\n\n#### Objective:\nWrite 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 `...
0.532497
Data_Structure_33022
C
[ "get_length", "intersection" ]
2
[ [ "intersection", "get_length" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
d6b284f3c660601edbf0a5ab3273f4b058fdad1d
e8b6ca62ab5bc5ba4e8c938f629a736f03e1acbd
v1.0
complete
Data_Structure
Data_Structure_33045_C
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def is_subtree(s, t): """ Check if one binary tree is a subtree of another. Args: s: TreeNode, the root of the main tree. t: TreeNode, the root of the subtree. Returns: A...
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": "Check if One Binary Tree is a Subtree of Another\n\n#### Objective\nYou are tasked to write a function to check whether one binary tree (`t`) is a subtree of another binary tree (`s`). \n\n#### Function Signature\n```python\ndef is_subtree(s, t):\n pass\n```\n\n#### Input and Output\n- *...
0.613807
Data_Structure_33045
C
[ "is_same_tree", "is_subtree" ]
2
[ [ "is_subtree", "is_same_tree" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
9991abab3fff5cf393d444cabe30da4e6419b5f1
2783ef95f903cdc9c37bf4c78652bf0dd33ab80e
v1.0
complete
Data_Structure
Data_Structure_32842_C
from typing import List, Tuple def bogo_sort(arr: List[int], simulation: bool = False) -> Tuple[List[int], int]: """Sorts the list using Bogo Sort algorithm and returns the sorted list. Args: arr (List[int]): List of integers to sort. simulation (bool): If True, return the number of iterations. Defaul...
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": "### Bogo Sort Deep Dive and Alternative\n\n**Scenario**:\nYou 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....
0.557661
Data_Structure_32842
C
[ "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
dac2fbcc6749effc17810562fe9d2a267a84e723
46a5aa13d920dd1a73bedd1e18a72a5b49d52c1d
v1.0
complete
Data_Structure
Data_Structure_32799_C
def matrix_multiply(A: list, B: list) -> list: """ 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. """ # Implementation here def identity_matr...
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": "### Matrix Exponentiation Application in Computer Science\n\nMatrix 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 matri...
0.558684
Data_Structure_32799
C
[ "matrix_multiply", "identity_matrix", "matrix_exponentiation" ]
3
[ [ "matrix_exponentiation", "identity_matrix" ], [ "matrix_exponentiation", "matrix_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
85b352698491a230d16ecaa98819432828023409
ceca55f7fc769f4ad38b251f592548899c8493cb
v1.0
complete
Data_Structure
Data_Structure_32859_C
from typing import List def binary_insertion_sort(array: List[int]) -> List[int]: """ Sorts an array using an improved version of Insertion Sort that uses binary search to reduce the number of comparisons needed to find the correct insertion point. """ pass import pytest def test_binary_insertion...
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": "### Question:\n\nYou 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....
0.62954
Data_Structure_32859
C
[ "search_insert", "binary_insertion_sort" ]
2
[ [ "binary_insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
75af429644ed6dabe60db9c735c2f574b6bc2a82
1ad12d1fc9f6745ccab78089bf620b5d22a08cb1
v1.0
complete
Data_Structure
Data_Structure_32596_C
from typing import List def quicksort(arr: List[int]) -> List[int]: """Sorts an array of integers using the quicksort algorithm.""" pass def bucket_sort(arr: List[int]) -> List[int]: """Sorts a list of non-negative integers using a variant of the bucket sort algorithm, where quicksort is applied to so...
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": "## Problem Statement\n\nYou 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 ...
0.62187
Data_Structure_32596
C
[ "quicksort", "bucket_sort" ]
2
[ [ "bucket_sort", "quicksort" ] ]
1
[]
false
[]
false
pytest
false
[]
true
2ffbf102ed1c04ddbf5ef3a9902748b0dc1cccc9
a8b7c7518bcdffae78ca288ef967c60ce78f7490
v1.0
complete
Data_Structure
Data_Structure_32677_C
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): """Insert a key into the AVL Tree. ...
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": "### AVL Tree Insertion and Balance Verification\n\n#### Objective\nYou 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 ...
0.46975
Data_Structure_32677
C
[ "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
e3331b3cf6292ac0cc23b7bb3075cd7a08d8aa7a
e1ca5b093e6a805f89b0fe500777e64043ba5192
v1.0
complete
Data_Structure
Data_Structure_32781_C
def detect_plagiarism(submission, snippet): """ Args: submission: List of strings, where each string represents a line in the student's submission. snippet: List of strings, where each string represents a line in the code snippet to search for. Returns: List of integers representing ...
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": "### Coding Problem: Plagiarism Detection Using KMP Algorithm\n\nIn 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 ...
0.478782
Data_Structure_32781
C
[ "calculate_lps", "kmp_search", "detect_plagiarism" ]
3
[ [ "detect_plagiarism", "kmp_search" ], [ "kmp_search", "calculate_lps" ] ]
2
[]
false
[]
false
pytest
false
[]
true
bf165d74b16c1aa1f1b286d7ab6b04a5a4e68dce
d3d1df9ac50dac22bbcf021aafc75af4dce6704f
v1.0
complete
Data_Structure
Data_Structure_33065_C
from typing import List def find_pseudo_perfect_numbers(low: int, high: int) -> List[int]: """ Return a list of all pseudo-perfect numbers within the inclusive range from low to high. A pseudo-perfect number is a number whose digits can be raised to consecutive powers (starting at 1 for the left-most digit) a...
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": "### Pseudo-Perfect Numbers\n\nA \"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.\n\nFor example:\n- 89 = 8^1 + 9^2 = 8 + 81 = 89\n- 135 = 1^1 + 3^2 + 5^3 = 1 + 9 + 125 = 13...
0.559981
Data_Structure_33065
C
[ "is_pseudo_perfect", "find_pseudo_perfect_numbers" ]
2
[ [ "find_pseudo_perfect_numbers", "is_pseudo_perfect" ] ]
1
[]
false
[]
false
pytest
true
[]
true
41fcc4aec28f47396b7545d7597402b52aa79643
6531c799346a62b5799aedd8fefb56cda44f047b
v1.0
complete
Data_Structure
Data_Structure_33125_C
def calculate_frequency(file_path): """ Calculate the frequency of each character in the given text file. :param file_path: str, the path to the input text file. :return: dict, a dictionary with characters as keys and frequencies as values. """ pass def build_huffman_tree(frequency_dict): ...
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": "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.\n\n#### Requi...
0.495255
Data_Structure_33125
C
[ "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
0f10a5cff8a291a459036ef95ce79c6fcf645c8f
a7877c4560333ff1104eb5211f2d375578ec6878
v1.0
complete
Data_Structure
Data_Structure_32851_C
from typing import List def maximum_flow(adjacency_matrix: List[List[int]]) -> int: """ 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. Args: adjacency_matrix (List[List[int]]): A square matrix...
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": "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.\n\n**Function Signature:**\n```python\ndef maximum_flow(adjacency_matrix: List[List[int]]) -> int:\n pass\n```\n\n### Input\n- `adjacen...
0.602687
Data_Structure_32851
C
[ "bfs", "maximum_flow" ]
2
[ [ "maximum_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4f505dd7acd2f984d5db0ea63aa064add073d0c8
fbc2900d2c5362694f58167767c0ab95bb48e255
v1.0
complete
Data_Structure
Data_Structure_32614_C
from collections import deque from typing import List def dinic_bfs(capacity: List[List[int]], flow: List[List[int]], level: List[int], source: int, sink: int) -> bool: """ Perform BFS to update level graph. Args: - capacity: two-dimensional list representing the capacity matrix. - flow: two-dimens...
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": "### Task\n\nImplement 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.\n\n### Description:\n\nYour implementation should incl...
0.513812
Data_Structure_32614
C
[ "dinic_bfs", "dinic_dfs", "dinic" ]
3
[ [ "dinic", "dinic_bfs" ], [ "dinic", "dinic_dfs" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d9c4c69cd9aae0c460ceb91bce36b75f5b1cd1ff
7a0084abccdb7bba70f1762b66ad48c3540579fc
v1.0
complete
Data_Structure
Data_Structure_33127_C
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. """ # Your code here def nearest_neighbor(x...
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": "#### Scenario\nYou 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.\n\nTo accomplish this, you need to implement the follo...
0.647927
Data_Structure_33127
C
[ "euclidean_distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d7a5fc60f7f775940bd44af736ae2dca07c7e6bd
ea92a3023780b4462f967c09677e4b109cf1320a
v1.0
complete
Data_Structure
Data_Structure_33025_C
import math def distance(point1, point2): """ Calculate the Euclidean distance between two points in 3D space. >>> distance((0, 0, 0), (1, 1, 1)) == math.sqrt(3) >>> distance((1, 2, 3), (4, 5, 6)) == math.sqrt(27) >>> distance((0, 0, 0), (0, 0, 0)) == 0.0 """ def nearest_neighbor(point, ob...
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": "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.\n\n#### Scenario\nYou are aiding an autonomous drone navigation system that relies on sensor data to recogn...
0.577927
Data_Structure_33025
C
[ "distance", "nearest_neighbor", "classify_obstacle" ]
3
[ [ "classify_obstacle", "nearest_neighbor" ], [ "nearest_neighbor", "distance" ] ]
2
[]
false
[]
false
pytest
true
[]
true
77989150b76b2b475c374ae11474eaa30fc51b5a
d552146421b30c9bdb643226bfa496ea2e9c76ab
v1.0
complete
Data_Structure
Data_Structure_33016_C
def gcd_bitwise(a: int, b: int) -> int: """ Computes the greatest common divisor using bitwise operations. >>> gcd_bitwise(18, 24) 6 >>> gcd_bitwise(101, 103) 1 """ pass def lcm(a: int, b: int) -> int: """ Computes the least common multiple using the result from gcd_bitwise. >>> lcm(18, 24)...
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": "### Coding Task\n\n#### Scenario:\nYou 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 ...
0.744831
Data_Structure_33016
C
[ "trailing_zero", "gcd_bitwise", "lcm" ]
3
[ [ "gcd_bitwise", "trailing_zero" ], [ "lcm", "gcd_bitwise" ] ]
2
[]
false
[]
false
pytest
true
[]
true
28c5b5640d4c9d86935a366267e17b608f207111
1ba26c8ac9ccb225dcabee1e54321f2e499d3011
v1.0
complete
Data_Structure
Data_Structure_33397_C
def gcd(a, b): """ Compute the greatest common divisor of a and b. >>> gcd(48, 18) 6 >>> gcd(20, 5) 5 """ pass def find_order(a, n): """ Find the order of a modulo n, or -1 if no order exists. >>> find_order(3, 10) 4 >>> find_order(2, 10) -1 """ pass def euler_totient(n): "...
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": "### Coding Task: Primitive Root Generator\n\n#### Problem Statement:\nYou 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 comput...
0.641509
Data_Structure_33397
C
[ "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
f644bd8757bea5c26f6246fafdb7f9f9e60302b9
b944076fb7bf10fca87b55c142aa900e3178a3ed
v1.0
complete
Data_Structure
Data_Structure_33381_C
from typing import List def analyze_quick_sort(arr: List[int], simulation: bool) -> List[int]: """Implement Quick Sort algorithm and analyze its behavior on different types of input arrays. Args: arr (List[int]): A list of integers to be sorted. simulation (bool): A boolean flag to print the intermedi...
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": "### Quick Sort Implementation and Analysis\n\n**Context**:\nYou 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...
0.654353
Data_Structure_33381
C
[ "quick_sort", "partition", "analyze_quick_sort" ]
3
[ [ "analyze_quick_sort", "quick_sort" ], [ "quick_sort", "partition" ] ]
2
[]
false
[]
false
pytest
true
[]
true
fc1dff913d3c716f344eab477e121bf9c33f89cd
0ba0bb3d8d1d45d72905a16d4cbbda282532e8f5
v1.0
complete
Data_Structure
Data_Structure_33385_C
def efficient_sort(arr: List[int]) -> List[int]: """ Efficiently sorts an array of integers in ascending order. This implementation aims for a time complexity of O(n log n). >>> efficient_sort([1, 3, 64, 5, 7, 8]) [1, 3, 5, 7, 8, 64] >>> efficient_sort([]) [] >>> efficient_sort([1]...
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": "Efficient Sorting Algorithm\nYou are given an array of `n` integers. Your task is to implement an efficient sorting algorithm that sorts the array in ascending order.\n\nThe current implementation using Stooge Sort has high time complexity and is inefficient for large datasets. You need to ...
0.648092
Data_Structure_33385
C
[ "efficient_sort", "merge" ]
2
[ [ "efficient_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d138a1575ee433f424216782f64c5cec414accb9
66de0869791a7c30a53bb1481f6616a10ac5a250
v1.0
complete
Data_Structure
Data_Structure_33416_C
from typing import List def invert_matrix(matrix: List[List[float]]) -> List[List[float]]: """ Computes the inverse of a given n x n matrix using the cofactor method. >>> invert_matrix([[4, 7], [2, 6]]) [[0.6, -0.7], [-0.2, 0.4]] >>> invert_matrix([[1, 2, 3], [0, 1, 4], [5, 6, 0]]) [[-24, 18, 5], [...
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": "### Matrix Inversion Challenge\n\nYou 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.\n\n**Function Signature:**\n\n``...
0.568855
Data_Structure_33416
C
[ "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
f29a352b265e3e3d7582d0da0420a478a2274003
4e459ffe80fde569cf5393982594ed23566341cf
v1.0
complete
Data_Structure
Data_Structure_33308_C
from typing import List, Tuple def gcd_bitwise(a: int, b: int) -> int: """ Compute the greatest common divisor (GCD) of two non-negative integers using bitwise operations. >>> gcd_bitwise(12, 15) 3 >>> gcd_bitwise(100, 150) 50 """ pass def lcm_using_gcd(a: int, b: int) -> int: """ Comp...
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": "Given a list of non-negative integer pairs, implement two functions to perform the following:\n1. Compute the greatest common divisor (GCD) of each pair using bitwise operations.\n2. Compute the lowest common multiple (LCM) of each pair using the Euclidean algorithm for GCD.\n\n### Constrai...
0.75269
Data_Structure_33308
C
[ "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
db4fa2ff594d7b794abc1c028edfaec4c0f0a4a0
23ca5cd3c4d32960020ac212f870e97ae29cdd35
v1.0
complete
Data_Structure
Data_Structure_33356_C
from typing import Dict, Tuple def nearest_neighbor(query_point: Tuple[float, ...], training_set: Dict[Tuple[float, ...], any]) -> any: """ Find the label of the nearest neighbor to the query_point from the training_set. Args: query_point (Tuple[float, ...]): The point for which to seek the nearest neighb...
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": "### Nearest Neighbor Classifier\n\nYou 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.\n\n### Input\n- A dictionary where k...
0.696734
Data_Structure_33356
C
[ "euclidean_distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
61534181772ffb67d117b09bebbad24bcdc2b753
b8382026c26b4de44e98c876678f18c992ffdbb0
v1.0
complete
Data_Structure
Data_Structure_33412_C
def bucket_sort(arr): """ Sort a list of non-negative integers using Bucket Sort enhanced with Merge Sort for intra-bucket sorting. >>> bucket_sort([4, 1, 7, 3, 10]) [1, 3, 4, 7, 10] >>> bucket_sort([10, 4, 7, 1, 3]) [1, 3, 4, 7, 10] """ pass def merge_sort(arr): """ Sort a list of inte...
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": "### Coding Challenge: Enhanced Bucket Sort\n\n**Context**:\nYou 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. Y...
0.601509
Data_Structure_33412
C
[ "bucket_sort", "merge_sort", "merge" ]
3
[ [ "bucket_sort", "merge_sort" ], [ "merge_sort", "merge" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1856dae2a34dd79fa83d4f49b5a4163d05414d4a
aafbea27176557f0f39cf0b03d0b6d541fef28fd
v1.0
complete
Data_Structure
Data_Structure_33413_C
from typing import List def improved_sort(arr: List[int]) -> List[int]: """ Implement an improved sorting algorithm that demonstrates 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 ...
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": "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. \n\n### Requirements\n\n* **Input/...
0.64309
Data_Structure_33413
C
[ "improved_sort", "merge" ]
2
[ [ "improved_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b478ac4db6fed6b892ad728c6aff02bb3aa3a2fe
43aa78f84fdb9fb65f7e0e9ca54d47a3f606edbb
v1.0
complete
Data_Structure
Data_Structure_33344_C
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Given an unsorted array of integers, implement the Merge Sort algorithm to sort the array in ascending order. Parameters: arr (List[int]): The array to be sorted. Returns: List[int]: The sorted array in ascending order. ...
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": "Enhanced Sorting Assessment\n\n#### Context:\nStooge 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...
0.65284
Data_Structure_33344
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0759811fb28c9a95b9e9477ab6908d688830c7c1
5834e03aa4aebb215fd363c962bd950cb113ecab
v1.0
complete
Data_Structure
Data_Structure_33369_C
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): """ 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": "#### Problem Statement\nYou 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:\n\n1. **optimal_set_cover(U, S, costs)**: An optimal algorithm to find the minimum cost subcollection of `...
0.636808
Data_Structure_33369
C
[ "powerset", "optimal_set_cover", "greedy_set_cover" ]
3
[ [ "optimal_set_cover", "powerset" ] ]
1
[]
false
[]
false
pytest
true
[]
true
64d5093a49a23a42a40a8ecb7a3c288d102d2a4e
39d954cf68c6943a761ebf6ea74647cabe3f373e
v1.0
complete
Data_Structure
Data_Structure_33503_C
def compute_gcd(a, b): """ Compute the greatest common divisor (GCD) of two integers using the Euclidean algorithm. Args: a (int): First non-zero integer b (int): Second non-zero integer Returns: int: The GCD of a and b Examples: >>> compute_gcd(48, 18) 6 >>> compute_gcd(...
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": "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 ut...
0.747884
Data_Structure_33503
C
[ "compute_gcd", "compute_lcm", "count_trailing_zeros" ]
3
[ [ "compute_lcm", "compute_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
22f0ebe9b7919f9ddd1f4b69798b6739c52ffb6f
4b3cf8f1ba484467f6a85206bf76ca63e74537c9
v1.0
complete
Data_Structure
Data_Structure_33554_C
def word_squares(words: List[str]) -> List[List[str]]: """Given a set of words (without duplicates), find all possible word squares that can be formed from them. A word square is a sequence of words where the kth row and column read the exact same string, for all valid k. The function takes a list...
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": "<|Analysis Begin|>\n\n### Algorithm Analysis\n\n#### Core Identification\n* **Algorithm/Data Structure**: The provided code utilizes a **backtracking algorithm** to construct word squares.\n* **Complexity**: \n * **Time Complexity**: In the worst case, the time complexity of the algorithm ...
0.601457
Data_Structure_33554
C
[ "build_prefix_dict", "backtrack", "word_squares" ]
3
[ [ "word_squares", "backtrack" ], [ "word_squares", "build_prefix_dict" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2c468212403b4f8ce5deb15883c033b125e5c4f4
35600202c65bcf4f12fc00b7a656c7c7c2c74325
v1.0
complete
Data_Structure
Data_Structure_33660_C
from typing import List def power_matrix(mat: List[List[int]], exp: int) -> List[List[int]]: """ Given a square matrix `mat` of size \( n \times n \) and an integer `exp`, this function returns the matrix raised to the power of `exp`. >>> power_matrix([[1, 2], [3, 4]], 2) [[7, 10], [15, 22]]...
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": "## Problem Statement\nGiven 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`.\n\n### Input\n- A square matrix `mat` of size \\( n \\...
0.527474
Data_Structure_33660
C
[ "multiply_matrices", "identity_matrix", "power_matrix" ]
3
[ [ "power_matrix", "identity_matrix" ], [ "power_matrix", "multiply_matrices" ] ]
2
[]
false
[]
false
pytest
true
[]
true
31b27f602159e14baf2d522340c659d78eca6f84
bdb1b4f4e31fa5bbce312b380181bddbfa28efac
v1.0
complete
Data_Structure
Data_Structure_33328_C
from typing import List def bucket_sort(arr: List[int]) -> List[int]: """ Sort a list of integers in the range 0 to 1000 using the Bucket Sort algorithm with nested Insertion Sort. >>> bucket_sort([29, 25, 3, 49, 9, 37, 21, 43]) == [3, 9, 21, 25, 29, 37, 43, 49] >>> bucket_sort([100, 200, 300]) == [100, 20...
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": "##### Context:\nYou 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 t...
0.590995
Data_Structure_33328
C
[ "insertion_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
09046cdd2a7fa11d87559616ca98b6638a70cb7b
629967f47fea7bc54e732bbb182902f7f512683c