version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | instruct | Data_Structure | Data_Structure_37819_I | ## Coding Assessment Question
### Context
You're working on a pattern recognition system and need to classify a set of query points based on a labeled training set using the nearest neighbor algorithm. The task involves implementing the key parts of this algorithm to correctly classify the query points.
### Problem S... | import math
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points.
Arguments:
point1 : tuple -- A tuple representing the first point.
point2 : tuple -- A tuple representing the second point.
Returns:
float -- The Euclidean ... | from solution import classify_query_points, euclidean_distance
def test_euclidean_distance():
assert math.isclose(euclidean_distance((0, 0), (3, 4)), 5.0)
assert math.isclose(euclidean_distance((1, 2), (4, 6)), 5.0)
assert math.isclose(euclidean_distance((1, 1), (1, 1)), 0.0)
def test_classify_single_quer... | [
{
"docstring": "Calculate the Euclidean distance between two points.\n\nArguments:\n point1 : tuple -- A tuple representing the first point.\n point2 : tuple -- A tuple representing the second point.\n \nReturns:\n float -- The Euclidean distance between the two points.",
"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": "import math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculates the Euclidean distance between two points.\n \n Arguments:\n p... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00037819",
"row_id": 37819,
"seed_ids": "[260]"
} | 0.626843 | Data_Structure_37819 | I | [
"euclidean_distance",
"classify_query_points"
] | 2 | [
[
"classify_query_points",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4f725b8dd5d3c7afb70234c95b84c7fd7f0d01a4 | b16a02f53b13f8c4d7bf07a53068c6ded9abab7b | |||
v1.0 | instruct | Data_Structure | Data_Structure_37824_I | ### Matrix Inversion
You are provided with an algorithm that inverts an \(n \times n\) matrix. The matrix inversion algorithm includes calculating the matrix of minors, creating the matrix of cofactors, adjugating, and scaling by the inverse of the determinant. Your task is to enhance the existing algorithm to improve... | from typing import List
def calculate_determinant(matrix: List[List[float]]) -> float:
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
determinant = 0
for c in range(n):
determinant += ((-1) ** c... | from solution import enhanced_invert_matrix
def test_non_square_matrix():
matrix = [
[1, 2],
[3, 4, 5]
]
assert enhanced_invert_matrix(matrix) == [[0]]
def test_singular_matrix():
matrix = [
[4, 2],
[2, 1]
]
assert enhanced_invert_matrix(matrix) == [[1]]
def te... | [
{
"docstring": null,
"function_declaration": "def calculate_determinant(matrix):",
"function_name": "calculate_determinant",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def get_minor(matrix, i, j):",
"function_name": "get_minor",
"parameter_list"... | [
0,
0,
0,
1,
1,
0,
1,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Optional\n\ndef matrix_determinant(matrix: List[List[float]], n: int) -> float:\n if n == 1:\n return matrix[0][0]\n if ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00037824",
"row_id": 37824,
"seed_ids": "[347]"
} | 0.543605 | Data_Structure_37824 | I | [
"calculate_determinant",
"get_minor",
"transpose",
"cofactor",
"enhanced_invert_matrix"
] | 5 | [
[
"calculate_determinant",
"get_minor"
],
[
"cofactor",
"calculate_determinant"
],
[
"cofactor",
"get_minor"
],
[
"enhanced_invert_matrix",
"calculate_determinant"
],
[
"enhanced_invert_matrix",
"cofactor"
],
[
"enhanced_invert_matrix",
"transpose"... | 6 | [] | false | [] | false | pytest | true | [] | true | d4723dc5da5a2e3e3986f1dae9d216f04b3dfd5f | b810121cdc8c6bed950d5985f47d298ed2c979a4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_37865_I | ### Context
To verify the understanding of binary exponentiation and its applications, especially in contexts involving large numbers, you'll implement an advanced function. This function should compute a value efficiently using properties of exponentiation and modular arithmetic.
### Problem Statement
Design a functi... | def mod_exponentiation(a: int, n: int, mod: int = None) -> int:
"""
Computes a^n efficiently. If `mod` is provided, computes a^n % mod.
"""
if mod is None:
return _mod_exponentiation(a, n)
else:
return _mod_exponentiation_with_mod(a, n, mod)
def _mod_exponentiation(a: int, n: in... | from solution import mod_exponentiation
def test_mod_exponentiation_no_mod():
assert mod_exponentiation(2, 10) == 1024
def test_mod_exponentiation_with_mod():
assert mod_exponentiation(2, 10, 1000) == 24
def test_mod_exponentiation_larger_base():
assert mod_exponentiation(3, 18) == 387420489
def test_mo... | [
{
"docstring": "Computes a^n efficiently. If `mod` is provided, computes a^n % mod.",
"function_declaration": "def mod_exponentiation(a, n, mod=None):",
"function_name": "mod_exponentiation",
"parameter_list": "(a, n, mod=None)"
},
{
"docstring": "Computes a^n using binary exponentiation.",
... | [
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 mod_exponentiation(a: int, n: int, mod: int = None) -> int:\n if n == 0:\n return 1 if mod is None else 1 % mod\n\n result = 1\n base = a\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00037865",
"row_id": 37865,
"seed_ids": "[151]"
} | 0.654527 | Data_Structure_37865 | I | [
"mod_exponentiation",
"_mod_exponentiation",
"_mod_exponentiation_with_mod"
] | 3 | [
[
"mod_exponentiation",
"_mod_exponentiation"
],
[
"mod_exponentiation",
"_mod_exponentiation_with_mod"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cbaed219511910ffe14ba845d87bef7dae070bf7 | 5e287d96d45aaa4722eadcbc11efb0febcb326d2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_37877_I | You are given an array of integers. Your task is to implement an optimized Quick Sort algorithm. The optimization should involve using a median-of-three method to choose the pivot and switching to Insertion Sort when the subarray size falls below a certain threshold.
### Input:
* An integer array `arr` of size `n` (1 ... | def insertion_sort(arr, low, high):
for i in range(low + 1, high + 1):
key = arr[i]
j = i - 1
while j >= low and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def median_of_three(arr, low, high):
mid = (low + high) // 2
if arr[low] > arr[m... | from solution import optimized_quick_sort
def test_single_element():
assert optimized_quick_sort([1]) == [1]
def test_already_sorted():
assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted():
assert optimized_quick_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_rand... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, low, high):",
"function_name": "insertion_sort",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
... | [
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 insertion_sort(arr, low, high):\n for i in range(low + 1, high + 1):\n key = arr[i]\n j = i - 1\n while j >= low and key < arr[j]:... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00037877",
"row_id": 37877,
"seed_ids": "[25]"
} | 0.569595 | Data_Structure_37877 | I | [
"insertion_sort",
"median_of_three",
"quick_sort",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"quick_sort"
],
[
"quick_sort",
"insertion_sort"
],
[
"quick_sort",
"median_of_three"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 0c7ddeb28e2335babfd3d61239d30a6bf6dcccb3 | d3f848be2506f5e01bb60002b67055a0f16b0a30 | |||
v1.0 | instruct | Data_Structure | Data_Structure_37918_I | ### Coding Problem: Dual-Heap Sort
#### Context:
Heap Sort is a comparison-based sorting technique that uses a binary heap data structure. It consists of two main operations, heap construction and repeated extraction of the maximum (or minimum) element. Given the code snippets of Max-Heap Sort and Min-Heap Sort, your ... | def heapify(arr, n, i, max_heap=True, simulation=False):
largest_smallest = i
left = 2 * i + 1
right = 2 * i + 2
if max_heap:
if left < n and arr[largest_smallest] < arr[left]:
largest_smallest = left
if right < n and arr[largest_smallest] < arr[right]:
... | from solution import generic_heap_sort
def test_max_heap_sort():
assert generic_heap_sort([3, 2, 1, 4, 5], "max") == [1, 2, 3, 4, 5]
assert generic_heap_sort([10, 20, 15, 30, 40], "max") == [10, 15, 20, 30, 40]
assert generic_heap_sort([-1, -3, -2, -5, -4], "max") == [-5, -4, -3, -2, -1]
def test_min_heap... | [
{
"docstring": null,
"function_declaration": "def heapify(arr, n, i, max_heap=True, simulation=False):",
"function_name": "heapify",
"parameter_list": "(arr, n, i, max_heap=True, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def generic_heap_sort(arr, heap_type='max... | [
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 heapify(arr, n, i, max_heap=True, simulation=False):\n largest_smallest = i \n left = 2 * i + 1 \n right = 2 * i + 2 \n\n if max_heap:\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00037918",
"row_id": 37918,
"seed_ids": "[8]"
} | 0.630953 | Data_Structure_37918 | I | [
"heapify",
"generic_heap_sort"
] | 2 | [
[
"generic_heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 532e55030175e5f9876b209e3bd525c65008df58 | eb70f5c47a7a60711272fc83c09d6241080edc4e | |||
v1.0 | instruct | Data_Structure | Data_Structure_37976_I | ### Problem: Implementing Heap Sort
You are required to implement the Heap Sort algorithm. You must provide two implementations: one using a Max Heap and another using a Min Heap. Both implementations should sort an array of integers in ascending order. Your task is to define two functions - `heap_sort_max` and `heap_s... | def heapify_max(arr, n, i):
"""
Creates a max heap from a given subtree.
"""
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest !... | from solution import heap_sort_max, heap_sort_min
def test_heap_sort_max():
assert heap_sort_max([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
assert heap_sort_max([9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
assert heap_sort_max([-1, 2, 0, -2, 1, 3]) == [-2, -1, 0,... | [
{
"docstring": "Creates a max heap from a given subtree.",
"function_declaration": "def heapify_max(arr, n, i):",
"function_name": "heapify_max",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Sorts an array in ascending order using max heap.",
"function_declaration": "def heap_sort_... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def heapify_max(arr, n, i):\n \"\"\"\n Creates a max heap from a given subtree.\n \"\"\"\n largest = i\n left = 2 * i + 1\n right = 2 * i + ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00037976",
"row_id": 37976,
"seed_ids": "[8]"
} | 0.714325 | Data_Structure_37976 | I | [
"heapify_max",
"heap_sort_max",
"heapify_min",
"heap_sort_min"
] | 4 | [
[
"heap_sort_max",
"heapify_max"
],
[
"heap_sort_min",
"heapify_min"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cc744d4b5f951b6ab51c7fe566e67cce3bbeb7fb | 9bbeafadf454626d1b3c374de10997a5407845ec | |||
v1.0 | instruct | Data_Structure | Data_Structure_37985_I | ### Context
You are tasked with improving the RSA encryption key generation process to address two primary issues: performance and security.
### Problem Statement
Enhance the `generate_key` function to make the RSA key generation process more efficient and secure. Specifically, you need to implement the following impr... | import random
from sympy import isprime
def generate_key(k, seed=None):
"""
Enhanced RSA key generating algorithm.
k : int : the number of bits in n.
seed : int, optional : Seed for reproducibility.
Returns tuple(n, e, d)
"""
if seed is not None:
random.seed(seed)
def gener... | from solution import generate_key, modinv
def test_generate_key():
n, e, d = generate_key(16, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
data = 20
encrypted = pow(data, e, n)
decrypted = pow(encrypted, d, n)
assert decrypted == data
def test_... | [
{
"docstring": "Enhanced RSA key generating algorithm.\nk : int : the number of bits in n.\nseed : int, optional : Seed for reproducibility.\nReturns tuple(n, e, d)",
"function_declaration": "def generate_key(k, seed=None):",
"function_name": "generate_key",
"parameter_list": "(k, seed=None)"
},
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime\nfrom sympy.ntheory import nextprime\n\ndef generate_prime_candidate(bit_size):\n \"\"\" Generate an odd integer r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00037985",
"row_id": 37985,
"seed_ids": "[154]"
} | 0.607219 | Data_Structure_37985 | I | [
"generate_key",
"modinv",
"extended_gcd"
] | 3 | [
[
"generate_key",
"modinv"
],
[
"modinv",
"extended_gcd"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | c22d765ead8f37dcdb48d0409472a4e67204cf11 | b11796ac47aebe8785a70b897d9bacde35176edc | |||
v1.0 | instruct | Data_Structure | Data_Structure_38034_I | ### Bogo Sort Timing Challenge
Given the inefficiency and randomness of the Bogo Sort algorithm, it is critical to handle edge cases and understand its limitations. Your task is to implement an improved version of Bogo Sort that can identify certain optimizations and handle typical scenarios more effectively. The exer... | import random
import time
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Check if the array is sorted in ascending order.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def bogo_sort_timed(arr: List[int], timeout: int = 10) -> List[int]:
"""
Sorts the arr... | from solution import bogo_sort_timed
def test_bogo_sort_already_sorted():
assert bogo_sort_timed([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]
def test_bogo_sort_reverse_order():
res = bogo_sort_timed([5, 4, 3, 2, 1], 5)
assert res == sorted(res) # Since it might timeout, we check for being sorted
def test_bog... | [
{
"docstring": "Check if the array is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the array using Bogo Sort algorithm with added timeout functionality.\nIf the array cannot be sor... | [
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\nimport time\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Check if the array is sorted in ascending order... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00038034",
"row_id": 38034,
"seed_ids": "[16]"
} | 0.513237 | Data_Structure_38034 | I | [
"is_sorted",
"bogo_sort_timed"
] | 2 | [
[
"bogo_sort_timed",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9995729fb280925e4fed2ab7b8c8dbaef11bf259 | 7db43a22fb068b8ceb3e602fa2efc0501bb6ea1c | |||
v1.0 | instruct | Data_Structure | Data_Structure_38068_I | ### Question: Implement an Enhanced Interpolation Search
You are given a sorted array of integers and a target search key. Implement a function `enhanced_interpolation_search` that searches for the target key in the array. The search should be efficient and robust, even for arrays that are not uniformly distributed.
... | import math
from typing import List
def enhanced_interpolation_search(arr: List[int], key: int) -> int:
if len(arr) == 0:
return -1
low = 0
high = len(arr) - 1
threshold = int(math.log2(len(arr)))
guesses = 0
while low <= high and key >= arr[low] and key <= arr[high]:
if low =... | from solution import enhanced_interpolation_search
def test_enhanced_interpolation_search():
# Basic tests
assert enhanced_interpolation_search([5, 10, 12, 14, 17, 20, 21], 14) == 3
assert enhanced_interpolation_search([5, 10, 12, 14, 17, 20, 21], 55) == -1
assert enhanced_interpolation_search([], 5) =... | [
{
"docstring": null,
"function_declaration": "def enhanced_interpolation_search(arr, key):",
"function_name": "enhanced_interpolation_search",
"parameter_list": "(arr, key)"
},
{
"docstring": null,
"function_declaration": "def binary_search(arr, low, high, key):",
"function_name": "b... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import List\n\ndef interpolation_search(arr: List[int], key: int, low: int, high: int) -> int:\n attempts = 0\n max_attempts = ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038068",
"row_id": 38068,
"seed_ids": "[192]"
} | 0.564987 | Data_Structure_38068 | I | [
"enhanced_interpolation_search",
"binary_search"
] | 2 | [
[
"enhanced_interpolation_search",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a2c97d088e96d45934a42d117fec433383a8f51e | 426c1fde5d5294073fa075aa0d3a927e3c2cff3a | |||
v1.0 | instruct | Data_Structure | Data_Structure_38079_I | Prime Path Finder
Given an undirected graph where each node corresponds to an integer, design a function to find the shortest path between two nodes where all the nodes in the path are prime numbers.
#### Task
Write a function `prime_shortest_path(graph, start, end)` that:
1. Takes an adjacency list `graph`, where `g... | from collections import deque
def prime_check(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def prime_sh... | import pytest
from solution import prime_shortest_path
def test_prime_shortest_path_found():
graph = {
2: [3, 5],
3: [2, 5, 11],
5: [2, 3, 7, 11],
7: [5, 11],
11: [3, 5, 7],
4: [6], # Non-prime nodes
6: [4] # Non-prime nodes
}
assert prime_shortest_p... | [
{
"docstring": null,
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def prime_shortest_path(graph, start, end):",
"function_name": "prime_shortest_path",
"parameter_list": "(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 collections import deque\n\ndef is_prime(n):\n \"\"\"\n Check if a number is prime\n \"\"\"\n if n <= 1:\n return False\n if n <= 3... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038079",
"row_id": 38079,
"seed_ids": "[143]"
} | 0.599324 | Data_Structure_38079 | I | [
"prime_check",
"prime_shortest_path"
] | 2 | [
[
"prime_shortest_path",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 11cf641a41fab4f748bc9225856a4b0d3b50662e | 3448ede52f5caa258fe62fa64f60740ec1bba8ef | |||
v1.0 | instruct | Data_Structure | Data_Structure_38143_I | ### Linked List Palindrome Checker
#### Objective
Given a singly linked list, you need to determine if the list is a palindrome. A list is considered a palindrome if it reads the same forwards and backwards.
#### Function Specifications
Implement the function `def check_palindrome(head: ListNode) -> bool:` where:
- `... | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_list(head: ListNode) -> ListNode:
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
... | from solution import ListNode, check_palindrome
def create_linked_list(values):
if not values:
return None
head = ListNode(values[0])
current = head
for value in values[1:]:
current.next = ListNode(value)
current = current.next
return head
def test_single_element():
hea... | [] | [
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 ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef check_palindrome(head: ListNode) -> bool:\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038143",
"row_id": 38143,
"seed_ids": "[246]"
} | 0.687677 | Data_Structure_38143 | I | [
"reverse_list",
"check_palindrome"
] | 2 | [
[
"check_palindrome",
"reverse_list"
]
] | 1 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | 8eb87e34430a167dbb1b881f3320c5ec846a7670 | 2944687d007706aacfbe4ef7cd77af20abcc1196 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38161_I | You are required to implement the Bucket Sort algorithm with the following specifications and constraints.
### Input:
* An array `arr` of `n` non-negative integers where \(1 \leq n \leq 10^5\).
* The integers in `arr` range from `0` to `10000`.
### Output:
* A sorted array containing the same elements as `arr`.
### ... | def bucket_sort(arr):
''' Bucket Sort
'''
if not arr:
return arr
max_value = max(arr)
bucket_count = len(arr)
size = (max_value / bucket_count) + 1
# Create buckets
buckets = [[] for _ in range(bucket_count)]
# Assign elements to the bucket
for v in arr:
... | from solution import bucket_sort, next_sort
def test_empty_array():
assert bucket_sort([]) == []
def test_single_element():
assert bucket_sort([1]) == [1]
def test_sorted_array():
assert bucket_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert bucket_sort([5, 4, 3, 2, ... | [
{
"docstring": "Bucket Sort\n ",
"function_declaration": "def bucket_sort(arr):",
"function_name": "bucket_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Insertion Sort\n ",
"function_declaration": "def next_sort(arr):",
"function_name": "next_sort",
"parameter_list": ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bucket_sort(arr):\n ''' Bucket Sort\n '''\n if not arr:\n return arr\n \n max_value = max(arr)\n size = max_value // len(arr) + 1... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038161",
"row_id": 38161,
"seed_ids": "[26]"
} | 0.571891 | Data_Structure_38161 | I | [
"bucket_sort",
"next_sort"
] | 2 | [
[
"bucket_sort",
"next_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4544bcb1ea11340a08dc28ce7adda3448742039f | 52148b9a5ecda40348dce4c31b88b59157bd1ef9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38187_I | **Question: Implement and Optimize Bucket Sort**
### Scenario
You are working to improve a data analysis pipeline where large datasets of floating-point numbers need to be sorted efficiently. The data tends to be uniformly distributed across a range, but you also want the solution to gracefully handle the cases where ... | from typing import List
def insertion_sort(arr: List[float]) -> List[float]:
"""
A simple implementation of insertion sort that will sort the elements in a list.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j... | from solution import bucket_sort
def test_bucket_sort_with_uniform_distribution():
data = [0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51]
assert bucket_sort(data) == [0.23, 0.25, 0.32, 0.42, 0.47, 0.51, 0.52]
def test_bucket_sort_with_empty_array():
assert bucket_sort([]) == []
def test_bucket_sort_with_singl... | [
{
"docstring": "A simple implementation of insertion sort that will sort the elements in a list.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts a list of floating-point numbers using the bucket 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\nimport math\n\ndef insertion_sort(arr: List[float]) -> List[float]:\n for i in range(1, len(arr)):\n key = arr[i]\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038187",
"row_id": 38187,
"seed_ids": "[26]"
} | 0.466169 | Data_Structure_38187 | I | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fbc5d6bd2caebe71ee987cc7d748af0445603c66 | b0812a5431e51451fae17b4d7bb306e244d84dbe | |||
v1.0 | instruct | Data_Structure | Data_Structure_38255_I | **Problem Statement:**
You are a member of a cryptography team working on implementing a secure communication system. One of the tasks is to compute modular inverses to encode and decode messages securely. Your job is to implement two crucial functions: `extended_gcd` and `modular_inverse`.
1. **Function `extended_gc... | def extended_gcd(a: int, b: int):
"""
Given two integers a and b, return a tuple (s, t, g) such that a*s + b*t = g, where g is the GCD of a and b.
"""
if b == 0:
return (1, 0, a)
else:
s, t, g = extended_gcd(b, a % b)
return (t, s - (a // b) * t, g)
def modular_inverse(a: in... | from solution import extended_gcd, modular_inverse
def test_extended_gcd():
assert extended_gcd(30, 20) == (1, -1, 10) or extended_gcd(30, 20) == (-1, 2, 10)
assert extended_gcd(48, 18) == (1, -2, 6) or extended_gcd(48, 18) == (-1, 3, 6)
assert extended_gcd(7, 5) == (-2, 3, 1) or extended_gcd(7, 5) == (3, ... | [
{
"docstring": "Given two integers a and b, return a tuple (s, t, g) such that a*s + b*t = g, where g is the GCD of a and b.",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Given two integers a and m, return ... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def extended_gcd(a: int, b: int):\n \"\"\"\n Given two integers a and b, return a tuple (s, t, g) such that a*s + b*t = g, where g is the GCD of a and b... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00038255",
"row_id": 38255,
"seed_ids": "[161]"
} | 0.534784 | Data_Structure_38255 | I | [
"extended_gcd",
"modular_inverse"
] | 2 | [
[
"modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7a5598244070aaad8b14fa6f51eef9dc1ebfbaaf | 4f6070563ce0f95844aebdb55597a2c130bed7f2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38283_I | **Context**:
You are given the task of sorting a list of floating-point numbers, ensuring that the algorithm performs efficiently for values uniformly distributed between [0, 1). The implementation should use the bucket sort algorithm, followed by insertion sort for sorting individual buckets.
**Function Signature**:
... | from typing import List
def insertion_sort(arr: List[float]) -> List[float]:
"""
Helper function to perform insertion sort on a list.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
... | from solution import bucket_sort_floats
def test_bucket_sort_floats_basic():
assert bucket_sort_floats([0.22, 0.45, 0.12, 0.36, 0.80, 0.72]) == [0.12, 0.22, 0.36, 0.45, 0.72, 0.80]
def test_bucket_sort_floats_with_duplicates():
assert bucket_sort_floats([0.50, 0.50, 0.50]) == [0.50, 0.50, 0.50]
def test_buck... | [
{
"docstring": "Helper function to perform insertion sort on a list.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts a list of floating-point numbers using bucket sort.",
"function_declaration": "... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bucket_sort_floats(arr: List[float]) -> List[float]:\n def insertion_sort(bucket: List[float]) -> List[float]:\n for ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038283",
"row_id": 38283,
"seed_ids": "[26]"
} | 0.581314 | Data_Structure_38283 | I | [
"insertion_sort",
"bucket_sort_floats"
] | 2 | [
[
"bucket_sort_floats",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9de4bf7505d19350c8d58fe8d924a6f11b479620 | dca78548a0901b037621aecbc106b707ea302dd0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38312_I | #### Context
You are working for a financial data analytics company, and one common task is to quickly compute the sum of daily stock prices over a specific range of days, as well as update the price for a specific day when new data comes in. Given that these operations need to be highly efficient due to the large volu... | def construct_tree(prices):
"""
Construct the Fenwick Tree (Binary Indexed Tree) from the given stock prices.
"""
n = len(prices)
bit_tree = [0] * (n + 1)
for i in range(n):
update(bit_tree, i, prices[i])
return bit_tree
def get_sum(bit_tree, i):
"""
Compute the pr... | from solution import construct_tree, get_sum, update
def test_construct_tree():
prices = [3, 2, -1, 6, 5, 4, -3]
bit_tree = construct_tree(prices)
expected_bit_tree = [0, 3, 5, -1, 10, 5, 9, -3]
assert bit_tree == expected_bit_tree
def test_get_sum():
prices = [3, 2, -1, 6, 5, 4, -3]
bit_tree ... | [
{
"docstring": "Construct the Fenwick Tree (Binary Indexed Tree) from the given stock prices.",
"function_declaration": "def construct_tree(prices):",
"function_name": "construct_tree",
"parameter_list": "(prices)"
},
{
"docstring": "Compute the prefix sum from day 1 to day i (0-based index)... | [
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 construct_tree(prices):\n \"\"\"\n Construct the Fenwick Tree (Binary Indexed Tree) from the given stock prices.\n \"\"\"\n n = len(prices)\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00038312",
"row_id": 38312,
"seed_ids": "[305]"
} | 0.473054 | Data_Structure_38312 | I | [
"construct_tree",
"get_sum",
"update"
] | 3 | [
[
"construct_tree",
"update"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5e718c6a441b533575df2c8b3c85232497949ca4 | b9f3f30a567552be45908a35aed8cf3abebe98c6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38321_I | Given the fundamental numerical concepts demonstrated in the provided code snippets, you are required to implement a function that computes the LCM of an array of integers efficiently.
### Problem Statement
Implement a function `lcm_array(arr: List[int]) -> int` that takes a list of non-negative integers `arr` and ret... | from typing import List
from math import gcd
def lcm(x, y):
return x * y // gcd(x, y)
def lcm_array(arr: List[int]) -> int:
result = 1
for num in arr:
if num == 0:
continue
result = lcm(result, num)
return result
# Example usage
# print(lcm_array([2, 7, 3])) # Should retu... | from solution import lcm_array
def test_lcm_array_basic():
assert lcm_array([2, 7, 3]) == 42
assert lcm_array([6, 8]) == 24
assert lcm_array([3, 5, 7]) == 105
def test_lcm_array_with_zero():
assert lcm_array([0, 6, 9]) == 18
assert lcm_array([0, 0, 0, 9]) == 9
assert lcm_array([0]) == 1 # Onl... | [
{
"docstring": null,
"function_declaration": "def lcm(x, y):",
"function_name": "lcm",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def lcm_array(arr):",
"function_name": "lcm_array",
"parameter_list": "(arr)"
}
] | [
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\nfrom math import gcd\n\ndef lcm(x: int, y: int) -> int:\n return x * y // gcd(x, y)\n\ndef lcm_array(arr: List[int]) -> int:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00038321",
"row_id": 38321,
"seed_ids": "[166]"
} | 0.677598 | Data_Structure_38321 | I | [
"lcm",
"lcm_array"
] | 2 | [
[
"lcm_array",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 11fb9f048d201a640dd7f63e13a31d6da4326bee | 968b1b223bd63893efb715e8395183f732f7f349 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38340_I | You're given an integer array `arr` which needs to be sorted using a variant of insertion sort that employs binary search to find the correct insertion point efficiently. The overall algorithm should refine the searching step, though the insertion step remains standard. Implement the function `binary_insertion_sort` th... | from typing import List
def search_insert(arr: List[int], val: int, start: int, end: int) -> int:
"""
Uses binary search to find the index at which val should be inserted
in the subarray arr[start:end].
"""
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
s... | from solution import binary_insertion_sort
def test_binary_insertion_sort_general_case():
assert binary_insertion_sort([4, 2, 9, 1, 5]) == [1, 2, 4, 5, 9]
def test_binary_insertion_sort_already_sorted():
assert binary_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_binary_insertion_sort_reverse_s... | [
{
"docstring": "Uses binary search to find the index at which val should be inserted\nin the subarray arr[start:end].",
"function_declaration": "def search_insert(arr, val, start, end):",
"function_name": "search_insert",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "Sorts th... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef binary_search(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Helper function to perform binary search... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038340",
"row_id": 38340,
"seed_ids": "[199]"
} | 0.605641 | Data_Structure_38340 | I | [
"search_insert",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 68a0ce773b0291bc4d057b41f04d38b8642a054d | e9a9027108d4ce786f0d609b54737a28d0e9730f | |||
v1.0 | instruct | Data_Structure | Data_Structure_38364_I | ### Question: Implement a Hybrid Quick Sort
Your task is to implement a Hybrid Quick Sort algorithm that uses the standard quick sort algorithm but switches to insertion sort when the size of the subarray is below a certain threshold. This hybrid approach helps to optimize the sorting of smaller subarrays, leveraging ... | from typing import List
def insertion_sort(arr: List[int], left: int, right: int) -> None:
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def partition(arr: List[int],... | def test_sort_array_standard_case():
assert sort_array([3, 6, 2, 8, 7, 1]) == [1, 2, 3, 6, 7, 8]
def test_sort_array_already_sorted():
assert sort_array([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_sort_array_reverse_sorted():
assert sort_array([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_sort_array_sing... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"paramet... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr, low, high):\n \"\"\"\n Sorts the array from index low to high using insertion sort.\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038364",
"row_id": 38364,
"seed_ids": "[25]"
} | 0.56433 | Data_Structure_38364 | I | [
"insertion_sort",
"partition",
"hybrid_quick_sort",
"sort_array"
] | 4 | [
[
"hybrid_quick_sort",
"insertion_sort"
],
[
"hybrid_quick_sort",
"partition"
],
[
"sort_array",
"hybrid_quick_sort"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 586a546cfad321fe6180e5967990d50c52140b13 | c742096526aeed4c066815763cc8f6f51caf0c13 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38406_I | #### Problem Statement
You are required to design a system that can handle arithmetic operations involving the greatest common divisor (GCD) and least common multiple (LCM). Additionally, you must devise a utility to count the trailing zeros in a binary representation of a number. This assessment covers different impl... | def gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor of two integers using Euclid's algorithm.
"""
while b:
a, b = b, a % b
return a
def gcd_bit(a: int, b: int) -> int:
"""
Computes the greatest common divisor of two non-negative integers using bitwise operations... | from solution import gcd, gcd_bit, lcm, trailing_zero
def test_gcd():
assert gcd(48, 18) == 6
assert gcd(100, 25) == 25
assert gcd(7, 3) == 1
assert gcd(12, 15) == 3
assert gcd(1, 1) == 1
def test_gcd_bit():
assert gcd_bit(48, 18) == 6
assert gcd_bit(100, 25) == 25
assert gcd_bit(7, 3)... | [
{
"docstring": "Computes the greatest common divisor of two integers using Euclid's algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the greatest common divisor of two non-negative integers using bitwise ope... | [
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 gcd(a: int, b: int) -> int:\n \"\"\"\n Computes the greatest common divisor of two integers using Euclid's algorithm.\n \"\"\"\n while b:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00038406",
"row_id": 38406,
"seed_ids": "[166]"
} | 0.597546 | Data_Structure_38406 | I | [
"gcd",
"gcd_bit",
"lcm",
"trailing_zero"
] | 4 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2b0907ad0fc443ae31a294eaa16ebfb679e84609 | 7395d0c8d337d42bd706aa5df3f99338c93c0a8c | |||
v1.0 | instruct | Data_Structure | Data_Structure_38435_I | You are tasked with implementing a function to compute the least common multiple (LCM) and greatest common divisor (GCD) of two integers using both traditional and bitwise methods. This task will test your understanding of the Euclidean algorithm, bitwise operations, and handling edge cases.
### Function Specification... | def compute_gcd(a: int, b: int) -> int:
"""
Returns the greatest common divisor (GCD) of a and b using the traditional Euclidean method.
"""
if a == 0 or b == 0:
raise ValueError("Input values cannot be zero")
a, b = abs(a), abs(b)
while b:
a, b = b, a % b
... | from solution import compute_gcd, compute_gcd_bitwise, compute_lcm
import pytest
def test_compute_gcd_positive_numbers():
assert compute_gcd(15, 20) == 5
def test_compute_gcd_negative_numbers():
assert compute_gcd(-15, -20) == 5
def test_compute_gcd_mixed_sign_numbers():
assert compute_gcd(-15, 20) == 5
... | [
{
"docstring": "Returns the greatest common divisor (GCD) of a and b using the traditional Euclidean method.",
"function_declaration": "def compute_gcd(a, b):",
"function_name": "compute_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the greatest common divisor (GCD) of a and b ... | [
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: int, b: int) -> int:\n \"\"\"\n Returns the greatest common divisor (GCD) of a and b using the traditional Euclidean method.\n \"\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00038435",
"row_id": 38435,
"seed_ids": "[166]"
} | 0.663283 | Data_Structure_38435 | I | [
"compute_gcd",
"compute_gcd_bitwise",
"compute_lcm"
] | 3 | [
[
"compute_lcm",
"compute_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3ce40a8a9e393b9d6d749f24a96bd2893e60cf29 | 16c33ae41a33cc1e083f08d8d9fe898b3784aac3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38451_I | ### Scenario and Context
Suppose you are tasked with a system where sorting numbers efficiently from a large list is a frequent requirement. Your team has decided to use Radix Sort due to its efficiency in cases where comparisons between numbers are computationally expensive. The integers in the dataset have a bounded ... | def counting_sort(arr, exp):
"""
A function to help with the counting sort of the digits, based on the exponent.
"""
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i]... | from solution import radix_sort
def test_radix_sort_single_element():
assert radix_sort([10]) == [10]
def test_radix_sort_sorted_list():
assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_radix_sort_reverse_sorted():
assert radix_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_radix_sort_d... | [
{
"docstring": "A function to help with the counting sort of the digits, based on the exponent. ",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "The main function to sort an array of non-negative in... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n for i in range(n):\n index = (arr[i] // exp) % 10\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038451",
"row_id": 38451,
"seed_ids": "[15]"
} | 0.549222 | Data_Structure_38451 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f4697298711bb2555ebd66d5ad0df6893c656222 | 336f3f7730120d73fc3ae0c596dae5c2098dcdd1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38455_I | ### Description
You have been tasked with implementing a mathematical algorithm to facilitate certain operations on square matrices. Specifically, you must implement a function that performs matrix exponentiation using the method of repeated squaring, leveraging matrix multiplication and identity matrix functions as he... | def multiply(matA, matB):
"""
Multiplies two square matrices matA and matB.
"""
n = len(matA)
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
result[i][j] = sum(matA[i][k] * matB[k][j] for k in range(n))
return result
def identity(n):
"""
... | import pytest
from solution import multiply, identity, matrix_power
def test_multiply():
matA = [
[1, 2],
[3, 4]
]
matB = [
[2, 0],
[1, 2]
]
expected = [
[4, 4],
[10, 8]
]
assert multiply(matA, matB) == expected
def test_identity():
expe... | [
{
"docstring": "Multiplies two square matrices matA and matB.",
"function_declaration": "def multiply(matA, matB):",
"function_name": "multiply",
"parameter_list": "(matA, matB)"
},
{
"docstring": "Returns the identity matrix of size n.",
"function_declaration": "def identity(n):",
"... | [
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 multiply(matA: list, matB: list) -> list:\n \"\"\"\n Multiplies two matrices matA and matB.\n \"\"\"\n n = len(matA)\n result = [[0] * n fo... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00038455",
"row_id": 38455,
"seed_ids": "[340]"
} | 0.522564 | Data_Structure_38455 | I | [
"multiply",
"identity",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity"
],
[
"matrix_power",
"multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ea27f3fb7b7bbe07373dcab9aec8fd5ea5b8ea63 | b775f9c6dd9f9a56862797e44c19bab0b35a1e85 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38493_I | ### Euler's Totient Function Implementation and Usage
Euler's totient function, also known as ϕ(n), is extremely useful in number theory and cryptographic algorithms. Given the significance of this function, your task is to implement the Euler's totient function and use it to solve a specific problem involving an arra... | def euler_totient(n: int) -> int:
"""
Euler's Totient function, also known as ϕ(n), computes the count of integers
up to n that are relatively prime to n.
"""
if n == 1:
return 1
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
... | from solution import euler_totient, sum_of_totients
def test_euler_totient():
assert euler_totient(1) == 1
assert euler_totient(2) == 1
assert euler_totient(3) == 2
assert euler_totient(4) == 2
assert euler_totient(5) == 4
assert euler_totient(10) == 4
assert euler_totient(12) == 4
asse... | [
{
"docstring": "Euler's Totient function, also known as ϕ(n), computes the count of integers\nup to n that are relatively prime to n.",
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": "Given an array of integers, co... | [
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 euler_totient(n):\n \"\"\"\n Computes the Euler's totient function for an integer n.\n \"\"\"\n result = n\n p = 2\n while p * p <= n:\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00038493",
"row_id": 38493,
"seed_ids": "[141]"
} | 0.619138 | Data_Structure_38493 | I | [
"euler_totient",
"sum_of_totients"
] | 2 | [
[
"sum_of_totients",
"euler_totient"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cafc1652732c1cce7635ecc10670532f5f78055f | d5f18a3ae84ff9e8a7a8f9a7718c07cfcc8f7d59 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38549_I | ### Merge Sort Implementation Challenge
**Scenario**:
You are tasked with optimizing a large dataset processing system. Given that stable, consistent sorting is crucial to preserve the integrity of records, you decide to implement the Merge Sort algorithm. The primary requirement is to sort an array of integers.
**... | def merge_sort(arr):
"""
Sorts the array `arr` using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left, right):
"""
... | from solution import merge_sort, merge
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_list():
asse... | [
{
"docstring": "Sorts the array `arr` using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists `left` and `right` into a single sorted list.",
"function_declaratio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array of integers using the Merge Sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n \... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038549",
"row_id": 38549,
"seed_ids": "[12]"
} | 0.636304 | Data_Structure_38549 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | caebe43a68a1ddfd7f91be92079c8e9cf01f7a6e | 1d30d54eda1dae6eae1e41c355ae1fadd7e878c8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38610_I | ### Question: Implement Enhanced Ternary Search
#### Problem Statement:
You are tasked with implementing an enhanced version of the ternary search algorithm. Write a Python function `enhanced_ternary_search` that not only finds the index of a given key in a sorted array but also returns whether the search was efficien... | from typing import List, Tuple
def binary_search(arr: List[int], key: int) -> Tuple[int, int]:
"""
Binary search, returning the index of the key in the array and the number of comparisons made.
"""
left, right = 0, len(arr) - 1
comparisons = 0
while left <= right:
comparisons += 1
... | from solution import enhanced_ternary_search
def test_enhanced_ternary_search_found():
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
key = 5
assert enhanced_ternary_search(arr, key) == (4, False)
def test_enhanced_ternary_search_not_found():
arr = [1, 2, 3, 4, 6, 7, 8, 9, 10]
key = 5
assert enhanc... | [
{
"docstring": "Binary search, returning the index of the key in the array and the number of comparisons made.",
"function_declaration": "def binary_search(arr, key):",
"function_name": "binary_search",
"parameter_list": "(arr, key)"
},
{
"docstring": "Ternary search, returning the index of ... | [
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": "from typing import List, Tuple\n\ndef enhanced_ternary_search(arr: List[int], key: int) -> Tuple[int, bool]:\n def ternary_search(arr, key):\n left,... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00038610",
"row_id": 38610,
"seed_ids": "[193]"
} | 0.576706 | Data_Structure_38610 | I | [
"binary_search",
"ternary_search",
"enhanced_ternary_search"
] | 3 | [
[
"enhanced_ternary_search",
"binary_search"
],
[
"enhanced_ternary_search",
"ternary_search"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 36ca774d4d68ce49b9dd56fc1a90381a71902cf6 | 5faa941b323889c3cb61aa1490729f3976d577c0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38651_I | You are part of a team developing secure communication protocols and have been assigned to implement a Diffie-Hellman key exchange mechanism. To verify the robustness of the implementation, you need to stretch beyond just performing the key exchange. You must ensure that the keys exchanged are indeed shared securely an... | import random
def generate_private_key(p: int) -> int:
"""
Generates a private key in the range [1, p-1].
"""
return random.randint(1, p - 1)
def generate_public_key(private_key: int, a: int, p: int) -> int:
"""
Computes the public key using the private key, primitive root, and prime number.
... | from solution import generate_private_key, generate_public_key, calculate_shared_key, validate_parameters
def test_generate_private_key():
p = 23
for _ in range(100):
key = generate_private_key(p)
assert 1 <= key < p
def test_generate_public_key():
p = 23
a = 5
private_key = 6
... | [
{
"docstring": "Generates a private key in the range [1, p-1].",
"function_declaration": "def generate_private_key(p):",
"function_name": "generate_private_key",
"parameter_list": "(p)"
},
{
"docstring": "Computes the public key using the private key, primitive root, and prime number.",
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_private_key(p: int) -> int:\n \"\"\"\n Generate a private key, which is a random number in the range [1, p-1].\n \"\"\"... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00038651",
"row_id": 38651,
"seed_ids": "[146]"
} | 0.392065 | Data_Structure_38651 | I | [
"generate_private_key",
"generate_public_key",
"calculate_shared_key",
"validate_parameters",
"is_prime",
"gcd"
] | 6 | [
[
"validate_parameters",
"gcd"
],
[
"validate_parameters",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3e30bef02ad02fd67a74d15658607b5dca72e659 | a94f051121456f9497dfa8d975dfae954b7a839b | |||
v1.0 | instruct | Data_Structure | Data_Structure_38755_I | ### Maximum Network Flow: Deep River Crossing
You're working on a network flow problem where you must determine the maximum flow of materials from the upstream source (node 0) to the downstream sink (the last node) over a series of pathways represented in matrix form.
Write a function `maximum_flow_bfs(adjacency_matr... | from typing import List
from collections import deque
def bfs(residual_graph, source, sink, parent):
visited = [False] * len(residual_graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(residual_graph[u]):
... | from solution import maximum_flow_bfs
def test_maximum_flow_example_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow_bfs(graph) == 23
def test... | [
{
"docstring": null,
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(adjacency_matrix):",
"function_name"... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bfs(rGraph: List[List[int]], s: int, t: int, parent: List[int]) -> bool:\n visited = [False] * len(rGraph)\n queue = []\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038755",
"row_id": 38755,
"seed_ids": "[229]"
} | 0.658698 | Data_Structure_38755 | I | [
"bfs",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f5437e4ec32faedc572b104ea6c2c9de57c1c577 | 7a2839821aa4145ca0e0fb16b0d7cc9bde8fc48c | |||
v1.0 | instruct | Data_Structure | Data_Structure_38787_I | ### Heap Sort Algorithm Implementation
**Scenario**: A logistics company needs to sort a list of delivery times to optimize their delivery sequence. To ensure the process is efficient, they have chosen to use heap sort. As part of their software development team, you are tasked with implementing the heap sort algorith... | def max_heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[largest] < 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]
max_heap... | def test_max_heap_sort_optimized():
arr = [4, 10, 3, 5, 1]
sorted_arr = max_heap_sort_optimized(arr.copy())
assert sorted_arr == [1, 3, 4, 5, 10], f"Unexpected result {sorted_arr}"
def test_min_heap_sort_optimized():
arr = [4, 10, 3, 5, 1]
sorted_arr = min_heap_sort_optimized(arr.copy())
assert... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": null,
"function_declaration": "def max_heap_sort_optimized(arr):",
"function_name": "max_heap_sort_optimized",
"parameter_... | [
0,
0,
0,
1,
1,
1,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"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 # Initialize largest as root\n l = 2 * i + 1 # left = 2*i + 1\n r = 2 * i + 2 # right = 2*i + 2\n\n # ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00038787",
"row_id": 38787,
"seed_ids": "[8]"
} | 0.696681 | Data_Structure_38787 | I | [
"max_heapify",
"max_heap_sort_optimized",
"min_heapify",
"min_heap_sort_optimized"
] | 4 | [
[
"max_heap_sort_optimized",
"max_heapify"
],
[
"min_heap_sort_optimized",
"min_heapify"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | a4ede620f6dd5918a7b1c422b210948287ae8cf8 | 3b2a0d9944d7c2a7c3f323078d2305ed23a74a6d | |||
v1.0 | instruct | Data_Structure | Data_Structure_38823_I | Implementation and Extension of Diffie-Hellman Key Exchange
#### Context:
Alice and Bob need to securely exchange keys over a public channel. You are tasked with implementing the Diffie-Hellman key exchange protocol. To ensure a robust solution, you will also implement auxiliary functions used within this protocol, wh... | from sympy import isprime, totient, primitive_root
def prime_check(num):
"""
Determines if num is a prime number.
Args:
num (int): The number to check for primality.
Returns:
bool: True if num is prime, False otherwise.
"""
return isprime(num)
def euler_totient(n):
"""
... | from solution import prime_check, euler_totient, find_order, find_primitive_root, exec_diffie_hellman
def test_prime_check():
assert prime_check(7) == True
assert prime_check(4) == False
assert prime_check(11) == True
assert prime_check(1) == False
def test_euler_totient():
assert euler_totient(1)... | [
{
"docstring": "Determines if num is a prime number.\n\nArgs:\nnum (int): The number to check for primality.\n\nReturns:\nbool: True if num is prime, False otherwise.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring"... | [
0,
0,
1,
0,
0,
1,
0,
0,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "def prime_check(num):\n \"\"\"\n Determines if num is a prime number.\n \"\"\"\n if num <= 1:\n return False\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00038823",
"row_id": 38823,
"seed_ids": "[146]"
} | 0.518469 | Data_Structure_38823 | I | [
"prime_check",
"euler_totient",
"find_order",
"find_primitive_root",
"exec_diffie_hellman"
] | 5 | [
[
"exec_diffie_hellman",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | ca79ad2777937df203c42c4a8be6edc39ee65f23 | 6140eafb4c64f0605901dab5ca022aa5507bda0e | |||
v1.0 | instruct | Data_Structure | Data_Structure_38838_I | ### Prime Sum Problem
#### Scenario:
You are hired to optimize the performance of a cryptographic system which relies on checking the sum of prime numbers from a list. Given a list of integers, you need to implement a function that returns the sum of all prime numbers within the list.
#### Task:
You will implement t... | def is_prime(n):
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def sum_of_primes(numbers):
"""
... | from solution import sum_of_primes
def test_sum_of_primes_basic():
assert sum_of_primes([2, 3, 4, 5, 6, 7, 8, 9, 10]) == 17
def test_sum_of_primes_no_primes():
assert sum_of_primes([1, 4, 6, 8, 10, 12, 14, 16]) == 0
def test_sum_of_primes_mixed_numbers():
assert sum_of_primes([11, 14, 17, 18, 19, 20]) ==... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given a list of integers, return the sum of all prime numbers in the list.\n\n:param numbers: List of integers\n:return: Sum of 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": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038838",
"row_id": 38838,
"seed_ids": "[143]"
} | 0.676841 | Data_Structure_38838 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 062638170e2edf685784d640ac77676285a5e4df | 9e8d3b1beea499bdac9201143b43d4f015efab9e | |||
v1.0 | instruct | Data_Structure | Data_Structure_38843_I | Consider the problem of searching words from a given list in a 2D grid of characters. This task involves implementing an efficient algorithm using both a Trie data structure and a backtracking method. You are provided with a grid (board) and a list of words.
### Goals:
1. Build a Trie data structure from the list of w... | class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
def build_trie(words):
root = TrieNode()
for word in words:
node = root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
... | from solution import find_words
def test_example_case():
board = [
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath","pea","eat","rain"]
assert sorted(find_words(board, words)) == ["eat", "oath"]
def test_single_letter_words():... | [] | [
0,
0,
0,
0,
1,
0,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict\n\nclass TrieNode:\n def __init__(self):\n self.children: Dict[str, TrieNode] = {}\n self.end_of_word = False\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00038843",
"row_id": 38843,
"seed_ids": "[115]"
} | 0.568882 | Data_Structure_38843 | I | [
"build_trie",
"find_words"
] | 2 | [
[
"find_words",
"build_trie"
]
] | 1 | [] | false | [
"TrieNode"
] | true | pytest | true | [] | true | 978df8032e0d741d941f769c81e2756ce68195e5 | 6c15af19b5f5a8b8eb54a45dacad981374d5a7c8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38910_I | ### Context
You have learned various sorting algorithms and their efficiency. Now, your task is to understand the limitations of certain inefficient algorithms by implementing one of the least efficient algorithms known: **Bogo Sort**.
### Task
Write a Python function `optimized_bogo_sort(arr)` that uses the Bogo Sort... | import random
def is_sorted(arr):
"""Helper function to check if a list is sorted."""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def optimized_bogo_sort(arr: list) -> tuple:
"""
Sorts an array using the Bogo Sort algorithm.
Parameter... | from solution import optimized_bogo_sort
def test_optimized_bogo_sort_empty():
sorted_arr, iterations = optimized_bogo_sort([])
assert sorted_arr == []
assert iterations == 0
def test_optimized_bogo_sort_single_element():
sorted_arr, iterations = optimized_bogo_sort([42])
assert sorted_arr == [42]... | [
{
"docstring": "Helper function to check if a list is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts an array using the Bogo Sort algorithm.\n\nParameters:\narr (list): The list of integers to be sorte... | [
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 \"\"\"\n Helper function to check if the array is sorted\n \n Parameters:\n arr (list): The list of inte... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038910",
"row_id": 38910,
"seed_ids": "[16]"
} | 0.589239 | Data_Structure_38910 | I | [
"is_sorted",
"optimized_bogo_sort"
] | 2 | [
[
"optimized_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3ff18497236e68cc373060edfb671d85abf48693 | 619af140a539e58e710ea2168953d055d1c58e1a | |||
v1.0 | instruct | Data_Structure | Data_Structure_38918_I | You are given an array of `n` real numbers. Your task is to implement a function `bucket_sort(arr: List[float]) -> List[float]`, that takes this array and returns a sorted array using the Bucket Sort algorithm. Here's what you need to consider:
1. **Input**: The function receives a list of `n` real numbers, `arr`, whe... | from typing import List
def insertion_sort(arr: List[float]) -> List[float]:
"""
Helper function to perform Insertion Sort on a list of floats.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -=... | from solution import bucket_sort
def test_bucket_sort_example_1():
arr = [0.897, 0.565, 0.656, 0.123, 0.665, 0.343]
expected = [0.123, 0.343, 0.565, 0.656, 0.665, 0.897]
assert bucket_sort(arr) == expected
def test_bucket_sort_example_2():
arr = [0.5, 0.25, 0.75, 0.1, 0.9]
expected = [0.1, 0.25, 0... | [
{
"docstring": "Helper function to perform Insertion Sort on a list of floats.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Perform Bucket Sort on a list of floats in the range [0, 1).",
"function_de... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[float]) -> List[float]:\n \"\"\"\n Performs insertion sort on the given list and returns the sor... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038918",
"row_id": 38918,
"seed_ids": "[26]"
} | 0.600563 | Data_Structure_38918 | I | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 56261f98b036bfa920062939db5b217c9e0e143f | fe0afeeb73f28da054a7dea0f57ac8c9cf209ac7 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38957_I | ### Matrix Inversion Challenge
#### Problem Description
You are given an n x n matrix and are tasked with computing its inverse, if it exists. Matrix inversion is a fundamental operation in linear algebra with applications ranging from solving linear systems to computer graphics.
#### Input Format
1. A single integer... | from typing import List, Union
def get_determinant(matrix: List[List[float]]) -> float:
"""
Computes the determinant of a matrix recursively.
"""
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]
determ... | from solution import invert_matrix
def test_invert_matrix_3x3():
matrix = [
[2, -1, 0],
[-1, 2, -1],
[0, -1, 2]
]
expected = [
[0.75, 0.5, 0.25],
[0.5, 1.0, 0.5],
[0.25, 0.5, 0.75]
]
assert invert_matrix(matrix) == expected
def test_invert_matrix_non... | [
{
"docstring": "Computes the determinant of a matrix recursively.",
"function_declaration": "def get_determinant(matrix):",
"function_name": "get_determinant",
"parameter_list": "(matrix)"
},
{
"docstring": "Returns the minor matrix after removing the i-th row and j-th column.",
"functio... | [
0,
0,
0,
1,
0,
1,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef invert_matrix(matrix):\n if not array_is_matrix(matrix):\n return -1 # Non-square matrix\n \n n = len(matrix)\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00038957",
"row_id": 38957,
"seed_ids": "[347]"
} | 0.589587 | Data_Structure_38957 | I | [
"get_determinant",
"get_minor",
"transpose",
"invert_matrix"
] | 4 | [
[
"get_determinant",
"get_minor"
],
[
"invert_matrix",
"get_determinant"
],
[
"invert_matrix",
"get_minor"
],
[
"invert_matrix",
"transpose"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 3c18836fed8d316fea7e4b11db7070f6ee5d271f | c500479c6f26067b492b6b272f00f171d7c16597 | |||
v1.0 | instruct | Data_Structure | Data_Structure_38972_I | ### Question: Implement an Efficient Insertion Sort
You are to implement the `insertion_sort` function that sorts a list of integers in non-decreasing order using the binary search method provided.
#### Function Signature
```python
def insertion_sort(arr: List[int]) -> List[int]:
```
#### Description
* Implement the... | from typing import List
def search_insert(arr: List[int], val: int) -> int:
"""
Uses binary search to find the index at which val should be inserted.
Assumes arr is sorted.
"""
low, high = 0, len(arr)
while low < high:
mid = (low + high) // 2
if arr[mid] < val:
low =... | from solution import insertion_sort
def test_insertion_sort_empty():
assert insertion_sort([]) == []
def test_insertion_sort_single_element():
assert insertion_sort([1]) == [1]
def test_insertion_sort_sorted_array():
assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_insertion_sort_rever... | [
{
"docstring": "Uses binary search to find the index at which val should be inserted.\nAssumes arr is sorted.",
"function_declaration": "def search_insert(arr, val):",
"function_name": "search_insert",
"parameter_list": "(arr, val)"
},
{
"docstring": "Sorts a list of integers in non-decreasi... | [
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], target: int) -> int:\n \"\"\"\n Use binary search to find the index at which target... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038972",
"row_id": 38972,
"seed_ids": "[199]"
} | 0.617733 | Data_Structure_38972 | I | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f65da5e01e0a71702f6348ac3a059e9ce8af822e | 19d014b883325431fa60aee5f1ff4a71f70f117e | |||
v1.0 | instruct | Data_Structure | Data_Structure_39000_I | ### Problem: Optimized Matrix Power Calculation
You are given a square matrix `mat` of size `d x d` and an integer `n`. Your task is to compute the matrix raised to the power `n` efficiently.
### Input
- `mat`: A list of lists representing a `d x d` matrix, where `d` is an integer (1 <= d <= 100).
- `n`: An integer (... | def matrix_multiply(A, B):
"""
Multiplies two matrices A and B
"""
d = len(A)
result = [[0] * d for _ in range(d)]
for i in range(d):
for j in range(d):
for k in range(d):
result[i][j] += A[i][k] * B[k][j]
return result
def identity_matrix(d):
"""
... | from solution import matrix_power
def test_matrix_power_identity():
mat = [
[1, 2],
[3, 4]
]
n = 0
expected = [
[1, 0],
[0, 1]
]
assert matrix_power(mat, n) == expected
def test_matrix_power_one():
mat = [
[1, 2],
[3, 4]
]
n = 1
e... | [
{
"docstring": "Multiplies two matrices A and B",
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": "Returns an identity matrix of size d x d",
"function_declaration": "def identity_matrix(d):",
"fun... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_multiply(mat1, mat2):\n \"\"\"\n Helper function to multiply two matrices mat1 and mat2.\n \"\"\"\n d = len(mat1)\n result = [[0] * ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039000",
"row_id": 39000,
"seed_ids": "[340]"
} | 0.552058 | Data_Structure_39000 | I | [
"matrix_multiply",
"identity_matrix",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity_matrix"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0af7650f27393751a295799ece34a1feeb487866 | 12af1242f17fa90099d7273687913b610c80c6be | |||
v1.0 | instruct | Data_Structure | Data_Structure_39037_I | ### Coding Problem: Enhanced Insertion Sort
You are given an unsorted list of integers. Your task is to implement an insertion sort algorithm using the given helper function `search_insert`. The helper function can be used to find the index where an element belongs in the sorted portion of the list.
#### Function Sig... | from typing import List
def search_insert(array, val):
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def insertion_sort(array: List[int]) -> List[int]:
... | from solution import insertion_sort
def test_empty_array():
assert insertion_sort([]) == []
def test_single_element_array():
assert insertion_sort([1]) == [1]
def test_sorted_array():
assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert insertion_sort([5,... | [
{
"docstring": null,
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": null,
"function_declaration": "def insertion_sort(array):",
"function_name": "insertion_sort",
"parameter_list": "(a... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n Helper function to find the appropriate position for a given... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039037",
"row_id": 39037,
"seed_ids": "[199]"
} | 0.611883 | Data_Structure_39037 | I | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ad20dc43a991ec111f1d62ad828edcdb2bc25f34 | 5ffa80f69675f7a8330cc23e552e585d14c00c7d | |||
v1.0 | instruct | Data_Structure | Data_Structure_39042_I | ### RSA Key Generation and Encryption/Decryption
You are asked to implement the RSA encryption algorithm including key generation, encryption, and decryption functions. For this task, you need to demonstrate your understanding of the RSA algorithm by implementing an optimized key generation algorithm and use it to enc... | import random
from sympy import isprime, mod_inverse
from typing import Tuple
def generate_prime_candidate(bit_length: int) -> int:
# Use the random library to generate a random odd integer of bit_length bits
p = random.getrandbits(bit_length)
# Ensure that it is odd by setting the last bit to 1
p |= (... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16)
assert isinstance(n, int) and n > 0
assert isinstance(e, int) and e > 0
assert isinstance(d, int) and d > 0
def test_encrypt_decrypt():
n, e, d = generate_key(16)
message = 42
encrypted_... | [
{
"docstring": null,
"function_declaration": "def generate_prime_candidate(bit_length):",
"function_name": "generate_prime_candidate",
"parameter_list": "(bit_length)"
},
{
"docstring": null,
"function_declaration": "def generate_large_prime(bit_length):",
"function_name": "generate_... | [
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 typing import Tuple\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime_candidate(length):\n \"\"\" Generate an odd integer r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039042",
"row_id": 39042,
"seed_ids": "[154]"
} | 0.668345 | Data_Structure_39042 | I | [
"generate_prime_candidate",
"generate_large_prime",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_large_prime"
],
[
"generate_large_prime",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | be564d31a89d25d3610ec6984ea5adf209fdcf3c | afaf3440d04973c2f614bfc4983056227a2fa05e | |||
v1.0 | instruct | Data_Structure | Data_Structure_39050_I | ### Nearest Neighbor Classification Algorithm Implementation
You are given a dataset of multi-dimensional points, where each point has an associated label. The Nearest Neighbor algorithm aims to classify a new point based on its proximity to points in the dataset. Your task is to implement a `nearest_neighbor` functio... | import math
def distance(x, y):
"""Calculate the Euclidean distance between vectors x and y."""
assert len(x) == len(y), "The vectors must have the same length"
sum_of_squares = 0
for i in range(len(x)):
sum_of_squares += (x[i] - y[i]) ** 2
return math.sqrt(sum_of_squares)
def nearest_neig... | from solution import nearest_neighbor
def test_basic_case():
tSet = {
(1.0, 2.0): 'A',
(3.0, 4.0): 'B',
(1.5, 1.8): 'A',
(-1.0, -2.0): 'C'
}
x = (0.0, 0.0)
assert nearest_neighbor(x, tSet) == 'A'
def test_single_point_case():
tSet = {
(1.0, 1.0): 'A'
}
... | [
{
"docstring": "Calculate the Euclidean distance between vectors x and y.",
"function_declaration": "def distance(x, y):",
"function_name": "distance",
"parameter_list": "(x, y)"
},
{
"docstring": "Find the nearest neighbor of x in the training set tSet.",
"function_declaration": "def ne... | [
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": "import math\n\ndef distance(x, y):\n \"\"\"\n Calculate the Euclidean distance between vectors x and y.\n \"\"\"\n assert len(x) == len(y), \"The ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039050",
"row_id": 39050,
"seed_ids": "[260]"
} | 0.716898 | Data_Structure_39050 | I | [
"distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1255f4cc09c9c2b351d0f81523625f34d932517b | 34c6dd9f446939289276159b065940a4bb025298 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39078_I | ### Problem: Advanced Radix Sort Implementation
#### Context:
Given that radix sort is powerful for sorting large lists of non-negative integers, we need to enhance its functionality to handle integers with leading negative values efficiently.
#### Task:
Write a function `enhanced_radix_sort(arr: List[int]) -> List[... | def enhanced_radix_sort(arr):
"""
Enhanced Radix Sort to handle both positive and negative numbers.
"""
if not arr:
return arr
# Separate positive and negative values
pos_arr = [num for num in arr if num >= 0]
neg_arr = [-num for num in arr if num < 0]
# Perform radix sort on ... | from solution import enhanced_radix_sort
def test_basic_sort():
assert enhanced_radix_sort([170, 45, 75, -90, -802, 24, 2, 66]) == [-802, -90, 2, 24, 45, 66, 75, 170]
def test_empty_list():
assert enhanced_radix_sort([]) == []
def test_all_negative():
assert enhanced_radix_sort([-5, -100, -6, -1, -99... | [
{
"docstring": "Enhanced Radix Sort to handle both positive and negative numbers.",
"function_declaration": "def enhanced_radix_sort(arr):",
"function_name": "enhanced_radix_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Performs radix sort on a list of non-negative integers.",
"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 enhanced_radix_sort(arr: List[int]) -> List[int]:\n # Radix sort helper\n def counting_sort(exp, base=10):\n n = l... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039078",
"row_id": 39078,
"seed_ids": "[15]"
} | 0.61541 | Data_Structure_39078 | I | [
"enhanced_radix_sort",
"radix_sort",
"counting_sort"
] | 3 | [
[
"enhanced_radix_sort",
"radix_sort"
],
[
"radix_sort",
"counting_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f3be4d4691fdc6c99e3d3259ce8d3dc63efd1328 | 66a97fd400db9c2366b825b1fba59216fa663a99 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39084_I | ### Question
You are tasked with enhancing a Markov Chain implementation, specifically modifying the `iterating_markov_chain` function to include a stopping criterion. Instead of running indefinitely, this function should now take an additional parameter, `steps`, that dictates the number of transitions to perform. Af... | import random
def iterating_markov_chain(chain: dict, initial_state: str, steps: int) -> list:
"""
Simulates a Markov chain for a given number of steps starting from an initial state.
Args:
chain (dict): A dictionary representing the Markov chain where key is the current state
a... | from solution import iterating_markov_chain
def test_iterating_single_step():
chain = {'A': {'A': 1.0}}
assert iterating_markov_chain(chain, 'A', 1) == ['A', 'A']
def test_iterating_multiple_steps():
chain = {
'A': {'A': 0.6, 'E': 0.4},
'E': {'A': 0.7, 'E': 0.3}
}
steps = 5
res... | [
{
"docstring": "Simulates a Markov chain for a given number of steps starting from an initial state.\n\nArgs:\nchain (dict): A dictionary representing the Markov chain where key is the current state \n and value is another dictionary representing the next state along with their \n tran... | [
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 iterating_markov_chain(chain: dict, initial_state: str, steps: int) -> list:\n \"\"\"\n This function performs transitions in the g... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039084",
"row_id": 39084,
"seed_ids": "[232]"
} | 0.442795 | Data_Structure_39084 | I | [
"iterating_markov_chain",
"next_state"
] | 2 | [
[
"iterating_markov_chain",
"next_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 55b806a0dd31e2977433efc5794e1afd0b6aac4e | bdb9b197d11856848269b223c43ecd14e785d1cd | |||
v1.0 | instruct | Data_Structure | Data_Structure_39138_I | ### Subtree Check for Binary Trees
**Context:**
You are given two binary trees and need to determine if one tree is a subtree of another. A subtree of a tree `t` is a tree consisting of a node in `t` and all of its descendants in `t`.
**Problem:**
Write a function `is_subtree(big, small)` that takes two binary trees ... | class Node:
def __init__(self, val:int=0, left:'Node'=None, right:'Node'=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big: Node, small: Node) -> bool:
if not small:
return True
if not big:
return False
if are_identical(big, s... | from solution import Node, is_subtree
def test_identical_subtree():
big = Node(3, Node(4, Node(1), Node(2)), Node(5))
small = Node(4, Node(1), Node(2))
assert is_subtree(big, small) == True
def test_not_subtree():
big = Node(3, Node(4, Node(1), Node(2, Node(0))), Node(5))
small = Node(4, Node(1), ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, val:int=0, left:'Node'=None, right:'Node'=None):\n self.val = val\n self.left = left\n self.right = r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039138",
"row_id": 39138,
"seed_ids": "[288]"
} | 0.601031 | Data_Structure_39138 | I | [
"is_subtree",
"are_identical"
] | 2 | [
[
"is_subtree",
"are_identical"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 5fd2554a41852461003d7553ec3aff21ae4d0d70 | 1872aef81a8e39d2958a4ebddfdaea67416773f2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39226_I | ### Assessing Nearest Neighbor Classification in Higher-Dimensional Space
#### Problem Description:
You are given an implementation of a nearest neighbor algorithm that classifies an input vector `x` based on the closest match from a training set `tSet`. Your task is to improve this implementation, ensuring correctnes... | from typing import Tuple, Dict
import math
def euclidean_distance(point1: Tuple[float, ...], point2: Tuple[float, ...]) -> float:
"""
Computes the Euclidean distance between two points in k-dimensional space.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(point1, point2)))
def nearest_neighbor(... | from solution import nearest_neighbor, euclidean_distance
def test_nearest_neighbor_standard_case():
x = (1.0, 2.0, 3.0)
tSet = {
(2.0, 3.0, 4.0): 'A',
(1.0, 2.1, 2.9): 'B',
(0.0, 0.0, 0.0): 'C'
}
assert nearest_neighbor(x, tSet) == 'B'
def test_nearest_neighbor_multiple_neares... | [
{
"docstring": "Computes the Euclidean distance between two points in k-dimensional space.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Finds the nearest neighbor of the inp... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom scipy.spatial import cKDTree\nfrom typing import Tuple, Dict\n\ndef nearest_neighbor(x: Tuple[float], tSet: Dict[Tuple[float], str]) -> str:... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039226",
"row_id": 39226,
"seed_ids": "[260]"
} | 0.594872 | Data_Structure_39226 | I | [
"euclidean_distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4d403092f4f49fd0252deb8631cc0b47576c1d64 | e1a17f60cae2e1a4c757264025b8555c4fce0d69 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39227_I | ### Subtree Check in Binary Trees
Given two binary trees `s` and `t`, determine if `t` is a subtree of `s`. A subtree of a binary tree `s` is any node `n` of `s` and all of its descendants.
#### Input:
- `s`: The root node of a binary tree.
- `t`: The root node of another binary tree to check if it is a subtree of `s... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
if not s:
return False
if is_same_tree(s, t):
return True
return is_subtree(s.left, t) or is_sub... | import pytest
from solution import TreeNode, is_subtree
def test_example_1():
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.left.right = TreeNode(2)
t = TreeNode(4)
t.left = TreeNode(1)
t.right = TreeNode(2)
assert is_subtree(s, t) ... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00039227",
"row_id": 39227,
"seed_ids": "[288]"
} | 0.594765 | Data_Structure_39227 | I | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 9fec48138c3c901bea55185162f3f4c7012050e0 | acccb16902bd8097caa48def2dd1f03a34486f1d | |||
v1.0 | instruct | Data_Structure | Data_Structure_39240_I | ### Context
Radix Sort is an efficient non-comparative integer sorting algorithm that sorts numbers by processing individual digits. This algorithm sorts the elements by iteratively processing digits from the least significant to the most significant digit using a bucket-based approach.
### Task
Implement a modified... | from typing import List, Union
def get_digit(number, digit_index, base=10):
"""
Extracts the digit at the specified index from the right.
"""
return (abs(number) // base ** digit_index) % base
def counting_sort(arr, digit_index, base=10):
"""
Performs a counting sort on the given digit index.
... | from solution import radix_sort_enhanced
def test_empty_list():
assert radix_sort_enhanced([], 2) == []
def test_single_element_list():
assert radix_sort_enhanced([5], 2) == [5]
assert radix_sort_enhanced([5.5], 2) == [5.5]
def test_positive_integers():
assert radix_sort_enhanced([170, 45, 75, 90], 2... | [
{
"docstring": "Extracts the digit at the specified index from the right.",
"function_declaration": "def get_digit(number, digit_index, base=10):",
"function_name": "get_digit",
"parameter_list": "(number, digit_index, base=10)"
},
{
"docstring": "Performs a counting sort on the given digit ... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Union\n\ndef counting_sort(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n \n output = [0] * n\n count = [0] * 1... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039240",
"row_id": 39240,
"seed_ids": "[15]"
} | 0.630443 | Data_Structure_39240 | I | [
"get_digit",
"counting_sort",
"radix_sort",
"handle_negative_numbers",
"handle_floats",
"radix_sort_enhanced"
] | 6 | [
[
"counting_sort",
"get_digit"
],
[
"handle_floats",
"radix_sort"
],
[
"handle_negative_numbers",
"radix_sort"
],
[
"radix_sort",
"counting_sort"
],
[
"radix_sort_enhanced",
"handle_floats"
],
[
"radix_sort_enhanced",
"handle_negative_numbers"
]
... | 6 | [] | false | [] | false | pytest | true | [] | true | 7cdf954e3b8e8dc897b77dc2a968f5eaff083005 | ec07db607c04edc77ec54cc98bd74b0e80be2e78 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39373_I | ### Problem Context:
You have been tasked to help optimize the score processing system for a sports competition platform. The system receives numerous athlete scores which need to be sorted efficiently to generate ranking and statistical analyses. The scores range uniformly between 0 and 100.
### Problem Statement:
Im... | from typing import List
def quicksort(arr):
"""
Quicksort algorithm to sort elements within each bucket.
"""
if len(arr) <= 1:
return arr
else:
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 ... | from solution import optimized_bucket_sort
def test_optimized_bucket_sort_sample_input():
scores = [52.5, 49.3, 66.8, 30.1, 90.4, 89.9, 45.3, 22.2]
expected = [22.2, 30.1, 45.3, 49.3, 52.5, 66.8, 89.9, 90.4]
assert optimized_bucket_sort(scores) == expected
def test_optimized_bucket_sort_empty_list():
... | [
{
"docstring": "Quicksort algorithm to sort elements within each bucket.",
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def optimized_bucket_sort(scores):",
"function_name": "op... | [
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 optimized_bucket_sort(scores: List[float]) -> List[float]:\n \"\"\"\n Sorts a list of scores using bucket sort algorithm.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039373",
"row_id": 39373,
"seed_ids": "[26]"
} | 0.62202 | Data_Structure_39373 | I | [
"quicksort",
"optimized_bucket_sort"
] | 2 | [
[
"optimized_bucket_sort",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ace410a5e8e2cc4a85e9045a97a9c7f81d9f6650 | a9159a1295f82b9e1d18187b6d93a26e437c9ed6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39408_I | You are tasked with implementing an optimized bucket sort algorithm. Given an array of non-negative integers, distribute the elements into a fixed number of buckets, sort each bucket using insertion sort, and then concatenate the buckets to get the final sorted list.
### Function Signature
```python
def bucket_sort(ar... | from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def bucket_sort(arr: List[int]) -> List[int... | from solution import bucket_sort
def test_bucket_sort_basic():
assert bucket_sort([4, 2, 2, 8, 3, 3, 1]) == [1, 2, 2, 3, 3, 4, 8]
assert bucket_sort([5, 1, 4, 2]) == [1, 2, 4, 5]
def test_bucket_sort_empty():
assert bucket_sort([]) == []
def test_bucket_sort_single_element():
assert bucket_sort([5]) ... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def bucket_sort(arr):",
"function_name": "bucket_sort",
"parameter_list": "(arr)"
}
] | [
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 insertion_sort(bucket):\n for i in range(1, len(bucket)):\n key = bucket[i]\n j = i - 1\n while j >= 0 and bucket[j] > key:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00039408",
"row_id": 39408,
"seed_ids": "[26]"
} | 0.546705 | Data_Structure_39408 | I | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 608f048eecc7237eb2a84d0d9df503b02dbd8854 | 8a99ef95637f06f3f24847520003ad1dc85e70de | |||
v1.0 | instruct | Data_Structure | Data_Structure_39417_I | Optimized Shuffle Sort Challenge
Given the highly inefficient nature of bogo sort, it's paramount to leverage randomness efficiently. Design and implement a new sorting algorithm that uses randomness but ensures better performance than bogo sort while maintaining simplicity.
#### Question
Write a Python function `op... | import random
from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def merge_sorted_chunks(chunk... | from solution import optimized_shuffle_sort
def test_sorted_array():
assert optimized_shuffle_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert optimized_shuffle_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_unsorted_array():
assert optimized_shuffle_sort([3, 1, 4, 1, 5... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge_sorted_chunks(chunks):",
"function_name": "merge_sorted_chunks",
"parameter_list": "(ch... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef insertion_sort(arr: List[int]) -> List[int]:\n for i in range(1, len(arr)):\n key = arr[i]\n j ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00039417",
"row_id": 39417,
"seed_ids": "[16]"
} | 0.652996 | Data_Structure_39417 | I | [
"insertion_sort",
"merge_sorted_chunks",
"optimized_shuffle_sort"
] | 3 | [
[
"optimized_shuffle_sort",
"insertion_sort"
],
[
"optimized_shuffle_sort",
"merge_sorted_chunks"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e2a0831404e69512380484e1cf60911c5f5f3d34 | bfcb673bfb2f13b59c11fd9602287f6153b350a9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39454_I | ### Question: Enhanced Prime Detection for Cryptographic Applications
#### Background:
In cryptographic systems, it is vital to use large prime numbers for creating secure keys. While the traditional Rabin-Miller primality test provides good results, there are scenarios where higher confidence and handling for small p... | import random
def is_prime_trial_division(n):
""" Check for small primes using trial division up to 20. """
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
... | from solution import enhanced_is_prime
def test_small_primes():
assert enhanced_is_prime(2) == True
assert enhanced_is_prime(3) == True
assert enhanced_is_prime(5) == True
def test_small_composites():
assert enhanced_is_prime(1) == False
assert enhanced_is_prime(4) == False
assert enhanced_is_... | [
{
"docstring": "Check for small primes using trial division up to 20. ",
"function_declaration": "def is_prime_trial_division(n):",
"function_name": "is_prime_trial_division",
"parameter_list": "(n)"
},
{
"docstring": "Efficiently compute (a^d) % n ",
"function_declaration": "def power_m... | [
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_trial_division(n):\n \"\"\" Check for small primes using trial division up to 20. \"\"\"\n if n <= 1:\n return Fals... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00039454",
"row_id": 39454,
"seed_ids": "[136]"
} | 0.689525 | Data_Structure_39454 | I | [
"is_prime_trial_division",
"power_mod",
"rabin_miller",
"enhanced_is_prime"
] | 4 | [
[
"enhanced_is_prime",
"is_prime_trial_division"
],
[
"enhanced_is_prime",
"rabin_miller"
],
[
"rabin_miller",
"power_mod"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | b7d56538e13d9456dd6a7bb6643311e32e3b9665 | 5446fd305464a800ab8971f669fd097eef18b7d8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39477_I | **Problem Statement**:
Implement an optimized version of Bucket Sort that accounts for non-uniformly distributed data using a more efficient sorting algorithm for the buckets. Specifically, replace Insertion Sort with QuickSort for sorting the contents of each bucket to enhance performance for larger datasets.
**Funct... | from typing import List
def quicksort(arr):
if len(arr) <= 1:
return arr
else:
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 + quicksor... | from solution import bucket_sort
def test_bucket_sort_empty():
assert bucket_sort([]) == []
def test_bucket_sort_single_element():
assert bucket_sort([1]) == [1]
def test_bucket_sort_small_array():
assert bucket_sort([4, 1, 2, 3, 5, 7, 6, 8]) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_bucket_sort_with_zero():... | [
{
"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,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def quicksort(arr):\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < pivot]\n middle = [x for ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00039477",
"row_id": 39477,
"seed_ids": "[26]"
} | 0.49875 | Data_Structure_39477 | I | [
"quicksort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aea92d8cbe6b1484a8c8a41d9b0d3c4b72f2c7c1 | 4ac0ed1be0cf35f1075706f18709511833eb496f | |||
v1.0 | instruct | Data_Structure | Data_Structure_39496_I | ## Problem Statement
You are tasked with implementing an algorithm that multiplies two positive integers without using the '*' operator. The function should utilize only bitwise operations (e.g., AND, OR, XOR, NOT, SHIFT).
### Input
Two positive integers `a` and `b`.
### Output
A single integer which is the product ... | def multiply_bitwise_operator(a: int, b: int) -> int:
"""
Multiplies two positive integers using bitwise operations.
"""
result = 0
while b > 0:
# If the lowest bit of b is set, add current value of a to result
if b & 1:
result = add_bitwise(result, a)
# Double t... | from solution import multiply_bitwise_operator
def test_multiply_small_numbers():
assert multiply_bitwise_operator(3, 4) == 12
assert multiply_bitwise_operator(2, 3) == 6
def test_multiply_with_one():
assert multiply_bitwise_operator(1, 5) == 5
assert multiply_bitwise_operator(5, 1) == 5
def test_mul... | [
{
"docstring": "Multiplies two positive integers using bitwise operations.",
"function_declaration": "def multiply_bitwise_operator(a, b):",
"function_name": "multiply_bitwise_operator",
"parameter_list": "(a, b)"
},
{
"docstring": "Adds two positive integers using bitwise operations.",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply_bitwise_operator(a, b):\n \"\"\"\n Multiply two positive integers using bitwise operations.\n \n Args:\n a (int): The first positi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039496",
"row_id": 39496,
"seed_ids": "[209]"
} | 0.735347 | Data_Structure_39496 | I | [
"multiply_bitwise_operator",
"add_bitwise"
] | 2 | [
[
"multiply_bitwise_operator",
"add_bitwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a62d2ae368c4ef8cc84a9be3a126d35db74c92b5 | 25c8c5c459f3051d0e49560371a36978e21a4268 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39566_I | ### Matrix Exponentiation in an Optimized Iterative Approach
You are provided with functions for matrix multiplication, identity matrix creation, and matrix exponentiation using recursion. Your task is to re-implement the `matrix_exponentiation` function iteratively to avoid potential stack overflow issues with deep r... | def matrix_multiply(A, B):
d = len(A)
result = [[0] * d for _ in range(d)]
for i in range(d):
for j in range(d):
for k in range(d):
result[i][j] += A[i][k] * B[k][j]
return result
def identity_matrix(size):
I = [[0 if i != j else 1 for j in range(size)] for i in ... | from solution import iterative_matrix_exponentiation
def test_example_1():
mat = [[1, 1], [1, 0]]
n = 5
expected = [[8, 5], [5, 3]]
assert iterative_matrix_exponentiation(mat, n) == expected
def test_example_2():
mat = [[2, 0], [0, 2]]
n = 3
expected = [[8, 0], [0, 8]]
assert iterative... | [
{
"docstring": null,
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def identity_matrix(size):",
"function_name": "identity_matrix",
"parameter_list": "(size)"
... | [
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(mat1, mat2):\n \"\"\"Multiplies two matrices mat1 and mat2.\"\"\"\n size = len(mat1)\n result = [[0] * size for _ in range(size)]... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039566",
"row_id": 39566,
"seed_ids": "[340]"
} | 0.524307 | Data_Structure_39566 | I | [
"matrix_multiply",
"identity_matrix",
"iterative_matrix_exponentiation"
] | 3 | [
[
"iterative_matrix_exponentiation",
"identity_matrix"
],
[
"iterative_matrix_exponentiation",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8c94136bbf76f55b5188304d202d65196cfea5e9 | 1c9f75593d4ecdd0edb79c9a9934b1d9fb9700be | |||
v1.0 | instruct | Data_Structure | Data_Structure_39579_I | on Diffie-Hellman Key Exchange
### Objective
Your task is to implement a validated variation of the Diffie-Hellman Key Exchange algorithm. You need to ensure that the inputs, particularly the prime number and its primitive root, are valid and lead to a successful key exchange.
### Function to Implement
Implement the ... | from math import isqrt
def is_prime(p):
"""
Check if a number p is a prime number.
"""
if p <= 1:
return False
if p <= 3:
return True
if p % 2 == 0 or p % 3 == 0:
return False
i = 5
while i * i <= p:
if p % i == 0 or p % (i + 2) == 0:
return F... | from solution import secure_diffie_hellman_key_exchange
def test_prime_and_primitive_root_success():
# 3 is a primitive root of prime number 7
assert secure_diffie_hellman_key_exchange(3, 7) == True
def test_prime_and_invalid_primitive_root():
# 4 is not a primitive root of prime number 7
assert secur... | [
{
"docstring": "Check if a number p is a prime number.",
"function_declaration": "def is_prime(p):",
"function_name": "is_prime",
"parameter_list": "(p)"
},
{
"docstring": "Compute the greatest common divisor of a and b.",
"function_declaration": "def gcd(a, b):",
"function_name": "g... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def prime_check(n):\n if n <= 1:\n return False\n if n in (2, 3):\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00039579",
"row_id": 39579,
"seed_ids": "[146]"
} | 0.473251 | Data_Structure_39579 | I | [
"is_prime",
"gcd",
"power_mod",
"find_primitive_root",
"secure_diffie_hellman_key_exchange"
] | 5 | [
[
"find_primitive_root",
"is_prime"
],
[
"find_primitive_root",
"power_mod"
],
[
"secure_diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"secure_diffie_hellman_key_exchange",
"is_prime"
],
[
"secure_diffie_hellman_key_exchange",
"power_mod"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 175f4012bea88e28887919e7e76737e1773e238b | f92ee518dfa547cc3e6aa8f650c7c2929d926946 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39587_I | You are provided with a simplified nearest neighbor algorithm that finds the vector in a training set closest to a given input vector. The specific task is to extend the functionality of this basic implementation to handle a k-nearest neighbors (k-NN) algorithm, taking the k nearest neighbors into account and returning... | import math
from collections import Counter
from typing import Any, Dict, Tuple
def euclidean_distance(v1: Tuple[float], v2: Tuple[float]) -> float:
"""
Calculate the Euclidean distance between two vectors.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def k_nearest_neighbors(x: Tupl... | from solution import k_nearest_neighbors
def test_knn_basic():
training_set = {
(1, 2): 'ClassA',
(3, 4): 'ClassB',
(1, 1): 'ClassA',
(2, 2): 'ClassC',
(6, 6): 'ClassB'
}
assert k_nearest_neighbors((1, 3), training_set, 3) == 'ClassA'
def test_k_equals_1():
trai... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom collections import Counter\n\ndef euclidean_distance(v1, v2):\n return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))\n\ndef k_near... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039587",
"row_id": 39587,
"seed_ids": "[260]"
} | 0.594563 | Data_Structure_39587 | I | [
"euclidean_distance",
"k_nearest_neighbors"
] | 2 | [
[
"k_nearest_neighbors",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1a36370c6be79cf0f743994998dabc4f4367034b | c25d96aa4f0c955279697a78dd5d131e0102973a | |||
v1.0 | instruct | Data_Structure | Data_Structure_39592_I | You are given two variants of Heap Sort algorithms, one using a Max Heap and the other using a Min Heap. A **Heap Sort algorithm** sorts an array by leveraging the properties of heap data structures.
Your task is to implement the variant of the Heap Sort that uses a **Min Heap** data structure. The implementation shou... | from typing import List
def min_heapify(arr: List[int], n: int, i: int):
smallest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] < arr[smallest]:
smallest = left
if right < n and arr[right] < arr[smallest]:
smallest = right
if smallest != i:
arr[... | from solution import min_heap_sort
def test_empty_array():
assert min_heap_sort([]) == []
def test_single_element_array():
assert min_heap_sort([1]) == [1]
def test_sorted_array():
assert min_heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_unsorted_array():
assert min_heap_sort([3, 1, 5, 2, 4... | [
{
"docstring": null,
"function_declaration": "def min_heapify(arr, n, i):",
"function_name": "min_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": null,
"function_declaration": "def min_heap_sort(arr, simulation=False):",
"function_name": "min_heap_sort",
"parameter_li... | [
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 min_heapify(arr, n, i):\n \"\"\"\n Helper function to maintain the min-heap property.\n \"\"\"\n smallest = i\n left = 2 * i + 1\n right... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00039592",
"row_id": 39592,
"seed_ids": "[8]"
} | 0.679026 | Data_Structure_39592 | I | [
"min_heapify",
"min_heap_sort"
] | 2 | [
[
"min_heap_sort",
"min_heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 46121043b202dda470d001207b769350436f41bd | 7c443b99fc64aa51b175b3a8923d30e08bfd1660 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39601_I | ## Coding Assessment Question
### Context
You have been given two functions that calculate the factorial of a given non-negative integer, `n`. One implementation uses an iterative approach while the other uses a recursive approach. Both functions also support calculating the factorial modulo some integer value to kee... | def compute_factorial(n, mod=None):
"""
This function will calculate factorial of 'n'.
If 'n' > 10,000, use the iterative approach.
If 'mod' is provided, compute n! % mod.
:param n: (int) The non-negative integer for which we want to compute the factorial.
:param mod: (Optional[int]) The mo... | from solution import compute_factorial
def test_factorial_simple():
assert compute_factorial(5) == 120
def test_factorial_with_mod():
assert compute_factorial(5, 3) == 0
def test_factorial_zero():
assert compute_factorial(0) == 1
def test_factorial_large_n():
assert compute_factorial(10001) > 0 # w... | [
{
"docstring": "This function will calculate factorial of 'n'.\nIf 'n' > 10,000, use the iterative approach.\nIf 'mod' is provided, compute n! % mod.\n\n:param n: (int) The non-negative integer for which we want to compute the factorial.\n:param mod: (Optional[int]) The modulus value for the factorial computati... | [
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": "def compute_factorial(n, mod=None):\n \"\"\"\n This function will calculate factorial of 'n'.\n If 'n' > 10,000, use the iterative approach.\n If ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039601",
"row_id": 39601,
"seed_ids": "[139]"
} | 0.694716 | Data_Structure_39601 | I | [
"compute_factorial",
"compute_factorial_iter",
"compute_factorial_recur"
] | 3 | [
[
"compute_factorial",
"compute_factorial_iter"
],
[
"compute_factorial",
"compute_factorial_recur"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ce37d73748bd11a863b15b958a6e59a6c7766a72 | 854d3bf4c2c46b411160598f0f665e15a6ea7d52 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39609_I | ### Pancake Sort Implementation and Analysis
You are required to implement the Pancake Sort algorithm without referencing any code examples. Pancake Sort is inspired by the process of sorting a stack of pancakes using a spatula to flip the stack. The goal is to sort the given array by performing a series of prefix rev... | from typing import List
def flip(arr: List[int], k: int) -> None:
"""
Reverses the order of the first k elements in the array.
"""
arr[:k] = arr[:k][::-1]
def find_max_index(arr: List[int], n: int) -> int:
"""
Finds the index of the maximum element in the first n elements of the array.
"""... | from solution import pancake_sort
def test_pancake_sort_normal_case():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
def test_pancake_sort_with_negative_and_zero():
assert pancake_sort([10, -1, 0, 5, 3]) == [-1, 0, 3, 5, 10]
def test_pancake_sort_single_element():
assert pancake_sort([1]) == [1]
def... | [
{
"docstring": "Reverses the order of the first k elements in the array.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Finds the index of the maximum element in the first n elements of the array.",
"function_declar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def pancake_sort(arr):\n def flip(arr, k):\n \"\"\"Helper function to flip the array up to index k.\"\"\"\n start = 0\n while start < ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039609",
"row_id": 39609,
"seed_ids": "[9]"
} | 0.713908 | Data_Structure_39609 | I | [
"flip",
"find_max_index",
"pancake_sort"
] | 3 | [
[
"pancake_sort",
"find_max_index"
],
[
"pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | bfb15428006ef06ed6588955b3dace16fa93494d | 4fb9762405f69f0abb6dc223814d4d56b7d02851 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39614_I | ### Primitive Root Finder
You are given a number `n`, and your task is to find all primitive roots of this number. In modular arithmetic, a primitive root of a prime `n` is an integer `g` such that every number between 1 and `n-1` can be expressed as `g^k` mod `n` for some integer `k`.
To achieve this, you need to im... | from math import gcd
from typing import List
def euler_totient(n: int) -> int:
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1
if n > 1:
result -= result // n
return result
def ... | from solution import find_order, find_primitive_root
def test_find_order():
assert find_order(3, 10) == 4
assert find_order(7, 10) == 4
assert find_order(2, 8) == -1
assert find_order(2, 9) == 6
assert find_order(1, 7) == 1
def test_find_primitive_root():
assert find_primitive_root(10) == [3, ... | [
{
"docstring": null,
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def find_order(a, n):",
"function_name": "find_order",
"parameter_list": "(a, n)"
},
{
"docstri... | [
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": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef find_order(a, n):\n \"\"\"\n Returns the smallest positive integer k such tha... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039614",
"row_id": 39614,
"seed_ids": "[160]"
} | 0.526554 | Data_Structure_39614 | I | [
"euler_totient",
"find_order",
"find_primitive_root"
] | 3 | [
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"find_order"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fa36666a3a6f8ec5264d8937ef2793d71420f0cf | 692286bfeb3389b04b896af8870f590085023f00 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39636_I | **Scenario**: You are developing a software module for a database system that needs to efficiently sort large datasets of non-negative integers. To achieve this, you decide to implement Radix Sort due to its efficient handling of integer data.
### Task
Implement the function `radix_sort_with_optimization` that takes a... | from typing import List
def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = abs(arr[i]) // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
for i in range(n - 1, -1, -1):
... | from solution import radix_sort_with_optimization
def test_radix_sort_with_mixed_integers():
assert radix_sort_with_optimization([170, -12, 45, 75, -90, 802, 24, 2, 66]) == [-90, -12, 2, 24, 45, 66, 75, 170, 802]
def test_radix_sort_with_only_negatives():
assert radix_sort_with_optimization([-5, -10, -3, -1])... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
},
{
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, base: int = 10) -> List[int]:\n \"\"\"\n A function to do counting sort of arr[] ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00039636",
"row_id": 39636,
"seed_ids": "[15]"
} | 0.591086 | Data_Structure_39636 | I | [
"counting_sort",
"radix_sort",
"radix_sort_with_optimization"
] | 3 | [
[
"radix_sort",
"counting_sort"
],
[
"radix_sort_with_optimization",
"radix_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8c4193b9c6fb74494418c384bab810ae22e626cb | 46c9d84a7969bf3694794ab3d105997b85fe983a | |||
v1.0 | instruct | Data_Structure | Data_Structure_39642_I | ### Radix Sort with Digits in Array
Given an array of non-negative integers, implement an optimized version of the radix sort algorithm. The goal is to sort the array in ascending order based on individual digits, processing from least significant to most significant digits. The given implementation must respect space ... | def counting_sort(arr, exp):
"""
A helper function to perform counting sort based on the digit represented by exp.
"""
n = len(arr)
output = [0] * n # output array that will have sorted arr
count = [0] * 10 # since digits are from 0-9
# Store count of occurrences in count[]
for i in r... | from solution import optimized_radix_sort
def test_sorted_array():
assert optimized_radix_sort([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_reverse_sorted_array():
assert optimized_radix_sort([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_random_array... | [
{
"docstring": "A helper function to perform counting sort based on the digit represented by exp.",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "Function to do Radix Sort",
"function_declaratio... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n \"\"\"\n A function to do counting sort of arr[] according to the digit represented by exp.\n \"\"\"\n n = len(arr)... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00039642",
"row_id": 39642,
"seed_ids": "[15]"
} | 0.631494 | Data_Structure_39642 | I | [
"counting_sort",
"optimized_radix_sort"
] | 2 | [
[
"optimized_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0b57c83143a49d17643bb65172de567a0cd5364e | f49ec9d55311d6475e4b4bb649b5fc0fbd87bc5f | |||
v1.0 | instruct | Data_Structure | Data_Structure_39645_I | ### Assignment: Implement a Secure Diffie-Hellman Key Exchange
**Problem Statement**:
Alice and Bob want to securely share a secret key over an insecure network using the Diffie-Hellman Key Exchange method. You need to implement the key components of this protocol to ensure they exchange keys securely.
**Function S... | import random
def alice_private_key(p):
"""
Returns Alice's private key as a random integer within the range [1, p-1].
"""
return random.randint(1, p-1)
def alice_public_key(a_pr_k, a, p):
"""
Returns Alice's public key.
"""
return pow(a, a_pr_k, p)
def bob_private_key(p):
"""
... | from solution import (
alice_private_key, alice_public_key, bob_private_key, bob_public_key,
alice_shared_key, bob_shared_key, diffie_hellman_key_exchange
)
import pytest
def test_alice_private_key():
p = 23
key = alice_private_key(p)
assert 1 <= key < p
def test_alice_public_key():
p = 23
... | [
{
"docstring": "Returns Alice's private key as a random integer within the range [1, p-1].",
"function_declaration": "def alice_private_key(p):",
"function_name": "alice_private_key",
"parameter_list": "(p)"
},
{
"docstring": "Returns Alice's public key.",
"function_declaration": "def al... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef alice_private_key(p):\n \"\"\"\n Returns Alice's private key as a random integer within the range [1, p-1].\n \"\"\"\n return... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039645",
"row_id": 39645,
"seed_ids": "[146]"
} | 0.381437 | Data_Structure_39645 | I | [
"alice_private_key",
"alice_public_key",
"bob_private_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"diffie_hellman_key_exchange"
] | 7 | [
[
"diffie_hellman_key_exchange",
"alice_private_key"
],
[
"diffie_hellman_key_exchange",
"alice_public_key"
],
[
"diffie_hellman_key_exchange",
"alice_shared_key"
],
[
"diffie_hellman_key_exchange",
"bob_private_key"
],
[
"diffie_hellman_key_exchange",
"bob_pu... | 6 | [] | false | [] | false | pytest | true | [] | true | 8caa19ed526a73f3d4d6509665b3b495564d611c | 9cef9d08dd78d97d33b32dd74592273f18d6f0ff | |||
v1.0 | instruct | Data_Structure | Data_Structure_39685_I | ### Maximum Flow Evaluation
#### Context:
You are managing a water distribution network for a city, represented as a directed graph. Each vertex in the graph represents a junction point, and each directed edge represents a water pipeline with a specific capacity indicating the maximum volume of water that can flow thr... | from collections import deque
def bfs(level_graph, source, sink, level):
"""
Perform BFS to construct level graph and update level of vertices.
"""
q = deque([source])
level[source] = 0
while q:
u = q.popleft()
for v in range(len(level_graph)):
if level[v] < 0 and l... | def test_basic_flow():
vertex_count = 4
capacity_matrix = [
[0, 10, 10, 0],
[0, 0, 5, 10],
[0, 0, 0, 10],
[0, 0, 0, 0]
]
source = 0
sink = 3
assert maximum_flow_dinic(vertex_count, capacity_matrix, source, sink) == 20
def test_no_path():
vertex_count = 4... | [
{
"docstring": "Perform BFS to construct level graph and update level of vertices.",
"function_declaration": "def bfs(level_graph, source, sink, level):",
"function_name": "bfs",
"parameter_list": "(level_graph, source, sink, level)"
},
{
"docstring": "Perform DFS to find the blocking flow i... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs_level_graph(vertex_count, capacity_graph, source, sink, level):\n for i in range(vertex_count):\n level[i] ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039685",
"row_id": 39685,
"seed_ids": "[240]"
} | 0.570684 | Data_Structure_39685 | I | [
"bfs",
"dfs",
"maximum_flow_dinic"
] | 3 | [
[
"maximum_flow_dinic",
"bfs"
],
[
"maximum_flow_dinic",
"dfs"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | c58256775a213bfd8033e8419a073e42511ad52e | ace051b1074dd87c1ca4b4f1d13b6d9744f939c3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39687_I | You are given an array of non-negative numbers. Your task is to implement a sorting function using the Bucket Sort algorithm. The inner sorting of each bucket will be handled using a specific function that you may choose to implement.
### Function Signature
```python
def bucket_sort(arr: List[int]) -> List[int]:
```
... | from typing import List
def insertion_sort(bucket: List[int]) -> List[int]:
"""
Performs insertion sort on a given list (bucket).
"""
for i in range(1, len(bucket)):
key = bucket[i]
j = i - 1
while j >= 0 and key < bucket[j]:
bucket[j + 1] = bucket[j]
j -... | from solution import bucket_sort
def test_bucket_sort_random():
assert bucket_sort([9, 4, 1, 7, 9, 1]) == [1, 1, 4, 7, 9, 9]
def test_bucket_sort_empty():
assert bucket_sort([]) == []
def test_bucket_sort_single_element():
assert bucket_sort([2]) == [2]
def test_bucket_sort_sorted():
assert bucket_s... | [
{
"docstring": "Performs insertion sort on a given list (bucket).",
"function_declaration": "def insertion_sort(bucket):",
"function_name": "insertion_sort",
"parameter_list": "(bucket)"
},
{
"docstring": "Performs bucket sort on a given list.",
"function_declaration": "def bucket_sort(a... | [
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 bucket_sort(arr: List[int]) -> List[int]:\n if len(arr) == 0:\n return []\n\n # Find maximum value to determine bu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039687",
"row_id": 39687,
"seed_ids": "[26]"
} | 0.65166 | Data_Structure_39687 | I | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e8855bc28a0d57745f03ebc88bd9111a121ab97d | 573ac0b7d6e361fda18867f1dbf73651c46d57f2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39694_I | ### Cosine Similarity Function Implementation
**Context**: Cosine similarity is a measure often used in machine learning and information retrieval to determine the similarity between two vectors. This is particularly useful in scenarios such as document comparison, recommendation systems, and clustering algorithms.
*... | import math
def _l2_distance(vec):
"""
Helper function to calculate the L2 norm of a vector.
"""
return math.sqrt(sum(x ** 2 for x in vec))
def cosine_similarity(vec1, vec2):
"""
Calculate cosine similarity between two vectors.
"""
if len(vec1) != len(vec2):
raise ValueError("V... | def test_cosine_similarity_same_vector():
assert math.isclose(cosine_similarity([1, 2, 3], [1, 2, 3]), 1.0)
def test_cosine_similarity_orthogonal_vectors():
assert math.isclose(cosine_similarity([1, 0, 0], [0, 1, 0]), 0.0)
def test_cosine_similarity_example_1():
assert math.isclose(cosine_similarity([1, 1... | [
{
"docstring": "Helper function to calculate the L2 norm of a vector.",
"function_declaration": "def _l2_distance(vec):",
"function_name": "_l2_distance",
"parameter_list": "(vec)"
},
{
"docstring": "Calculate cosine similarity between two vectors.",
"function_declaration": "def cosine_s... | [
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 _l2_norm_squared(vec):\n \"\"\"\n Helper function to calculate the L2 norm squared of a vector.\n \"\"\"\n return sum(x ** 2 fo... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00039694",
"row_id": 39694,
"seed_ids": "[149]"
} | 0.600439 | Data_Structure_39694 | I | [
"_l2_distance",
"cosine_similarity"
] | 2 | [
[
"cosine_similarity",
"_l2_distance"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 185cc32e54cd76bf4cf7c9fadc4d69cc1bca58c3 | efb4a0545691792fe999692b5a4ce7c407cbaf20 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39711_I | ### Prime Number Verification and Sum Calculations
#### Problem Statement
Given the provided `prime_check(n)` function, implement a new function `prime_sum(limit)` that calculates the sum of all prime numbers less than or equal to a given integer `limit`. You will then extend `prime_sum(limit)` to another function `p... | def prime_check(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def prime_sum(limit):
"""
Returns t... | from solution import prime_sum, prime_subsequence_sum
def test_prime_sum():
assert prime_sum(10) == 17
assert prime_sum(1) == 0
assert prime_sum(2) == 2
assert prime_sum(100) == 1060
assert prime_sum(17) == 58
def test_prime_subsequence_sum():
assert prime_subsequence_sum([3, 4, 7, 10, 11]) ==... | [
{
"docstring": null,
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers less than or equal to limit.",
"function_declaration": "def prime_sum(limit):",
"function_name": "prime_... | [
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 prime_check(n):\n \"\"\"\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039711",
"row_id": 39711,
"seed_ids": "[143]"
} | 0.684503 | Data_Structure_39711 | I | [
"prime_check",
"prime_sum",
"prime_subsequence_sum"
] | 3 | [
[
"prime_subsequence_sum",
"prime_check"
],
[
"prime_sum",
"prime_check"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | efb3a0c26456a375c2735e2fbee00c3430adacc7 | 0dc1064d0629317204d7cfc8a2d40cd3fcb5ae1a | |||
v1.0 | instruct | Data_Structure | Data_Structure_39719_I | ### Question:
**Problem Statement: Greatest Common Divisor Using Advanced Methods**
Your task is to implement the following functions using the described algorithms and constraints:
1. **gcd_optimized(a: int, b: int) -> int**:
- Calculate the greatest common divisor of `a` and `b` using Euclid's algorithm. Ensure... | def gcd_optimized(a, b):
"""
Returns the greatest common divisor of a and b using Euclid's algorithm.
Raises ValueError for non-integer or zero inputs.
"""
if not isinstance(a, int) or not isinstance(b, int):
raise ValueError("Inputs must be integers.")
a, b = abs(a), abs(b)
... | from solution import gcd_optimized, lcm_optimized, gcd_bitwise
import pytest
def test_gcd_optimized_positive_integers():
assert gcd_optimized(48, 18) == 6
def test_gcd_optimized_negative_integers():
assert gcd_optimized(-48, -18) == 6
def test_gcd_optimized_non_integers():
with pytest.raises(ValueError):... | [
{
"docstring": "Returns the greatest common divisor of a and b using Euclid's algorithm.\nRaises ValueError for non-integer or zero inputs.",
"function_declaration": "def gcd_optimized(a, b):",
"function_name": "gcd_optimized",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the least ... | [
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 gcd_optimized(a, b):\n \"\"\"\n Calculate the Greatest Common Divisor (GCD) of a and b using Euclid's algorithm.\n \"\"\"\n if not isinstance(... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00039719",
"row_id": 39719,
"seed_ids": "[166]"
} | 0.717252 | Data_Structure_39719 | I | [
"gcd_optimized",
"lcm_optimized",
"gcd_bitwise"
] | 3 | [
[
"lcm_optimized",
"gcd_optimized"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3d36809caa1a6b170dcfcbb9d2bdbce83fc2a6be | de83b15368e6714dbe6f19acf328cfd2622d23da | |||
v1.0 | instruct | Data_Structure | Data_Structure_39775_I | ### Prime Number Validator with Dynamic Range
You are tasked with implementing an efficient prime number validation function as part of a cryptographic program. The program needs to verify the primality of multiple numbers in a dynamic range efficiently.
**Function Signature**:
```python
def validate_primes(numbers: L... | from typing import List
def is_prime(n: int) -> bool:
"""Helper function to determine if a given number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0... | from solution import validate_primes
def test_validate_primes_basic():
assert validate_primes([1, 2, 3, 4, 5, 15, 17]) == [False, True, True, False, True, False, True]
def test_validate_primes_prime_numbers():
assert validate_primes([2, 3, 5, 7, 11, 13]) == [True, True, True, True, True, True]
def test_valid... | [
{
"docstring": "Helper function to determine if a given number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given a list of integers, return a list of boolean values corresponding\nto the primality of each int... | [
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 prime_check(n: int) -> bool:\n \"\"\"\n Helper function to check if a number is prime.\n \n :param n: Integer to ch... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039775",
"row_id": 39775,
"seed_ids": "[143]"
} | 0.67709 | Data_Structure_39775 | I | [
"is_prime",
"validate_primes"
] | 2 | [
[
"validate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ef5754740373e0289c97670b36b5638140168a8e | 2768c7400d788fdeb6bce519d0b8a9d36bc43bda | |||
v1.0 | instruct | Data_Structure | Data_Structure_39824_I | ### Coding Task: Implement Bitonic Sort Without Size Limitation
#### Scenario
You work for a software company that deals with large amounts of streaming data. You need an efficient sorting algorithm capable of leveraging parallel processing capabilities. As part of this requirement, you are tasked to modify the Bitoni... | from concurrent.futures import ThreadPoolExecutor
def merge_bitonic(arr, low, cnt, direction):
if cnt > 1:
k = cnt // 2
for i in range(low, low + k):
if (direction == (arr[i] > arr[i + k])):
arr[i], arr[i + k] = arr[i + k], arr[i]
merge_bitonic(arr, low, k, direc... | from solution import bitonic_sort
def test_bitonic_sort_with_multiple_elements():
arr = [34, 7, 23, 32, 5, 62]
assert bitonic_sort(arr, reverse=False) == [5, 7, 23, 32, 34, 62]
assert bitonic_sort(arr, reverse=True) == [62, 34, 32, 23, 7, 5]
def test_bitonic_sort_with_power_of_two_length():
arr = [4, ... | [
{
"docstring": null,
"function_declaration": "def merge_bitonic(arr, low, cnt, direction):",
"function_name": "merge_bitonic",
"parameter_list": "(arr, low, cnt, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_sort_recursive(arr, low, cnt, direction):",
"func... | [
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 concurrent.futures import ThreadPoolExecutor\n\ndef merge_bitonic(arr, low, cnt, direction):\n if cnt > 1:\n k = cnt // 2\n for i in ran... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00039824",
"row_id": 39824,
"seed_ids": "[17]"
} | 0.603043 | Data_Structure_39824 | I | [
"merge_bitonic",
"bitonic_sort_recursive",
"bitonic_sort"
] | 3 | [
[
"bitonic_sort",
"bitonic_sort_recursive"
],
[
"bitonic_sort_recursive",
"merge_bitonic"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c1bb32e3861861cdebc6936abfb78842999fff15 | 369f64113c478b1dd89e401de42d52d03ab0fbc1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39852_I | ### Factorial Calculation with Additional Functionalities
#### Objective
Implement a function called `factorial_prime_factors` that computes the factorial of a given non-negative integer `n` and also returns the list of prime factors of the factorial result. The function should optionally take a modulus `mod` to retur... | from typing import List, Tuple
from math import factorial
from sympy import primerange
def prime_factors(n: int) -> List[int]:
i = 2
factors = []
while i * i <= n:
while (n % i) == 0:
factors.append(i)
n //= i
i += 1
if n > 1:
factors.append(n)
return... | import pytest
from solution import factorial_prime_factors
def test_factorial_prime_factors_no_mod():
result, factors = factorial_prime_factors(5)
assert result == 120
assert sorted(factors) == [2, 2, 2, 3, 5]
def test_factorial_prime_factors_with_mod():
result, factors = factorial_prime_factors(5, mo... | [
{
"docstring": null,
"function_declaration": "def prime_factors(n):",
"function_name": "prime_factors",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def factorial_prime_factors(n, mod=None):",
"function_name": "factorial_prime_factors",
"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": "from typing import List, Tuple\nfrom math import factorial\nfrom sympy import primerange\n\ndef prime_factors(n: int) -> List[int]:\n i = 2\n factors = ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00039852",
"row_id": 39852,
"seed_ids": "[139]"
} | 0.759678 | Data_Structure_39852 | I | [
"prime_factors",
"factorial_prime_factors"
] | 2 | [
[
"factorial_prime_factors",
"prime_factors"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | d080a5ebd4a08cc14c7606a54b97011365851c8e | 3090cb042b43af23a2be28aa6797a4fb2a94e1c2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39860_I | ## Question: Implement Enhanced Radix Sort
Radix Sort can efficiently sort arrays of non-negative integers. However, the basic implementation doesn’t handle arrays containing negative numbers.
Your task is to modify the existing Radix Sort algorithm to correctly sort arrays that can contain both negative and non-neg... | from typing import List
def counting_sort_for_radix(arr: List[int], exp: int) -> None:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[(index % 10)] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while ... | from solution import enhanced_radix_sort
def test_enhanced_radix_sort_typical_case():
assert enhanced_radix_sort([170, -45, 90, 802, 24, 2, 66, -3]) == [-45, -3, 2, 24, 66, 90, 170, 802]
def test_enhanced_radix_sort_mixed_signs():
assert enhanced_radix_sort([5, -3, 0, -1, -2, 3, 2, 1, -4]) == [-4, -3, -2, -1,... | [
{
"docstring": null,
"function_declaration": "def counting_sort_for_radix(arr, exp):",
"function_name": "counting_sort_for_radix",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"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": "from typing import List\n\ndef counting_sort_for_radix(arr: List[int], exp: int) -> None:\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00039860",
"row_id": 39860,
"seed_ids": "[15]"
} | 0.631991 | Data_Structure_39860 | I | [
"counting_sort_for_radix",
"radix_sort",
"enhanced_radix_sort"
] | 3 | [
[
"enhanced_radix_sort",
"radix_sort"
],
[
"radix_sort",
"counting_sort_for_radix"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6100f87fbb9531a2b8b19471049843d77c3aa0a0 | d90d3149583141898562d94312b8f9879f9fc9d2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39872_I | ### Question: Implement and Analyze an Optimized Sorting Algorithm
#### Context:
You are given a list of integers that need to be sorted in ascending order. Gnome Sort is one approach to accomplish this, but its inefficiency on larger, unsorted datasets can be a hindrance. To remedy this, you must implement and analyz... | import time
def gnome_sort(arr):
"""
Gnome Sort Algorithm.
"""
index = 0
while index < len(arr):
if index == 0 or arr[index] >= arr[index - 1]:
index += 1
else:
arr[index], arr[index - 1] = arr[index - 1], arr[index]
index -= 1
return arr
def... | from solution import gnome_sort, optimized_sort, compare_sorting_performance
def test_gnome_sort_empty():
assert gnome_sort([]) == []
def test_gnome_sort_single_element():
assert gnome_sort([1]) == [1]
def test_gnome_sort_sorted():
assert gnome_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_gnome_sor... | [
{
"docstring": "Gnome Sort Algorithm.",
"function_declaration": "def gnome_sort(arr):",
"function_name": "gnome_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merge Sort Algorithm.",
"function_declaration": "def optimized_sort(arr):",
"function_name": "optimized_sort",
"para... | [
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 time\n\ndef gnome_sort(arr):\n \"\"\"\n Gnome Sort Algorithm.\n \"\"\"\n index = 0\n while index < len(arr):\n if index == 0 or a... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00039872",
"row_id": 39872,
"seed_ids": "[13]"
} | 0.550991 | Data_Structure_39872 | I | [
"gnome_sort",
"optimized_sort",
"merge",
"compare_sorting_performance"
] | 4 | [
[
"compare_sorting_performance",
"gnome_sort"
],
[
"compare_sorting_performance",
"optimized_sort"
],
[
"optimized_sort",
"merge"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 95ba59778ef3995560e4eadeab2186f6604e7a58 | 781dd8a1abae33c00f01eed5e8f854206fe70eb6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39877_I | ### **Coding Assessment Question: RSA Encryption Implementation**
#### Scenario
Imagine you are tasked with securing a communication channel between a client and a server using RSA encryption. Your job is to implement the functions required to generate RSA keys, encrypt, and decrypt messages. The client will use the p... | import random
from sympy import isprime, mod_inverse
def generate_large_prime(bits):
while True:
p = random.getrandbits(bits)
if isprime(p):
return p
def generate_key(k):
"""
Generate RSA keys with a modulus of bit length k.
Parameters:
k (int): Bit length for ... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(512)
assert type(n) == int and type(e) == int and type(d) == int
assert n.bit_length() >= 512
def test_encrypt_decrypt():
n, e, d = generate_key(512)
plaintext = 123456789
encrypted = encry... | [
{
"docstring": null,
"function_declaration": "def generate_large_prime(bits):",
"function_name": "generate_large_prime",
"parameter_list": "(bits)"
},
{
"docstring": "Generate RSA keys with a modulus of bit length k.\n\nParameters:\n k (int): Bit length for the modulus n.\n\nReturns:\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": "import random\nfrom sympy import isprime\nfrom math import gcd\nfrom sympy import mod_inverse\n\ndef generate_large_prime(bits):\n while True:\n num... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039877",
"row_id": 39877,
"seed_ids": "[154]"
} | 0.573307 | Data_Structure_39877 | I | [
"generate_large_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_large_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 0bd17daa4ce056411cb697453c5373aae8da9e9d | e9a103f1477f0b704a38fabb28c77bbddbab6ac4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39890_I | **Scenario:**
You are working on a data management system for a large e-commerce platform where product IDs need to be sorted efficiently. The IDs are large integers, and the sorting must be stable to maintain the initial order of products with identical IDs. Your task is to implement an efficient sorting mechanism usi... | from typing import List
def counting_sort(arr: List[int], exp: int) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i] += count[i - 1]
for i in range(n - 1, -1,... | from solution import efficient_radix_sort
def test_empty_list():
assert efficient_radix_sort([]) == []
def test_single_element_list():
assert efficient_radix_sort([1]) == [1]
def test_sorted_list():
assert efficient_radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list():
asser... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def efficient_radix_sort(arr):",
"function_name": "efficient_radix_sort",
"parameter_list... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n for ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039890",
"row_id": 39890,
"seed_ids": "[15]"
} | 0.51932 | Data_Structure_39890 | I | [
"counting_sort",
"efficient_radix_sort"
] | 2 | [
[
"efficient_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1b854e9638551cd69a7d30e59411c5b2783d63e4 | 38f70c1b60ed171aa4542f202fa4f44c237efcd3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_39906_I | ### Bogo Sort Variation Challenge
**Background**: While Bogo Sort is a highly inefficient sorting algorithm, it serves as an interesting case study in understanding the limitations and behavior of brute-force algorithms. In this task, you will extend the Bogo Sort algorithm to handle additional features to demonstrate... | import random
def is_sorted(arr):
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def enhanced_bogo_sort(arr: list, max_attempts: int) -> tuple:
if not arr:
return (arr, 0)
if all(x == arr[0] for x in arr):
return (arr, 0)
attempts = 0
while not is_sorted(a... | from solution import enhanced_bogo_sort
def test_empty_array():
assert enhanced_bogo_sort([], 10) == ([], 0)
def test_all_identical_elements():
assert enhanced_bogo_sort([1, 1, 1], 10) == ([1, 1, 1], 0)
def test_already_sorted_array():
result = enhanced_bogo_sort([1, 2, 3], 100)
assert result[0] == [... | [
{
"docstring": null,
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def enhanced_bogo_sort(arr, max_attempts):",
"function_name": "enhanced_bogo_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": "import random\n\ndef enhanced_bogo_sort(arr, max_attempts):\n \"\"\"\n Enhanced Bogo Sort algorithm that sorts a list and returns the number of iteratio... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039906",
"row_id": 39906,
"seed_ids": "[16]"
} | 0.58345 | Data_Structure_39906 | I | [
"is_sorted",
"enhanced_bogo_sort"
] | 2 | [
[
"enhanced_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5dc6cb2eea1f043a026f5b1d225c1bf378f0b991 | 75711a33bf2f15b17bcd5d39a3c1dd763eefe33a | |||
v1.0 | instruct | Data_Structure | Data_Structure_39963_I | ### Nearest Neighbor Classifier Implementation
You are tasked with implementing a nearest neighbor classifier. The classifier should be capable of determining the nearest neighbor from a training dataset based on the Euclidean distance metric and returning the label associated with the nearest neighbor. Your solution ... | from typing import Tuple, Dict
import math
def euclidean_distance(v1: Tuple[float, ...], v2: Tuple[float, ...]) -> float:
"""
Calculate the Euclidean distance between two vectors.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def nearest_neighbor_classifier(x: Tuple[float, ...], trai... | from solution import nearest_neighbor_classifier
def test_nearest_neighbor_basic_functionality():
x = (1.0, 2.0)
training_set = {
(0.0, 0.0): 0,
(1.0, 2.5): 1,
(2.0, 2.0): 2
}
assert nearest_neighbor_classifier(x, training_set) == 1
def test_nearest_neighbor_single_element():
... | [
{
"docstring": "Calculate the Euclidean distance between two vectors.",
"function_declaration": "def euclidean_distance(v1, v2):",
"function_name": "euclidean_distance",
"parameter_list": "(v1, v2)"
},
{
"docstring": null,
"function_declaration": "def nearest_neighbor_classifier(x, train... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Tuple, Dict\nimport math\n\ndef euclidean_distance(a: Tuple[float, ...], b: Tuple[float, ...]) -> float:\n return math.sqrt(sum((x - y) ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039963",
"row_id": 39963,
"seed_ids": "[260]"
} | 0.680589 | Data_Structure_39963 | I | [
"euclidean_distance",
"nearest_neighbor_classifier"
] | 2 | [
[
"nearest_neighbor_classifier",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b741f3418fc04909412964348ec421c9930a6903 | e906a9b112171b4aaa057e4d8ae576ec62ed6dde | |||
v1.0 | instruct | Data_Structure | Data_Structure_39970_I | ### Question: Implement an Optimized Matrix Exponentiation Function
You are given a function `matrix_exponentiation` that raises a square matrix to an integer power using repeated squaring, but it suffers in performance for very high powers due to redundant multiplications. Your task is to optimize the matrix exponent... | def multiply(mat1, mat2):
"""
Multiplies two matrices mat1 and mat2.
"""
size = len(mat1)
result = [[0] * size for _ in range(size)]
for i in range(size):
for j in range(size):
for k in range(size):
result[i][j] += mat1[i][k] * mat2[k][j]
return ... | from solution import optimized_matrix_exponentiation
def test_simple_case():
mat = [
[1, 2],
[3, 4]
]
n = 3
assert optimized_matrix_exponentiation(mat, n) == [
[37, 54],
[81, 118]
]
def test_identity_case():
mat = [
[2, 0],
[0, 2]
]
n = 0... | [
{
"docstring": "Multiplies two matrices mat1 and mat2.",
"function_declaration": "def multiply(mat1, mat2):",
"function_name": "multiply",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": "Returns an identity matrix of given size.",
"function_declaration": "def identity(size):",
"f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply(mat1, mat2):\n \"\"\"\n Multiplies two matrices mat1 and mat2.\n \"\"\"\n size = len(mat1)\n result = [[0] * size for _ in range(s... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00039970",
"row_id": 39970,
"seed_ids": "[340]"
} | 0.493794 | Data_Structure_39970 | I | [
"multiply",
"identity",
"optimized_matrix_exponentiation"
] | 3 | [
[
"optimized_matrix_exponentiation",
"identity"
],
[
"optimized_matrix_exponentiation",
"multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6d34324ea25463175babd25c5244d3bf3a3e7762 | 3a1218f7de2da14e4339f00a09660deb3370dba0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_40014_I | ### Question: Efficient GCD and LCM Computations
#### Problem Statement
You are given two non-negative integers, `x` and `y`. Your task is to implement two functions:
1. `efficient_gcd(x, y)` which computes the greatest common divisor (GCD) using:
- Bitwise operations for performance efficiency.
- Handling comm... | def efficient_gcd(x, y):
"""
Returns the greatest common divisor (GCD) of x and y using the binary GCD algorithm.
"""
if x == 0:
return y
if y == 0:
return x
# From here on, x and y are guaranteed to be non-zero
shift = 0
while ((x | y) & 1) == 0:
x >>= 1
... | from solution import efficient_gcd, smallest_lcm
def test_efficient_gcd_both_non_zero():
assert efficient_gcd(40, 100) == 20
assert efficient_gcd(18, 24) == 6
assert efficient_gcd(13, 29) == 1
assert efficient_gcd(270, 192) == 6
def test_efficient_gcd_one_zero():
assert efficient_gcd(0, 5) == 5
... | [
{
"docstring": "Returns the greatest common divisor (GCD) of x and y using the binary GCD algorithm.",
"function_declaration": "def efficient_gcd(x, y):",
"function_name": "efficient_gcd",
"parameter_list": "(x, y)"
},
{
"docstring": "Returns the least common multiple (LCM) of x and y using ... | [
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 efficient_gcd(x, y):\n \"\"\"\n Compute the greatest common divisor (GCD) of two non-negative integers x and y using bitwise operations.\n \"\"\"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040014",
"row_id": 40014,
"seed_ids": "[166]"
} | 0.667396 | Data_Structure_40014 | I | [
"efficient_gcd",
"smallest_lcm"
] | 2 | [
[
"smallest_lcm",
"efficient_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e7ab6bac1cd43acf2dc5626d9d599c277f9e26f2 | 3a1a111ef033e390329efa50d5bd7e409269c11b | |||
v1.0 | instruct | Data_Structure | Data_Structure_40042_I | #### Context:
You have been provided with functions to duplicate each element in a stack using auxiliary storage structures. Your task is to further manipulate a stack with combinations of these duplication operations and apply additional constraints.
#### Problem Statement:
You need to write a function `combine_stutt... | def first_stutter(stack):
"""
This function takes a stack and duplicates each element in the stack.
"""
aux = []
while stack:
value = stack.pop()
aux.append(value)
aux.append(value)
while aux:
stack.append(aux.pop())
def second_stutter(stack):
"""
... | from solution import combine_stutter_operations
def test_empty_stack():
assert combine_stutter_operations([]) == []
def test_single_element_stack():
assert combine_stutter_operations([10]) == [10, 10, 10, 10]
def test_multiple_elements_stack():
assert combine_stutter_operations([3, 7, 1, 14, 9]) == [3, 3... | [
{
"docstring": "This function takes a stack and duplicates each element in the stack.",
"function_declaration": "def first_stutter(stack):",
"function_name": "first_stutter",
"parameter_list": "(stack)"
},
{
"docstring": "This function takes a stack and duplicates each element in the stack."... | [
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 first_stutter(stack):\n \"\"\"\n Given a stack (represented as a list), replace each element with two copies of itself, maintaining the original ord... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040042",
"row_id": 40042,
"seed_ids": "[169]"
} | 0.505947 | Data_Structure_40042 | I | [
"first_stutter",
"second_stutter",
"combine_stutter_operations"
] | 3 | [
[
"combine_stutter_operations",
"first_stutter"
],
[
"combine_stutter_operations",
"second_stutter"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 078165fcfa781205ab1a1ac6966cd219a0cc1025 | 124221cd9046c92fd9d6af096096340ebbb56986 | |||
v1.0 | instruct | Data_Structure | Data_Structure_40067_I | #### Scenario
A local bookstore needs to sort their inventory of books based on the ascending order of book IDs to streamline the search process. They have implemented a basic version of Merge Sort but realized their inventory size can be quite large, leading to high space usage. Your task is to implement an improved v... | def merge_sort_optimized(book_ids):
"""
Sorts a list of book IDs in ascending order using an optimized version of merge sort
that minimizes additional space complexity.
"""
if len(book_ids) <= 1:
return book_ids
temp_array = [0] * len(book_ids)
_merge_sort(book_ids, temp_array, ... | from solution import merge_sort_optimized
def test_merge_sort_optimized_basic():
assert merge_sort_optimized([101, 25, 82, 5, 210, 107]) == [5, 25, 82, 101, 107, 210]
def test_merge_sort_optimized_sorted():
assert merge_sort_optimized([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_optimized_reverse(... | [
{
"docstring": "Sorts a list of book IDs in ascending order using an optimized version of merge sort\nthat minimizes additional space complexity.",
"function_declaration": "def merge_sort_optimized(book_ids):",
"function_name": "merge_sort_optimized",
"parameter_list": "(book_ids)"
},
{
"doc... | [
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_optimized(book_ids):\n \"\"\"\n Sorts the provided list of book IDs in ascending order using an optimized version of Merge Sort.\n \"\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040067",
"row_id": 40067,
"seed_ids": "[12]"
} | 0.541006 | Data_Structure_40067 | I | [
"merge_sort_optimized",
"_merge_sort",
"_merge"
] | 3 | [
[
"_merge_sort",
"_merge"
],
[
"merge_sort_optimized",
"_merge_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1cee58b74fa9029238dbad2c8c92109b4554876b | faa26f2e9ca7dbfa735e2fcf48e27b3290023082 | |||
v1.0 | instruct | Data_Structure | Data_Structure_40070_I | ### Coding Challenge: Implementing Optimized Merge Sort
#### Context:
You are tasked with implementing an optimized version of merge sort that reduces the memory overhead usually associated with this algorithm. Traditional merge sort implementations use additional arrays to manage sorting during the merge phase. Your... | def merge_in_place(arr, start, mid, end):
start2 = mid + 1
if arr[mid] <= arr[start2]:
return
while start <= mid and start2 <= end:
if arr[start] <= arr[start2]:
start += 1
else:
value = arr[start2]
index = start2
while index != star... | def test_merge_sort_in_place_single_element():
arr = [1]
merge_sort_in_place(arr, 0, len(arr) - 1)
assert arr == [1]
def test_merge_sort_in_place_already_sorted():
arr = [1, 2, 3, 4, 5]
merge_sort_in_place(arr, 0, len(arr) - 1)
assert arr == [1, 2, 3, 4, 5]
def test_merge_sort_in_place_reverse... | [
{
"docstring": null,
"function_declaration": "def merge_in_place(arr, start, mid, end):",
"function_name": "merge_in_place",
"parameter_list": "(arr, start, mid, end)"
},
{
"docstring": null,
"function_declaration": "def merge_sort_in_place(arr, start, end):",
"function_name": "merge... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_in_place(arr, start, mid, end):\n start2 = mid + 1\n\n # If the direct merge is already sorted\n if arr[mid] <= arr[start2]:\n retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040070",
"row_id": 40070,
"seed_ids": "[12]"
} | 0.657532 | Data_Structure_40070 | I | [
"merge_in_place",
"merge_sort_in_place"
] | 2 | [
[
"merge_sort_in_place",
"merge_in_place"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | d696c2ca605852bcfe3150df30550c4d80b35f98 | ff5e658a4693c7642ea3069e3c6497e521ceb89e | |||
v1.0 | instruct | Data_Structure | Data_Structure_40093_I | You are tasked with implementing a function that computes the GCD of two non-negative integers a and b using an optimized algorithm that combines both the traditional Euclidean algorithm and bitwise operations. Your function should handle common edge cases and potential pitfalls.
You are also required to implement a f... | def optimized_gcd(a: int, b: int) -> int:
"""
Compute the greatest common divisor (GCD) of two non-negative integers a and b
using a combination of the Euclidean algorithm and bitwise operations.
"""
if a == 0:
return b
if b == 0:
return a
# Finding the largest power of ... | from solution import optimized_gcd, optimized_lcm
def test_optimized_gcd_basic():
assert optimized_gcd(48, 18) == 6
def test_optimized_gcd_zero():
assert optimized_gcd(0, 34) == 34
assert optimized_gcd(34, 0) == 34
assert optimized_gcd(0, 0) == 0
def test_optimized_gcd_prime():
assert optimized_g... | [
{
"docstring": "Compute the greatest common divisor (GCD) of two non-negative integers a and b\nusing a combination of the Euclidean algorithm and bitwise operations.",
"function_declaration": "def optimized_gcd(a, b):",
"function_name": "optimized_gcd",
"parameter_list": "(a, b)"
},
{
"docs... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_gcd(a: int, b: int) -> int:\n \"\"\"\n Optimized GCD function using bitwise operations and the Euclidean algorithm.\n \"\"\"\n if a ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040093",
"row_id": 40093,
"seed_ids": "[166]"
} | 0.699087 | Data_Structure_40093 | I | [
"optimized_gcd",
"optimized_lcm"
] | 2 | [
[
"optimized_lcm",
"optimized_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 83d167b6e58708ff3e32d4b907af898027fd25cf | d5bfea9c5e836fbf8ffb547903cfbf9574be7844 | |||
v1.0 | instruct | Data_Structure | Data_Structure_40099_I | ### Quick Sort Implementation with Optimization
#### Problem Statement
You are required to implement an optimized version of the Quick Sort algorithm. Your task is to handle large arrays efficiently, minimize the risk of the worst-case performance, and improve the average-case performance by implementing a pivot selec... | def median_of_three(arr, low, high):
mid = (low + high) // 2
a, b, c = arr[low], arr[mid], arr[high]
if a > b:
if a < c:
median = low
elif b > c:
median = mid
else:
median = high
else:
if a > c:
median = low
elif b <... | import pytest
from solution import optimized_quick_sort
def test_empty_array():
assert optimized_quick_sort([]) == []
def test_single_element():
assert optimized_quick_sort([1]) == [1]
def test_already_sorted():
assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted():
... | [
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_quick_sort(arr):\n \"\"\"\n This function takes an unsorted list of integers and returns the sorted list\n using an optimized Quick Sor... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040099",
"row_id": 40099,
"seed_ids": "[25]"
} | 0.582278 | Data_Structure_40099 | I | [
"median_of_three",
"partition",
"quick_sort_recursive",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"quick_sort_recursive"
],
[
"partition",
"median_of_three"
],
[
"quick_sort_recursive",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ae2cfbeee1905db834d6470d9fc2d94083cc9601 | 0af6a843eff6ef06161461539aea316c8537e3bb | |||
v1.0 | instruct | Data_Structure | Data_Structure_40157_I | ### Binary Search Tree Implementation
Suppose you are a software developer tasked with creating a library for a binary search tree (BST). You need to implement the core functionalities: inserting a new value, deleting a value, and searching for a value in the tree.
#### Function Signatures
- Insert: `def insert(root:... | class TreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
def insert(root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = inser... | from solution import TreeNode, insert, delete, search
def test_insert_into_empty_tree():
root = None
root = insert(root, 10)
assert root.val == 10
assert root.left is None
assert root.right is None
def test_insert_multiple_values():
values = [20, 10, 30, 5, 15, 25, 35]
root = None
for ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0):\n self.val = val\n self.left = None\n self.right = None\n\ndef insert(root: TreeNode, val... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040157",
"row_id": 40157,
"seed_ids": "[287]"
} | 0.543475 | Data_Structure_40157 | I | [
"insert",
"delete",
"find_min",
"search"
] | 4 | [
[
"delete",
"find_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 278fb67033d01d708f285d8324501b9b0bc91135 | 14d5d7ada6f9e78fbaec9b1cda6431cd9b42aa89 | |||
v1.0 | instruct | Data_Structure | Data_Structure_40160_I | ### Radix Sort Implementation Challenge
You've just learned about a sorting algorithm called Radix Sort, which sorts a list of non-negative integers efficiently by processing individual digits from the least significant to the most significant. The algorithm uses buckets to collect numbers based on their digit values ... | def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] // exp
output[count[in... | from solution import radix_sort
def test_radix_sort_example1():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_example2():
assert radix_sort([3, 3, 3, 3]) == [3, 3, 3, 3]
def test_radix_sort_example3():
assert radix_sort([]) == []
def test_r... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def radix_sort(arr):\n \"\"\"\n Performs radix sort on a given list of non-negative integers.\n \"\"\"\n if not arr:\n return arr\n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040160",
"row_id": 40160,
"seed_ids": "[15]"
} | 0.615286 | Data_Structure_40160 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5324ec6c9463b3d867422bc1474346b68592d21f | eef6a70730325913d56c4983aa23db384c68f579 | |||
v1.0 | instruct | Data_Structure | Data_Structure_40179_I | ### Euler's Totient Function: Optimized Implementation and Applications
#### Context:
Euler's Totient function, ϕ(n), or the phi function, is an important function in number theory that counts integers up to n that are coprime with n. This function is particularly prominent in fields such as cryptography and modular a... | # Optimized Euler's Totient function
def euler_totient(n: int) -> int:
result = n
p = 2
while p ** 2 <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1
if n > 1:
result -= result // n
return result
# Helper fun... | import pytest
from solution import euler_totient, gcd_totient
def test_euler_totient_prime():
assert euler_totient(5) == 4 # 5 is a prime number
def test_euler_totient_non_prime():
assert euler_totient(10) == 4 # totient of 10 is 4
def test_euler_totient_one():
assert euler_totient(1) == 1 # totie... | [
{
"docstring": null,
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
... | [
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 euler_totient(n: int) -> int:\n result = n\n p = 2\n while p * p <= n:\n if n % p == 0:\n while n % p == 0:\n n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00040179",
"row_id": 40179,
"seed_ids": "[141]"
} | 0.628582 | Data_Structure_40179 | I | [
"euler_totient",
"gcd",
"gcd_totient"
] | 3 | [
[
"gcd_totient",
"euler_totient"
],
[
"gcd_totient",
"gcd"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4c0f271b1d447340ff02f895b00bca7f26db806b | 6119870eeafb45b858b9d2d817bd92c7a4e7d2fb | |||
v1.0 | instruct | Data_Structure | Data_Structure_40265_I | Implement an efficient solution for matrix exponentiation utilizing the principles of repeated squaring. Given an integer `k` and an `n x n` matrix `mat`, return the matrix raised to the power `k`, i.e., `mat^k`.
### Function Signature
```python
def matrix_power(mat: list, k: int) -> list:
pass
```
### Input
* `m... | def matrix_multiply(mat1, mat2):
"""
Multiplies two matrices mat1 and mat2.
"""
n = len(mat1)
res = [[0]*n for _ in range(n)]
for i in range(n):
for j in range(n):
res[i][j] = sum(mat1[i][k] * mat2[k][j] for k in range(n))
return res
def identity_matrix(n):
"""
R... | from solution import matrix_power
def test_matrix_power_identity():
mat = [
[2, 0],
[0, 2]
]
k = 0
assert matrix_power(mat, k) == [[1, 0], [0, 1]]
def test_matrix_power_basic():
mat = [
[2, 0],
[0, 2]
]
k = 3
assert matrix_power(mat, k) == [[8, 0], [0, 8... | [
{
"docstring": "Multiplies two matrices mat1 and mat2.",
"function_declaration": "def matrix_multiply(mat1, mat2):",
"function_name": "matrix_multiply",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": "Returns the n x n identity matrix.",
"function_declaration": "def identity_matrix(n... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "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\n for ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040265",
"row_id": 40265,
"seed_ids": "[340]"
} | 0.483635 | Data_Structure_40265 | I | [
"matrix_multiply",
"identity_matrix",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity_matrix"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 806e1a7d7c6f541da92f637c381ca02a3142b00a | 55e69876f3c156e638bb897dbdc813bdc4cb391e | |||
v1.0 | instruct | Data_Structure | Data_Structure_40284_I | ### Coding Challenge: Implement Max-Heap and Min-Heap Sorts
You are required to implement two sorting algorithms: one based on the max-heap and the other on the min-heap structure. Both algorithms should sort an array of integers in ascending order and include a simulation mode that prints the array at each step.
###... | def max_heapify(arr, n, i, simulation):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
... | from solution import max_heap_sort, min_heap_sort
def test_max_heap_sort_regular_case():
assert max_heap_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
def test_min_heap_sort_regular_case():
assert min_heap_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6,... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, simulation):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, simulation)"
},
{
"docstring": null,
"function_declaration": "def max_heap_sort(arr, simulation=False):",
"function_name": "max_heap_... | [
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 max_heapify(arr, n, i, simulation):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n and arr[left] > arr[largest]:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00040284",
"row_id": 40284,
"seed_ids": "[8]"
} | 0.621284 | Data_Structure_40284 | I | [
"max_heapify",
"max_heap_sort",
"min_heapify",
"min_heap_sort"
] | 4 | [
[
"max_heap_sort",
"max_heapify"
],
[
"min_heap_sort",
"min_heapify"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a2d8e8eacf92409cf3270ed309ab3ed5752aa2d3 | 6fc04eabecd834a6218a51e31cf3d4832403a1f4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_40303_I | ### Diffie-Hellman Key Exchange Implementation Challenge
You are tasked with implementing a simplified version of the Diffie-Hellman key exchange algorithm. This exercise will help assess your understanding of modular arithmetic and cryptographic protocols.
#### Problem Statement
Implement a function `diffie_hellman... | import random
def prime_check(num: int) -> bool:
"""
Returns True if `num` is a prime number.
Else returns 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... | import pytest
from solution import prime_check, find_primitive_root, diffie_hellman_key_exchange
def test_prime_check():
assert prime_check(2) == True
assert prime_check(3) == True
assert prime_check(4) == False
assert prime_check(29) == True
def test_find_primitive_root():
assert 2 in find_primit... | [
{
"docstring": "Returns True if `num` is a prime number.\nElse returns False.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"pa... | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef prime_check(num):\n if num < 2:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00040303",
"row_id": 40303,
"seed_ids": "[146]"
} | 0.586953 | Data_Structure_40303 | I | [
"prime_check",
"gcd",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 4 | [
[
"diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"diffie_hellman_key_exchange",
"prime_check"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 93083964d6e0720e0a6109b425024e7221fad0b2 | a9ad4c5df95657ab9c13db1c3e13f48f907e9a3a | |||
v1.0 | instruct | Data_Structure | Data_Structure_40385_I | ### Scenario
You have been tasked by a software company to implement an efficient sorting algorithm suitable for parallel processing environments. The company frequently deals with large datasets that require fast and reliable sorting using their high-performance computing clusters.
### Coding Task
Implement a functio... | from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List
def bitonic_merge(arr, low, cnt, direction):
if cnt > 1:
k = cnt // 2
for i in range(low, low + k):
if (direction == (arr[i] > arr[i + k])):
arr[i], arr[i + k] = arr[i + k], arr[i]
... | from solution import bitonic_sort_parallel
def test_bitonic_sort_parallel_ascending():
assert bitonic_sort_parallel([3, 7, 2, 8, 1, 5, 6, 4], False) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_bitonic_sort_parallel_descending():
assert bitonic_sort_parallel([3, 7, 2, 8, 1, 5, 6, 4], True) == [8, 7, 6, 5, 4, 3, 2, 1]... | [
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, low, cnt, direction):",
"function_name": "bitonic_merge",
"parameter_list": "(arr, low, cnt, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_sort_recursive(arr, low, cnt, direction):",
"func... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom concurrent.futures import ThreadPoolExecutor\nimport math\n\ndef bitonic_merge(arr, low, cnt, direction):\n if cnt > 1:\n ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00040385",
"row_id": 40385,
"seed_ids": "[17]"
} | 0.552103 | Data_Structure_40385 | I | [
"bitonic_merge",
"bitonic_sort_recursive",
"bitonic_sort_parallel"
] | 3 | [
[
"bitonic_sort_parallel",
"bitonic_sort_recursive"
],
[
"bitonic_sort_recursive",
"bitonic_merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | dd398f9e307c35199df9be0b3c5434c514e340b7 | 0dbfc20d6caeb187969e87eec6fa2e7a202dad27 | |||
v1.0 | instruct | Data_Structure | Data_Structure_40430_I | ### Question:
You are given a binary tree and need to perform certain operations on it concerning the depth and height calculations. Implement the following functions:
1. **min_depth**: This function should take a root node of a binary tree and return the minimum depth (the number of nodes along the shortest path from... | from typing import Optional
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def min_depth(root: Optional[TreeNode]) -> int:
if not root:
return 0
queue = deque([(root, 1)... | from solution import TreeNode, min_depth, min_height, print_tree
def test_min_depth():
tree = TreeNode(10)
tree.left = TreeNode(12)
tree.right = TreeNode(15)
tree.left.left = TreeNode(25)
tree.right.left = TreeNode(36)
assert min_depth(tree) == 3
def test_min_depth_empty():
tree = None
... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Optional\nfrom collections import deque\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00040430",
"row_id": 40430,
"seed_ids": "[292]"
} | 0.577242 | Data_Structure_40430 | I | [
"min_depth",
"min_height",
"print_tree"
] | 3 | [
[
"min_height",
"min_depth"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | fdd8125e9d7256ea37dbb02bb949978dae93d3c4 | 1a37f7c04443e06b6fb5fefe3dcdea2fa6a33879 | |||
v1.0 | instruct | Data_Structure | Data_Structure_40576_I | ### Merge Sort with In-Place Merge
You are tasked with implementing an enhanced version of the Merge Sort algorithm. The improvement you need to implement is an in-place merge operation that reduces the auxiliary space usage from O(n) to O(log n), which aligns with the depth of the recursion tree.
#### Task
Implement... | def merge_sort_inplace(arr, left, right):
"""
Sorts the portion of the array from index left to index right (inclusive) using in-place merge sort.
:param arr: List[int] - The list of integers to be sorted.
:param left: int - The starting index of the portion of the array to sort.
:param right: ... | import pytest
from solution import merge_sort_inplace
def test_merge_sort_inplace_sorted_array():
arr = [1, 2, 3, 4, 5]
merge_sort_inplace(arr, 0, len(arr) - 1)
assert arr == [1, 2, 3, 4, 5]
def test_merge_sort_inplace_reverse_sorted_array():
arr = [5, 4, 3, 2, 1]
merge_sort_inplace(arr, 0, len(ar... | [
{
"docstring": "Sorts the portion of the array from index left to index right (inclusive) using in-place merge sort.\n\n:param arr: List[int] - The list of integers to be sorted.\n:param left: int - The starting index of the portion of the array to sort.\n:param right: int - The ending index of the portion of t... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge(arr, left, mid, right):\n start2 = mid + 1\n \n # If the direct merge is already sorted\n if arr[mid] <= arr[start2]:\n return\n \... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00040576",
"row_id": 40576,
"seed_ids": "[12]"
} | 0.628412 | Data_Structure_40576 | I | [
"merge_sort_inplace",
"merge"
] | 2 | [
[
"merge_sort_inplace",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5d767003cc6ecafdc4073d815208b0bad0fe8608 | ed288ba8b5acf3ea942665269fb93cf8adaee7ca | |||
v1.0 | instruct | Data_Structure | Data_Structure_40660_I | ## Heap Sort Enhanced: Multiple Array Segments
### Background
Heap Sort is a powerful sorting algorithm leveraging heaps to order elements. Two forms exist: max-heap sorts in ascending order, and min-heap sorts in descending order. Your task extends upon this foundation, applying heap sort across multiple independent ... | def heapify(arr, n, i, sort_type):
"""
Maintain the heap property for a subtree rooted at index i
assuming the whole array 'arr' is a heap, except for possibly i itself.
"""
largest = smallest = i
left = 2 * i + 1
right = 2 * i + 2
if sort_type == "max":
if left < n and arr[i]... | from solution import sort_segments
def test_sort_segments_max_heap_small():
arr = [3, 5, 1, 2, 4, 6, 9, 8, 7]
segments = [(0, 3), (4, 6)]
sort_type = 'max'
result = sort_segments(arr, segments, sort_type)
assert result == [1, 2, 3, 5, 4, 6, 9, 8, 7]
def test_sort_segments_min_heap_small():
arr... | [
{
"docstring": "Maintain the heap property for a subtree rooted at index i \nassuming the whole array 'arr' is a heap, except for possibly i itself.",
"function_declaration": "def heapify(arr, n, i, sort_type):",
"function_name": "heapify",
"parameter_list": "(arr, n, i, sort_type)"
},
{
"do... | [
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 heapify(arr, n, i, sort_type):\n \"\"\"Helper function to maintain the heap property.\"\"\"\n largest_or_smallest = i\n left = 2 * i + 1\n rig... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040660",
"row_id": 40660,
"seed_ids": "[8]"
} | 0.560836 | Data_Structure_40660 | I | [
"heapify",
"heap_sort_segment",
"sort_segments"
] | 3 | [
[
"heap_sort_segment",
"heapify"
],
[
"sort_segments",
"heap_sort_segment"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6d99972d806fd4eaec836cf16e2bca1a523d8963 | 5959ed575de40b18febbf24ed986fb8151d1354d | |||
v1.0 | instruct | Data_Structure | Data_Structure_40724_I | You are tasked with implementing parts of the Diffie-Hellman key exchange system. Specifically, you need to create functions that perform the following:
1. Prime check for a given number.
2. Finding a primitive root for a given prime number `p`.
3. Completing the Diffie-Hellman key exchange given a prime `p` and its p... | from math import gcd
def is_prime(num: int) -> bool:
"""
Return True if num is a prime number, otherwise return False.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % ... | from solution import is_prime, primitive_root, diffie_hellman_exchange
def test_is_prime():
assert is_prime(2) is True
assert is_prime(3) is True
assert is_prime(4) is False
assert is_prime(29) is True
assert is_prime(30) is False
def test_primitive_root():
assert primitive_root(11) == 2
a... | [
{
"docstring": "Return True if num is a prime number, otherwise return False.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Return a primitive root of the prime number p. If no \nprimitive root exists, return -1.",
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num: int) -> bool:\n \"\"\"\n Return True if num is a prime number, otherwise return False.\n \"\"\"\n if num <= 1:\n return F... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00040724",
"row_id": 40724,
"seed_ids": "[146]"
} | 0.496945 | Data_Structure_40724 | I | [
"is_prime",
"primitive_root",
"diffie_hellman_exchange"
] | 3 | [
[
"diffie_hellman_exchange",
"is_prime"
],
[
"diffie_hellman_exchange",
"primitive_root"
],
[
"primitive_root",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ececf19340066f7ece2d1d08596ba3ad85aa8457 | f3fd68f0cc943bc335b82d13f8ec4a6e1b2db01b | |||
v1.0 | instruct | Data_Structure | Data_Structure_40742_I | ### RSA Encryption Algorithm Implementation and Enhancement
In this task, you will implement and enhance an RSA encryption system.
### Context
For secure communication, you often need a secure way to encrypt messages so that only the intended recipient can decrypt them. RSA is a widely used encryption algorithm that... | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(length):
# Generate random bits and ensure the MSB and LSB are 1
p = random.getrandbits(length)
p |= (1 << length - 1) | 1
return p
def generate_prime_number(length):
p = 4
while not isprime(p):
p = gener... | from solution import generate_key, encrypt, decrypt
def test_key_generation():
n, e, d = generate_key(64, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert n.bit_length() == 64
def test_encryption_decryption():
n, e, d = generate_key(64, seed=42)
... | [
{
"docstring": null,
"function_declaration": "def generate_prime_candidate(length):",
"function_name": "generate_prime_candidate",
"parameter_list": "(length)"
},
{
"docstring": null,
"function_declaration": "def generate_prime_number(length):",
"function_name": "generate_prime_numbe... | [
0,
0,
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 mod_inverse, isprime\n\ndef generate_key(k, seed=None):\n if seed:\n random.seed(seed)\n \n while True:\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040742",
"row_id": 40742,
"seed_ids": "[154]"
} | 0.629715 | Data_Structure_40742 | I | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | e0b0d5b405872ba78e1ce9de2c2fac9e46c4bbe0 | 41756e0782b4254d27713c39f93b2a2de3de16c6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_40775_I | You are given an array of integers that you need to sort using an efficient sorting algorithm. Implement the `merge_sort` function that sorts an array in non-decreasing order using the Merge Sort algorithm. Follow the guidelines and constraints given below.
### Function Signature
```python
def merge_sort(arr: List[int... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array in non-decreasing order using the Merge Sort algorithm.
"""
if len(arr) <= 1:
return arr
# Divide the array into two halves
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_h... | from solution import merge_sort
def test_merge_sort():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
assert merge_sort([5, 1, 1, 2, 0, 0]) == [0, 0, 1, 1, 2, 5]
assert merge_sort([]) == []
assert merge_sort([1]) == [1]
assert merge_sort([2, 1]) == [1, 2]
assert mer... | [
{
"docstring": "Sorts an array in non-decreasing order using the Merge Sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted arrays into one sorted array.",
"function_declaration": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array of integers in non-decreasing order using the Merge So... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040775",
"row_id": 40775,
"seed_ids": "[12]"
} | 0.68888 | Data_Structure_40775 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c082294ef76781c63d65471cd73ea0c59efb8769 | e1a4c52e36f425ab670655ed3ad45950ba4a2dcb | |||
v1.0 | instruct | Data_Structure | Data_Structure_40820_I | ### Scenario: Prime Validation Service
Your task is to implement a function that leverages the prime-checking algorithm discussed above within a more extensive service that validates multiple numbers and returns a summary report.
### Function Specification
You must implement `validate_prime_numbers(numbers: List[int... | from typing import List, Dict, Union
def prime_check(n: int) -> bool:
"""
Check if the number is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i +... | from solution import validate_prime_numbers
def test_validate_prime_numbers():
# Example test case from the prompt
assert validate_prime_numbers([2, 3, 4, 5, 16]) == {
"primes": [2, 3, 5],
"non_primes": [4, 16],
"prime_count": 3,
"non_prime_count": 2
}
def test_validate_pri... | [
{
"docstring": "Check if the number is a prime number.",
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def validate_prime_numbers(numbers):",
"function_name": "validate_prime_num... | [
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, Dict, Union\n\ndef is_prime(n: int) -> bool:\n \"\"\"Check if a number is a prime number.\"\"\"\n if n <= 1:\n return Fa... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00040820",
"row_id": 40820,
"seed_ids": "[143]"
} | 0.642359 | Data_Structure_40820 | I | [
"prime_check",
"validate_prime_numbers"
] | 2 | [
[
"validate_prime_numbers",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4f21bdb1151089fbbb097fadd67b64f813d19f32 | 8f087da32c596c24d2c6b1d966d0e6e66e3697a5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_40825_I | #### Context
You are working on a predictive text model that uses a Markov Chain to suggest the next character in a sequence. The system models transitions between characters based on probabilities derived from historical text data.
Your task is to implement functions to operate this Markov Chain model, enhancing its ... | import random
def choose_next_state(state_map):
"""
Given a dictionary state_map representing possible transitions from the current state with their associated probabilities,
this function returns the chosen next state based on the given probabilities.
"""
states = list(state_map.keys())
probab... | from solution import choose_next_state, validate_transition_map, markov_chain_generator
def test_choose_next_state():
state_map = {'A': 0.5, 'B': 0.5}
next_states = [choose_next_state(state_map) for _ in range(1000)]
assert 'A' in next_states
assert 'B' in next_states
def test_validate_transition_map(... | [
{
"docstring": "Given a dictionary state_map representing possible transitions from the current state with their associated probabilities,\nthis function returns the chosen next state based on the given probabilities.",
"function_declaration": "def choose_next_state(state_map):",
"function_name": "choos... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef choose_next_state(state_map):\n \"\"\"\n Chooses the next state based on the provided transition probabilities.\n \n Args:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040825",
"row_id": 40825,
"seed_ids": "[232]"
} | 0.476811 | Data_Structure_40825 | I | [
"choose_next_state",
"validate_transition_map",
"markov_chain_generator"
] | 3 | [
[
"markov_chain_generator",
"choose_next_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e14836d77699bdb28777428a1837e1d43ddbca68 | e2832443e627d02419dda458e9b9e6a7cc39755b | |||
v1.0 | instruct | Data_Structure | Data_Structure_40870_I | ## Objective:
Implement a function that multiplies two positive integers using only bitwise operations.
## Scenario:
You are working on a low-level programming task where you need to perform multiplication of two positive integers without using any of the traditional arithmetic operators (`*`, `/`, `+`, and `-`). Inst... | def multiply_bitwise(x, y):
"""
Multiplies two positive integers using only bitwise operations.
"""
result = 0
while y > 0:
# If the least significant bit of y is set, add x to the result
if y & 1:
result = add_bitwise(result, x)
# Double x and halve y
x <... | from solution import multiply_bitwise
def test_multiply_simple_cases():
assert multiply_bitwise(3, 4) == 12
assert multiply_bitwise(7, 5) == 35
def test_multiply_with_zero():
assert multiply_bitwise(0, 9) == 0
assert multiply_bitwise(9, 0) == 0
def test_multiply_with_one():
assert multiply_bitwis... | [
{
"docstring": "Multiplies two positive integers using only bitwise operations.",
"function_declaration": "def multiply_bitwise(x, y):",
"function_name": "multiply_bitwise",
"parameter_list": "(x, y)"
},
{
"docstring": "Adds two numbers using bitwise operations.",
"function_declaration":... | [
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 multiply_bitwise(x, y):\n \"\"\"\n Multiplies two positive integers using only bitwise operations.\n \"\"\"\n result = 0\n while y > 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040870",
"row_id": 40870,
"seed_ids": "[209]"
} | 0.661228 | Data_Structure_40870 | I | [
"multiply_bitwise",
"add_bitwise"
] | 2 | [
[
"multiply_bitwise",
"add_bitwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8b3e3594631c84390ea15581547bfa96650ade6a | ff52598147b5996fe838f67e057d1d0c4ae7970f | |||
v1.0 | instruct | Data_Structure | Data_Structure_40903_I | ### Prime Pair Finder
You are working on a cryptography application and need to find pairs of prime numbers that sum up as required pairs.
#### Problem Statement
Write a function:
```python
def find_prime_pairs(n):
"""
Given a number n, return all unique pairs of prime numbers (p1, p2) such that p1 + p2 = n... | from typing import List, Tuple
def is_prime(n: int) -> bool:
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
limit = int(n ** 0.5)
for i in range(3, limit + 1, 2):
if n % i == 0:
r... | from solution import find_prime_pairs
def test_find_prime_pairs_10():
assert find_prime_pairs(10) == [(3, 7), (5, 5)]
def test_find_prime_pairs_26():
assert find_prime_pairs(26) == [(3, 23), (7, 19), (13, 13)]
def test_find_prime_pairs_50():
assert find_prime_pairs(50) == [(3, 47), (7, 43), (13, 37), (19... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given a number n, return all unique pairs of prime numbers (p1, p2) such that p1 + p2 = n.",
"function_declaration": "def find... | [
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 is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00040903",
"row_id": 40903,
"seed_ids": "[143]"
} | 0.791137 | Data_Structure_40903 | I | [
"is_prime",
"find_prime_pairs"
] | 2 | [
[
"find_prime_pairs",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 961526cb4852cd59fdd9ea613c371c55583c3957 | dc07d9fdab8fc804e875ef08f8fc240f62056e44 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.