version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | complete | Data_Structure | Data_Structure_2505_C | from typing import List, Tuple
class Interval:
def __init__(self, start: int, end: int):
self.start = start
self.end = end
def __repr__(self):
return f"Interval ({self.start}, {self.end})"
def find_gaps(intervals: List[Interval]) -> List[Tuple[int, int]]:
"""Identify gaps between ... | from typing import List, Tuple
class Interval:
def __init__(self, start: int, end: int):
self.start = start
self.end = end
def __repr__(self):
return f"Interval ({self.start}, {self.end})"
def merge_intervals(intervals: List[Interval]) -> List[Interval]:
if not intervals:
... | from solution import Interval, find_gaps, expand
def test_find_gaps_no_intervals():
assert find_gaps([]) == []
def test_find_gaps_no_gaps():
intervals = [Interval(1, 5), Interval(5, 10)]
assert find_gaps(intervals) == []
def test_find_gaps_with_gaps():
intervals = [Interval(1, 5), Interval(8, 10), In... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\nclass Interval:\n def __init__(self, start: int, end: int):\n self.start = start\n self.end = end\n\n de... | trial_gpt4o_0 | {
"original_instruction": "You are given a data structure to manage and manipulate intervals of real numbers. Your task is to enhance its functionality by adding a new method `find_gaps` that identifies gaps between a set of potentially overlapping or adjacent intervals, and an `expand` method that expands each inter... | 0.608338 | Data_Structure_2505 | C | [
"merge_intervals",
"find_gaps",
"expand"
] | 3 | [
[
"find_gaps",
"merge_intervals"
]
] | 1 | [] | false | [
"Interval"
] | true | pytest | true | [] | true | 4d555a35f7993a025a63b64bab1ee12d1076547d | 168d4186ea9a667af94ec98268fa94bcecd7e8e1 | |||
v1.0 | complete | Data_Structure | Data_Structure_1264_C | def improved_bitonic_sort(arr: list, reverse: bool = False) -> list:
""" Sort an array using the Bitonic Sort algorithm. Handles arrays that are not of size power of two by padding with a high-value sentinel element until they reach the next power of two.
Args:
arr (list): A list of elements to be ... | import math
def next_power_of_two(n):
"""Return the next power of two greater than or equal to n."""
return 1 << (n - 1).bit_length()
def bitonic_compare_and_swap(arr, i, j, direction):
if (direction == (arr[i] > arr[j])):
arr[i], arr[j] = arr[j], arr[i]
def bitonic_merge(arr, low, cnt, direction... | from solution import improved_bitonic_sort
def test_improved_bitonic_sort_ascending():
input_array = [3, 7, 2, 5, 1]
assert improved_bitonic_sort(input_array, reverse=False) == [1, 2, 3, 5, 7]
def test_improved_bitonic_sort_descending():
input_array = [3, 7, 2, 5, 1]
assert improved_bitonic_sort(input... | [
{
"docstring": "Return the next power of two greater than or equal to n.",
"function_declaration": "def next_power_of_two(n):",
"function_name": "next_power_of_two",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def bitonic_compare_and_swap(arr, i, j, direction... | [
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 math\n\ndef next_power_of_two(x):\n return 1 if x == 0 else 2**(x - 1).bit_length()\n\ndef bitonic_compare_and_swap(arr, i, j, direction):\n if (... | trial_gpt4o_2 | {
"original_instruction": "Implement a function `improved_bitonic_sort` that sorts an array using the Bitonic Sort algorithm. Your function should handle arrays that are not of size power of two by padding them with a high-value sentinel element (e.g., float('inf')) until they reach the next power of two. Additionall... | 0.672124 | Data_Structure_1264 | C | [
"next_power_of_two",
"bitonic_compare_and_swap",
"bitonic_merge",
"bitonic_sort",
"improved_bitonic_sort"
] | 5 | [
[
"bitonic_merge",
"bitonic_compare_and_swap"
],
[
"bitonic_sort",
"bitonic_merge"
],
[
"improved_bitonic_sort",
"bitonic_sort"
],
[
"improved_bitonic_sort",
"next_power_of_two"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 952f136dc049bd47aefab9ea180af6cc93ed3dcb | be918c9b5499a9fe7e1c6da698cca650a216d26b | |||
v1.0 | complete | Data_Structure | Data_Structure_2239_C | from typing import List
def enhanced_interpolation_search(array: List[int], search_key: int) -> int:
"""
:param array: The array to be searched.
:param search_key: The key to be searched in the array.
:returns: Index of search_key in array if found, else -1.
Enhanced Requirements:
- Handles e... | from typing import List
def interpolation_search(array: List[int], search_key: int) -> int:
low = 0
high = len(array) - 1
while low <= high and search_key >= array[low] and search_key <= array[high]:
if low == high:
if array[low] == search_key:
return low
re... | from solution import enhanced_interpolation_search
def test_empty_array():
assert enhanced_interpolation_search([], 10) == -1
def test_array_with_identical_elements():
assert enhanced_interpolation_search([10, 10, 10, 10], 10) == 0
assert enhanced_interpolation_search([10, 10, 10, 10], 5) == -1
def test_... | [
{
"docstring": null,
"function_declaration": "def interpolation_search(array, search_key):",
"function_name": "interpolation_search",
"parameter_list": "(array, search_key)"
},
{
"docstring": null,
"function_declaration": "def binary_search(array, search_key, low, high):",
"function_... | [
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 enhanced_interpolation_search(array: List[int], search_key: int) -> int:\n \"\"\"\n Enhanced Interpolation Search:\n -... | trial_gpt4o_2 | {
"original_instruction": "### Question:\n\nAs a programmer, your task is to enhance the Interpolation Search algorithm to address some of its limitations while maintaining its performance advantages.\n\n#### Requirements:\n1. Improve the function to handle and return appropriate results for all edge cases, specifica... | 0.477963 | Data_Structure_2239 | C | [
"interpolation_search",
"binary_search",
"enhanced_interpolation_search"
] | 3 | [
[
"enhanced_interpolation_search",
"binary_search"
],
[
"enhanced_interpolation_search",
"interpolation_search"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2b620f9b8bbf4cce361785bbeb79b361b0aa44b5 | 73740a1a217fe1b9337732a95d1f860affe82124 | |||
v1.0 | complete | Data_Structure | Data_Structure_1611_C | from typing import List
def radix_sort_hex(arr: List[int]) -> List[int]:
"""
Sort a list of integers using the Radix Sort algorithm with base 16 (hexadecimal).
>>> radix_sort_hex([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66, 75, 90, 170, 802]
>>> radix_sort_hex([15, 255, 1, 0, 1024])
... | from typing import List
def counting_sort_base(arr: List[int], exp: int, base: int) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * base
for i in range(n):
index = (arr[i] // exp) % base
count[index] += 1
for i in range(1, base):
count[i] += count[i - 1]
for... | from solution import radix_sort_hex
def test_radix_sort_hex_basic():
assert radix_sort_hex([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_hex_single_element():
assert radix_sort_hex([15]) == [15]
def test_radix_sort_hex_sorted():
assert radix_sort_hex([1, 2, 3... | [
{
"docstring": null,
"function_declaration": "def counting_sort_base(arr, exp, base):",
"function_name": "counting_sort_base",
"parameter_list": "(arr, exp, base)"
},
{
"docstring": null,
"function_declaration": "def radix_sort_hex(arr):",
"function_name": "radix_sort_hex",
"para... | [
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_hex(arr: List[int], exp: int, base: int) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0] *... | trial_gpt4o_2 | {
"original_instruction": "### Task\n\nYou are required to implement a function that sorts a list of integers using the Radix Sort algorithm with a minor variation: instead of using base 10, you will use base 16 (hexadecimal).\n\n### Function Signature\n```python\ndef radix_sort_hex(arr: List[int]) -> List[int]:\n```... | 0.598455 | Data_Structure_1611 | C | [
"counting_sort_base",
"radix_sort_hex"
] | 2 | [
[
"radix_sort_hex",
"counting_sort_base"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | abc6eaec6dbf87cfce484d8f80440994d3d7795e | e16a52685fc887298223d8a40aa754c94e17e8f2 | |||
v1.0 | complete | Data_Structure | Data_Structure_2249_C | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Given a sorted array and a value, this function returns the index where val
should be inserted to maintain the sort order.
"""
left, right = 0, len(array)
while left < right:
mid = (left + right) // 2
... | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Given a sorted array and a value, this function returns the index where val
should be inserted to maintain the sort order.
"""
left, right = 0, len(array)
while left < right:
mid = (left + right) // 2
... | from solution import sorted_insert
def test_sorted_insert_existing_value():
assert sorted_insert([1, 3, 5, 6], 5) == [1, 3, 5, 5, 6]
def test_sorted_insert_new_value_middle():
assert sorted_insert([1, 3, 5, 6], 2) == [1, 2, 3, 5, 6]
def test_sorted_insert_new_value_end():
assert sorted_insert([1, 3, 5, 6... | [
{
"docstring": "Given a sorted array and a value, this function returns the index where val \nshould be inserted to maintain the sort order.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "Inser... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n Helper function to find the index at which 'val' should be i... | trial_gpt4o_2 | {
"original_instruction": "Implement an Efficient Sorted Insert\nYou are tasked with writing a function `sorted_insert` that takes a sorted list and a value, and returns a new list with the value inserted at the correct position to maintain the sorted order. Use the `search_insert` helper function provided.\n\n#### F... | 0.672929 | Data_Structure_2249 | C | [
"search_insert",
"sorted_insert"
] | 2 | [
[
"sorted_insert",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 791f9afdcce0a58cf0498310a0c7a1d3950226cd | 4d43b6950bcf9261f7893fb23439e6bc5cfea5c2 | |||
v1.0 | complete | Data_Structure | Data_Structure_1255_C | def merge_sort(arr: list) -> list:
"""
Sorts an array of integers using the merge sort algorithm.
Parameters:
arr (list): A list of integers to be sorted.
Returns:
list: A sorted list of integers.
Examples:
>>> merge_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
[1, 1, 2, 3, 3, 4, 5, 5,... | def merge_sort(arr: list) -> list:
"""
Sorts an array of integers using the merge sort algorithm.
Parameters:
arr (list): A list of integers to be sorted.
Returns:
list: A sorted list of integers.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_so... | from solution import merge_sort
def test_sort_empty_list():
assert merge_sort([]) == []
def test_sort_single_element_list():
assert merge_sort([1]) == [1]
def test_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_sort_reverse_sorted_list():
assert merge_sort([5, 4, ... | [
{
"docstring": "Sorts an array of integers using the merge sort algorithm.\n\nParameters:\narr (list): A list of integers to be sorted.\n\nReturns:\nlist: A sorted list of integers.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr: list) -> list:\n \"\"\"\n Sorts an array of integers using the merge sort algorithm.\n\n Parameters:\n arr (list): A list of i... | trial_gpt4o_2 | {
"original_instruction": "You are given an array of integers and need to sort it using the Merge Sort algorithm. Your task is to implement the `merge_sort` function and its helper function `merge`, which will recursively sort the input array.\n\n#### Function Signatures\n\n```python\ndef merge_sort(arr: list) -> lis... | 0.628749 | Data_Structure_1255 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 47541efa739dc2c6f0f0094572bcb61daf30608c | 4fb7778dbc220028d26eb15117b91abe5960c351 | |||
v1.0 | complete | Data_Structure | Data_Structure_1900_C | import math
from collections import Counter
from typing import Tuple, Dict
def distance(x: Tuple[float], y: Tuple[float]) -> float:
""" Calculate the Euclidean distance between two vectors """
assert len(x) == len(y), "The vectors must have the same length"
sum = 0
for i in range(len(x)):
sum +... | import math
from collections import Counter
def distance(x, y):
assert len(x) == len(y), "The vectors must have the same length"
sum = 0
for i in range(len(x)):
sum += (x[i] - y[i]) ** 2
return math.sqrt(sum)
def knn_classifier(x, tSet, k):
assert isinstance(x, tuple) and isinstance(tSet, ... | from solution import knn_classifier
def test_knn_classifier_simple_case():
test_vector = (1.5, 2.5)
training_set = {
(1.0, 2.0): 'A',
(2.0, 3.0): 'B',
(3.0, 4.0): 'A'
}
k = 2
assert knn_classifier(test_vector, training_set, k) == 'A'
def test_knn_classifier_all_same_labels(... | [
{
"docstring": null,
"function_declaration": "def distance(x, y):",
"function_name": "distance",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def knn_classifier(x, tSet, k):",
"function_name": "knn_classifier",
"parameter_list": "(x, tSet, k)"
}
] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom collections import Counter\n\ndef distance(x,y):\n \"\"\"\n Compute the Euclidean distance between two vectors x and y.\n \"\"\"\n ... | trial_gpt4o_1 | {
"original_instruction": "### Question\n\nYou are tasked with implementing the K-Nearest Neighbors (KNN) classification algorithm. KNN is an extension of the nearest neighbor algorithm provided in the code snippets. Instead of returning the closest single neighbor, KNN will return the most common class among the 'k'... | 0.620226 | Data_Structure_1900 | C | [
"distance",
"knn_classifier"
] | 2 | [
[
"knn_classifier",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b51ee557e0036df8b11a0d1ed7b3ba802093e406 | e4a881c2ce6298475fe413e6fdd0c2a9d487d8c2 | |||
v1.0 | complete | Data_Structure | Data_Structure_2748_C | from typing import Tuple
def is_prime(num: int) -> bool:
"""Check if a given number is prime.
>>> is_prime(2) == True
>>> is_prime(4) == False
"""
def modinv(a: int, m: int) -> int:
"""Compute the modular inverse of a under modulus m.
>>> modinv(3, 11) == 4
>>> modinv(10, 17) == 12
"""... | import random
from typing import Tuple
def is_prime(num: int, k: int = 5) -> bool:
"""
Miller-Rabin primality test to check if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0:
return False
# Write (num - 1) as 2^r * d
r,... | from solution import generate_rsa_keys, is_prime, modinv
def test_generate_rsa_keys_valid_range():
n, e, d = generate_rsa_keys(32)
assert n.bit_length() == 32
assert e == 65537
assert 1 < d < (n - 1)
def test_generate_rsa_keys_greater_than_minimum():
n, e, d = generate_rsa_keys(128)
assert n.b... | [
{
"docstring": "Miller-Rabin primality test to check if a number is prime.",
"function_declaration": "def is_prime(num, k=5):",
"function_name": "is_prime",
"parameter_list": "(num, k=5)"
},
{
"docstring": "Generate an odd integer randomly.",
"function_declaration": "def generate_prime_c... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import Tuple\n\ndef is_prime(num: int, k: int = 5) -> bool:\n \"\"\"\n Perform Miller-Rabin primality test to check if a numb... | trial_gpt4o_1 | {
"original_instruction": "Implementing a Robust RSA Key Generator\n\nGiven your understanding of the RSA encryption algorithm, write a Python program to generate RSA keys (`n`, `e`, `d`), and ensure robust handling of edge cases and performance pitfalls.\n\n### Problem Requirements\n* Implement a function `generate_... | 0.632245 | Data_Structure_2748 | C | [
"is_prime",
"generate_prime_candidate",
"generate_prime",
"gcd",
"modinv",
"generate_rsa_keys"
] | 6 | [
[
"generate_prime",
"generate_prime_candidate"
],
[
"generate_prime",
"is_prime"
],
[
"generate_rsa_keys",
"gcd"
],
[
"generate_rsa_keys",
"generate_prime"
],
[
"generate_rsa_keys",
"modinv"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | a3e23b3b49deae54a9af8db9364b39f54d5ebc9f | 5538690d64fbc7fd3e3615e3828b23c04c74aa1b | |||
v1.0 | complete | Data_Structure | Data_Structure_1340_C | def int_to_base(num: int, base: int) -> str:
""" Converts an integer num to a string representation in the specified base.
Args:
num (int): The integer to convert.
base (int): The base to convert to.
Returns:
str: The string representation of num in the specified base.
Raises:
... | def int_to_base(num, base):
"""
Converts an integer num to a string representation in the specified base.
Args:
num (int): The integer to convert.
base (int): The base to convert to.
Returns:
str: The string representation of num in the specified base.
"""
if base < 2 or ba... | def test_int_to_base():
assert int_to_base(5, 2) == '101'
assert int_to_base(-15, 16) == '-F'
assert int_to_base(0, 10) == '0'
assert int_to_base(255, 16) == 'FF'
assert int_to_base(123456789, 36) == '21I3V9'
assert int_to_base(-123456789, 36) == '-21I3V9'
def test_base_to_int():
assert bas... | [
{
"docstring": "Converts an integer num to a string representation in the specified base.\n\nArgs:\nnum (int): The integer to convert.\nbase (int): The base to convert to.\n\nReturns:\nstr: The string representation of num in the specified base.",
"function_declaration": "def int_to_base(num, base):",
"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def int_to_base(num, base):\n \"\"\"\n Converts an integer num (base 10) to a string representation in the specified base.\n Handles bases from 2 to ... | trial_gpt4o_1 | {
"original_instruction": "You are tasked with improving and extending a utility that converts integers between different numeral systems (bases). The utility currently supports base conversions up to base 36 using digits and uppercase letters.\n\n#### Requirements:\n1. **Function 1**: Implement a function `int_to_ba... | 0.79798 | Data_Structure_1340 | C | [
"int_to_base",
"int_to_char",
"base_to_int",
"char_to_int"
] | 4 | [
[
"base_to_int",
"char_to_int"
],
[
"int_to_base",
"int_to_char"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | de97a017e704d9bb3a6f821d46e46c498f0e8985 | b693b56f07153e6733055fe26cd53a6388d722e6 | |||
v1.0 | complete | Data_Structure | Data_Structure_2449_C | def gcd(a, b):
"""
Computes the greatest common divisor of integers a and b using
Euclid's Algorithm.
Arguments:
a -- First integer
b -- Second integer
Returns:
The greatest common divisor of a and b.
Raises:
ValueError if any of a or b are zero or not integers.
>>> gcd(4... | def gcd(a, b):
"""
Computes the greatest common divisor of integers a and b using Euclid's Algorithm.
"""
if not isinstance(a, int) or not isinstance(b, int):
raise ValueError("Both a and b must be integers")
if a == 0 and b == 0:
raise ValueError("Both a and b cannot be zero")
... | from solution import gcd, lcm, gcd_bit
import pytest
def test_gcd():
assert gcd(48, 18) == 6
assert gcd(0, 18) == 18
assert gcd(48, 0) == 48
assert gcd(-48, 18) == 6
assert gcd(48, -18) == 6
assert gcd(17, 31) == 1
with pytest.raises(ValueError):
gcd(0, 0)
with pytest.raise... | [
{
"docstring": "Computes the greatest common divisor of integers a and b using Euclid's Algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the least common multiple of integers a and b using gcd function.",
... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"\n Computes the greatest common divisor of integers a and b using Euclid's Algorithm.\n \"\"\"\n if not isinstance(a, int) ... | trial_gpt4o_0 | {
"original_instruction": "You are developing a tool that requires the computation of greatest common divisors and least common multiples for pairs of numbers. To ensure robust and efficient implementations, you are asked to:\n\n1. Implement the `gcd` function using the Euclidean algorithm.\n2. Implement the `lcm` fu... | 0.817885 | Data_Structure_2449 | C | [
"gcd",
"lcm",
"gcd_bit"
] | 3 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2ab62700043e4a86f2ff0ed57cc84cad03c06d95 | 2ea81fadb5603d7a5fd5b42599e8f150366fb8f7 | |||
v1.0 | complete | Data_Structure | Data_Structure_2338_C | import random
from typing import Optional, Tuple
def is_probably_prime(num: int, k: int) -> bool:
"""
Uses the Miller-Rabin primality test to check if a number is a probable prime.
Parameters:
num (int): The number to test for primality.
k (int): The number of iterations for the Miller-Rabin test ... | import random
def is_probably_prime(num, k):
"""
Uses the Miller-Rabin primality test to check if a number is a probable prime.
Parameters:
num (int): The number to test for primality.
k (int): The number of iterations for the Miller-Rabin test (higher k increases the accuracy).
Returns:
... | from solution import is_probably_prime, generate_key
def test_is_probably_prime_small_primes():
assert is_probably_prime(2, 5)
assert is_probably_prime(3, 5)
assert is_probably_prime(5, 5)
assert is_probably_prime(7, 5)
assert is_probably_prime(11, 5)
assert is_probably_prime(13, 5)
def test_i... | [
{
"docstring": "Uses the Miller-Rabin primality test to check if a number is a probable prime.\nParameters:\nnum (int): The number to test for primality.\nk (int): The number of iterations for the Miller-Rabin test (higher k increases the accuracy).\nReturns: \nbool: True if num is probably prime, otherwise Fal... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_probably_prime(num, k):\n \"\"\" \n Uses the Miller-Rabin primality test to check if a number is a probable prime.\n Paramete... | trial_gpt4o_0 | {
"original_instruction": "### Question: Implement Enhanced RSA Encryption Key Generation\n\n#### Context:\nRSA encryption is a fundamental algorithm in modern cryptography. It ensures the secure transmission of data over an insecure network. This question focuses on generating RSA keys with a more efficient prime nu... | 0.654181 | Data_Structure_2338 | C | [
"is_probably_prime",
"generate_key"
] | 2 | [
[
"generate_key",
"is_probably_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4f708e195014fd102a0c8f0baa91337d9f92b06f | 0d89054d2df80be8c126949e9e6413c858c322a6 | |||
v1.0 | complete | Data_Structure | Data_Structure_1777_C | def kd_tree_insert(root, point, depth=0):
"""Inserts a point into the KD-Tree.
Parameters:
root: Root node of the KD-Tree.
point: A tuple representing the point to be inserted.
depth: The current depth, used to determine which axis to split.
Returns:
None
"""
pass
de... | import math
class KDTreeNode:
def __init__(self, point, left=None, right=None):
self.point = point
self.left = left
self.right = right
def kd_tree_insert(root, point, depth=0):
if root is None:
return KDTreeNode(point)
axis = depth % len(point)
if point[axis] ... | from solution import kd_tree_insert, kd_tree_nearest, optimized_nearest_neighbor
def test_kd_tree_insert_and_nearest():
points = [(1, 2), (3, 4), (5, 6), (7, 8)]
root = None
for point in points:
root = kd_tree_insert(root, point)
assert kd_tree_nearest(root, (4, 5)) == (3, 4)
assert kd... | [] | [
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\nclass KDTreeNode:\n def __init__(self, point, left=None, right=None):\n self.point = point\n self.left = left\n self.ri... | trial_gpt4o_0 | {
"original_instruction": "Implement an Optimized Nearest Neighbor Algorithm\n\n**Context:**\nYou are working on a machine learning project that involves classifying data points using the nearest neighbor algorithm. Given the limitations of the basic implementation provided, you need to optimize the algorithm to hand... | 0.604405 | Data_Structure_1777 | C | [
"kd_tree_insert",
"distance_squared",
"kd_tree_nearest",
"optimized_nearest_neighbor"
] | 4 | [
[
"kd_tree_nearest",
"distance_squared"
],
[
"optimized_nearest_neighbor",
"kd_tree_insert"
],
[
"optimized_nearest_neighbor",
"kd_tree_nearest"
]
] | 3 | [] | false | [
"KDTreeNode"
] | true | pytest | true | [] | true | 897df49638aa5590381594877b560d971d9897e2 | 8de8c08a3c6e52ade2fa9e5821d5056d452661cf | |||
v1.0 | complete | Data_Structure | Data_Structure_2229_C | from typing import List, Tuple
def vector_to_index_value_list(vector: List[float]) -> List[Tuple[int, float]]:
"""
Converts a dense vector to a sparse vector represented as a list of index-value pairs.
>>> vector_to_index_value_list([1.0, 0.0, 0.0, 3.0, 0.0])
[(0, 1.0), (3, 3.0)]
>>> vector_to_inde... | from typing import List, Tuple
def vector_to_index_value_list(vector: List[float]) -> List[Tuple[int, float]]:
"""
Converts a dense vector to a sparse vector represented as a list of index-value pairs.
"""
return [(i, value) for i, value in enumerate(vector) if value != 0.0]
def sparse_vector_dot_prod... | from solution import sparse_vector_dot_product, vector_to_index_value_list
def test_vector_to_index_value_list():
assert vector_to_index_value_list([1.0, 0.0, 0.0, 3.0, 0.0]) == [(0, 1.0), (3, 3.0)]
assert vector_to_index_value_list([0.0, 0.0, 0.0]) == []
assert vector_to_index_value_list([0.0, 2.0, 0.0, 0... | [
{
"docstring": "Converts a dense vector to a sparse vector represented as a list of index-value pairs.",
"function_declaration": "def vector_to_index_value_list(vector):",
"function_name": "vector_to_index_value_list",
"parameter_list": "(vector)"
},
{
"docstring": "Computes the dot product ... | [
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, Tuple\n\ndef vector_to_index_value_list(vector: List[float]) -> List[Tuple[int, float]]:\n \"\"\"\n Converts a dense vector (li... | trial_gpt4o_2 | {
"original_instruction": "You are given two large sparse vectors, potentially with millions of elements but only a small percentage of them being non-zero. To efficiently store these vectors and perform operations on them, a better data representation is required.\n\nWrite a Python function `sparse_vector_dot_produc... | 0.567435 | Data_Structure_2229 | C | [
"vector_to_index_value_list",
"sparse_vector_dot_product"
] | 2 | [
[
"sparse_vector_dot_product",
"vector_to_index_value_list"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ce4d6079c6d2f7bbb6b871553e41ede7b85c141a | c4ac3e8c0fba21afd396ff0c06420cdd51789576 | |||
v1.0 | complete | Data_Structure | Data_Structure_2649_C | def is_valid_chain(chain: dict) -> bool:
"""
Validates the Markov Chain by ensuring all probability distributions
from each state sum to 1.
>>> is_valid_chain({'a': {'b': 0.5, 'c': 0.5}, 'b': {'a': 1.0}, 'c': {'a': 0.7, 'b': 0.3}})
True
>>> is_valid_chain({'a': {'b': 0.2, 'c': 0.5}, 'b': {'... | import random
def is_valid_chain(chain: dict) -> bool:
"""
Validates the Markov Chain by ensuring all probability distributions
from each state sum to 1 (or nearly 1 due to floating-point precision).
"""
for state, transitions in chain.items():
if not (0.99 <= sum(transitions.values()) <= 1... | from solution import is_valid_chain, generate_text
def test_is_valid_chain():
valid_chain = {
'a': {'b': 0.5, 'c': 0.5},
'b': {'a': 1.0},
'c': {'a': 0.7, 'b': 0.3}
}
invalid_chain = {
'a': {'b': 0.2, 'c': 0.5},
'b': {'a': 1.1},
'c': {'a': 0.7, 'b': 0.1}
... | [
{
"docstring": "Validates the Markov Chain by ensuring all probability distributions\nfrom each state sum to 1 (or nearly 1 due to floating-point precision).",
"function_declaration": "def is_valid_chain(chain):",
"function_name": "is_valid_chain",
"parameter_list": "(chain)"
},
{
"docstring... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_valid_chain(chain: dict) -> bool:\n \"\"\"\n Check if the Markov Chain is valid. A valid chain has all \n probability distrib... | trial_gpt4o_1 | {
"original_instruction": "**Problem Statement**:\n\nYou are tasked with enhancing and extending a Markov Chain model for a text generation system where each state corresponds to a word, and transitions between states are based on the preceding word in a sentence.\n\nGiven a dictionary structure of a Markov Chain for... | 0.527909 | Data_Structure_2649 | C | [
"is_valid_chain",
"generate_text",
"weighted_choice"
] | 3 | [
[
"generate_text",
"weighted_choice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aa02fb21277f748e64af2fed9a4816b0e656c626 | e6324cd9eab4fe17bbf666f651761ebc25aaf4be | |||
v1.0 | complete | Data_Structure | Data_Structure_2921_C | from typing import List
from math import gcd
from functools import reduce
def euler_totient(x: int) -> int:
""" Compute Euler's Totient function for a given integer x.
>>> euler_totient(1)
1
>>> euler_totient(5)
4
"""
def lcm(a: int, b: int) -> int:
""" Compute the least common multiple (L... | from math import gcd
from functools import reduce
from sympy.ntheory import totient
def lcm(a, b):
"""
Helper function to compute LCM of two numbers a and b.
"""
return a * b // gcd(a, b)
def lcm_of_numbers(upto_n):
"""
Compute the least common multiple (LCM) of all integers from 1 to upto_n.
... | from solution import lcm_of_numbers
def test_lcm_of_numbers():
assert lcm_of_numbers(1) == 1
assert lcm_of_numbers(2) == 2
assert lcm_of_numbers(3) == 6
assert lcm_of_numbers(4) == 12
assert lcm_of_numbers(5) == 60
assert lcm_of_numbers(6) == 60
assert lcm_of_numbers(7) == 420
assert lc... | [
{
"docstring": "Helper function to compute LCM of two numbers a and b.",
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": "Compute the least common multiple (LCM) of all integers from 1 to upto_n.",
"function_declaration": "de... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import gcd\n\ndef euler_totient(x):\n \"\"\" Computes Euler's Totient Function for x \"\"\"\n result = x\n p = 2\n while p * p <= x:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Euler's Totient Function Advanced Application\n\n**Objective**: Implement a function to find the least common multiple (LCM) of all numbers from 1 to `n`, and use Euler's Totient Function within your implementation.\n\n**Problem Statement**:\nGiven an integer `n`, write a function `lcm_... | 0.687584 | Data_Structure_2921 | C | [
"lcm",
"lcm_of_numbers"
] | 2 | [
[
"lcm_of_numbers",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | a29fd901a75e3d645757d5569ed272a652667462 | c108553775300b5758afa3ba51f549f3f48914a4 | |||
v1.0 | complete | Data_Structure | Data_Structure_2234_C | from typing import List
def pancake_sort(arr: List[int]) -> List[int]:
""" Pancake Sort Challenge: Sort the given list of unsorted integers using the Pancake Sort algorithm.
This function sorts the array `arr` in non-decreasing order by picking the maximum element and moving it to its position by flipping... | def flip(arr, k):
"""
Reverses the sub-array arr[0:k+1]
"""
left = 0
right = k
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
def find_max_index(arr, n):
"""
Finds the index of the maximum element in arr[0:n]
"""
ma... | from solution import pancake_sort
def test_pancake_sort_example1():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
def test_pancake_sort_example2():
assert pancake_sort([1, 2, 3]) == [1, 2, 3]
def test_pancake_sort_empty():
assert pancake_sort([]) == []
def test_pancake_sort_single_element():
ass... | [
{
"docstring": "Reverses the sub-array arr[0:k+1]",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Finds the index of the maximum element in arr[0:n]",
"function_declaration": "def find_max_index(arr, n):",
"funct... | [
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 flip(arr: List[int], k: int) -> None:\n \"\"\"\n Helper function to reverse the array up to index k.\n \"\"\"\n arr... | trial_gpt4o_2 | {
"original_instruction": "### Pancake Sort Challenge\n\nAs an aspiring programmer, you have encountered various sorting algorithms. Today, you will implement an interesting, lesser-known one called **Pancake Sort**. This is a sorting algorithm where you pick the maximum element and move it to its position by flippin... | 0.755209 | Data_Structure_2234 | C | [
"flip",
"find_max_index",
"pancake_sort"
] | 3 | [
[
"pancake_sort",
"find_max_index"
],
[
"pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 40e7fe5efb19db06e8a337a38f3f9ff05cb14a85 | d0bc1499179a38d52dbf748aa029cdba3d91e1ef | |||
v1.0 | complete | Data_Structure | Data_Structure_2056_C | from typing import List
def bucket_sort(arr: List[float]) -> List[float]:
"""Given an array of floating-point numbers uniformly distributed over the range [0, 1),
implement a bucket sort algorithm to sort the array.
Parameters:
arr (List[float]): An array of floating-point numbers within the range [0.... | from typing import List
def insertion_sort(arr: List[float]) -> List[float]:
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def bucket_sort(arr: List[float]) -> Li... | from solution import bucket_sort
def test_bucket_sort_basic():
input_array = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]
expected = [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
assert bucket_sort(input_array) == expected
def test_bucket_sort_empty():
assert bucket_sort... | [
{
"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,
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 for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n ... | trial_gpt4o_2 | {
"original_instruction": "Given an array of floating-point numbers uniformly distributed over the range [0, 1), implement a bucket sort algorithm to sort the array.\n\n### Problem Description\n\n**Function Signature**: `def bucket_sort(arr: List[float]) -> List[float]`\n\nWrite a Python function that sorts an array ... | 0.594402 | Data_Structure_2056 | C | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9b93e9acd7445f474831a94c2f40126482f1230a | 7ccdba1bf9c0ceffd2d72a710db48ae635a118ed | |||
v1.0 | complete | Data_Structure | Data_Structure_1630_C | import random
def gen_prime(k, seed=None):
"""Generate a prime with k bits using the Miller-Rabin primality test."""
# Fill in the implementation
def generate_key(k, seed=None):
"""Generate an RSA key pair.
Args:
k (int): The number of bits for the prime numbers.
seed (int, optional): A s... | import random
def miller_rabin_primality_test(n, k):
"""Run the Miller-Rabin primality test `k` times to determine if `n` is a prime number."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
# write (n - 1) as 2^r * d
r, d = 0, n - 1
... | from solution import generate_key, encrypt, decrypt
import random
def test_gen_prime():
for k in [16, 32, 64]:
assert len(bin(gen_prime(k))) - 2 == k
def test_generate_key():
n, e, d = generate_key(16)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert... | [
{
"docstring": "Run the Miller-Rabin primality test `k` times to determine if `n` is a prime number.",
"function_declaration": "def miller_rabin_primality_test(n, k):",
"function_name": "miller_rabin_primality_test",
"parameter_list": "(n, k)"
},
{
"docstring": "Generate a prime with k bits ... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom math import gcd\n\ndef is_prime(n, k=5):\n \"\"\"Use Miller-Rabin primality test to test if a number is prime\"\"\"\n if n <= 1:\n ... | trial_gpt4o_8 | {
"original_instruction": "### RSA Encryption Key Generation and Data Encryption/Decryption\n\nYou are given an implementation of the RSA encryption algorithm which includes key generation, encryption, and decryption functions. The provided implementation generates RSA keys and uses them to encrypt and decrypt data. ... | 0.647418 | Data_Structure_1630 | C | [
"miller_rabin_primality_test",
"gen_prime",
"gcd",
"modinv",
"generate_key",
"encrypt",
"decrypt"
] | 7 | [
[
"gen_prime",
"miller_rabin_primality_test"
],
[
"generate_key",
"gcd"
],
[
"generate_key",
"gen_prime"
],
[
"generate_key",
"modinv"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 8171dd949f3c38b05dd0d21c0b627b570d03322f | 96d8be93f280a59068f950abbeeb931d07d2f567 | |||
v1.0 | complete | Data_Structure | Data_Structure_3230_C | def matrix_inverse(matrix):
""" Calculate the inverse of an n x n matrix.
If the matrix is non-invertible (e.g., singular or not square), return None.
>>> matrix_inverse([[4, 7], [2, 6]])
[[0.6, -0.7], [-0.2, 0.4]]
>>> matrix_inverse([[1, 2], [2, 4]])
None
>>> matrix_inverse([[1, 0], [0... | def matrix_determinant(matrix):
"""Helper function to compute the determinant of a matrix."""
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
determinant = 0
for c in range(n):
minor = [[matri... | from solution import matrix_inverse
def test_matrix_inverse_2x2():
matrix = [
[4, 7],
[2, 6]
]
expected = [
[0.6, -0.7],
[-0.2, 0.4]
]
result = matrix_inverse(matrix)
assert result == expected, f"Expected {expected}, but got {result}"
def test_matrix_inverse_3x3... | [
{
"docstring": "Helper function to compute the determinant of a matrix.",
"function_declaration": "def matrix_determinant(matrix):",
"function_name": "matrix_determinant",
"parameter_list": "(matrix)"
},
{
"docstring": "Helper function to get the minor of the matrix excluding row i and colum... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_determinant(matrix):\n \"\"\"Helper function to compute the determinant of a matrix.\"\"\"\n n = len(matrix)\n if n == 1:\n return ... | trial_gpt4o_0 | {
"original_instruction": "### Matrix Inversion Function\n\nYou are required to implement a `matrix_inverse` function that calculates the inverse of an `n x n` matrix using the principles outlined above. Your implementation should follow these steps:\n1. **Matrix of Minors**: Compute the minors for each element.\n2. ... | 0.550287 | Data_Structure_3230 | C | [
"matrix_determinant",
"get_matrix_minor",
"matrix_inverse"
] | 3 | [
[
"matrix_inverse",
"get_matrix_minor"
],
[
"matrix_inverse",
"matrix_determinant"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1c44116ca0d2892f6c1d8b970e946ce3d2c7a6eb | 185ab7a34c0a3d29d6824a62426bf6e31ea87d71 | |||
v1.0 | complete | Data_Structure | Data_Structure_1571_C | def insertion_sort(arr):
"""Sorts the array in-place using insertion sort."""
pass
def merge(left, right):
"""Merges two sorted lists into a sorted list."""
pass
def merge_sort(arr, k=10):
"""Sorts the array using merge sort with an insertion sort optimization for small sublists.
>>> merg... | def insertion_sort(arr):
"""
Sorts the array in-place using insertion sort.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def merge(left, right):
"""
Merg... | from solution import merge_sort, merge, insertion_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_... | [
{
"docstring": "Sorts the array in-place using insertion sort.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into a sorted list.",
"function_declaration": "def merge(left, righ... | [
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 merge_sort(arr, k=10):\n if len(arr) <= 1:\n return arr\n\n if len(arr) < k:\n return insertion_sort(arr)\n\n mid = len(arr) // 2\n... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Implementation with Advanced Features\n\nGiven the principles and characteristics of the merge sort algorithm, implement the `merge_sort` function and its helper `merge` which includes the following requirements:\n\n1. **Input**: A list of integers `arr` of size `n` (0 <= n <... | 0.629186 | Data_Structure_1571 | C | [
"insertion_sort",
"merge",
"merge_sort"
] | 3 | [
[
"merge_sort",
"insertion_sort"
],
[
"merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 059c2abe52d4994eaa814aa7d607ff592b59204b | c97b5644badac7f180eac3f549ccc9fba6c4a106 | |||
v1.0 | complete | Data_Structure | Data_Structure_2382_C | def is_prime(n: int) -> bool:
""" Check if a number n is a prime number.
Time Complexity: O(sqrt(n))
>>> is_prime(2)
True
>>> is_prime(4)
False
>>> is_prime(17)
True
"""
pass
def find_primitive_root(p: int) -> int:
""" Find a primitive root for prime p.
>>> find_primitiv... | import random
from math import gcd
from sympy import isprime
def is_prime(n: int) -> bool:
"""
Check if a number n is a prime number.
Time Complexity: O(sqrt(n))
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
... | def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(13)
assert is_prime(17)
assert not is_prime(0)
assert not is_prime(1)
assert not is_prime(18)
assert is_prime(19)
def test_find_primitive_root():
assert find_primitive_root(23) in [... | [
{
"docstring": "Check if a number n is a prime number.\nTime Complexity: O(sqrt(n))",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find a primitive root for prime p.",
"function_declaration": "def find_primitive_root(... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom math import gcd\nfrom sympy import isprime\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Check if a number n is a prime number.\n T... | trial_gpt4o_0 | {
"original_instruction": "Implement a Secure Diffie-Hellman Key Exchange\n\nYou have been given the task to implement a secure key exchange protocol using the Diffie-Hellman algorithm. The objective is to generate a shared secret key between two parties (Alice and Bob) over an unsecured communication channel.\n\n###... | 0.570852 | Data_Structure_2382 | C | [
"is_prime",
"find_primitive_root",
"generate_private_key",
"generate_public_key",
"compute_shared_key",
"diffie_hellman_key_exchange"
] | 6 | [
[
"diffie_hellman_key_exchange",
"compute_shared_key"
],
[
"diffie_hellman_key_exchange",
"generate_private_key"
],
[
"diffie_hellman_key_exchange",
"generate_public_key"
],
[
"find_primitive_root",
"is_prime"
]
] | 4 | [] | false | [] | false | pytest | false | [
"sympy"
] | false | 69e376162979179f10bc8fb3976a9b8cb8120af5 | c785cf0b84104e144474d7c9edc68ff358002ccb | |||
v1.0 | complete | Data_Structure | Data_Structure_2906_C | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Helper function to find the index at which val should be inserted to maintain sorted order.
"""
pass
def insertion_sort_with_search(array: List[int], val: int) -> List[int]:
""" Returns a new sorted array with `val` ... | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Helper function to find the index at which val should be inserted to maintain sorted order.
"""
left, right = 0, len(array) - 1
while left <= right:
mid = left + (right - left) // 2
if ar... | from solution import insertion_sort_with_search
def test_insert_middle():
assert insertion_sort_with_search([1, 3, 5, 6], 2) == [1, 2, 3, 5, 6]
def test_insert_existing():
assert insertion_sort_with_search([1, 3, 5, 6], 5) == [1, 3, 5, 5, 6]
def test_insert_end():
assert insertion_sort_with_search([1, 3,... | [
{
"docstring": "Helper function to find the index at which val should be inserted to maintain sorted order.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "Returns a new sorted array with val in... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n This helper function returns the index at which `val` should... | trial_gpt4o_2 | {
"original_instruction": "### Coding Challenge\n\nYou are given a sorted array of integers and a new integer `val` that needs to be inserted into the array. The aim is to maintain the sorted order after the insertion. Write a function `insertion_sort_with_search(array, val)` that returns a new sorted array with `val... | 0.642658 | Data_Structure_2906 | C | [
"search_insert",
"insertion_sort_with_search"
] | 2 | [
[
"insertion_sort_with_search",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d2a3697bc659ce6289e45f63b1bcda1de7b9b815 | 38bed404de5ae0f66ef701ce19ab1999c5080ce6 | |||
v1.0 | complete | Data_Structure | Data_Structure_1390_C | from typing import List
def bucket_sort(arr: List[float]) -> List[float]:
"""Given an array of floating-point numbers in the range [0, 1),
sort them using the Bucket Sort algorithm with Merge Sort for
sorting within each bucket.
Args:
arr (List[float]): A list of floating-point numbers in th... | from typing import List
def merge_sort(arr: List[float]) -> List[float]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left: List[float], right: List[float]) -> List[float]:
sorted_li... | from solution import bucket_sort
def test_bucket_sort_example_1():
assert bucket_sort([0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]) == \
[0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
def test_bucket_sort_example_2():
assert bucket_sort([0.42, 0.32, 0.23, 0.52, 0.3, 0.... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
},
{
"docst... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[float]) -> List[float]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n lef... | trial_gpt4o_2 | {
"original_instruction": "### Challenging Coding Assessment Question\n\n#### Problem Statement\n\nGiven an array of floating-point numbers in the range [0, 1), implement a sorting function using the Bucket Sort algorithm. Each bucket should be sorted using the Merge Sort algorithm instead of the more straightforward... | 0.604305 | Data_Structure_1390 | C | [
"merge_sort",
"merge",
"bucket_sort"
] | 3 | [
[
"bucket_sort",
"merge_sort"
],
[
"merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fbfc15de2e1bef0e80ec18ad0f64ecf1782a37b8 | 87ef75177c0d7e14eb47cc10b417b6352ba28a72 | |||
v1.0 | complete | Data_Structure | Data_Structure_2885_C | import random
def is_prime(num: int) -> bool:
""" Determines if a number num is prime.
>>> is_prime(2)
True
>>> is_prime(17)
True
>>> is_prime(18)
False
"""
pass
def euler_totient(n: int) -> int:
""" Computes the Euler's Totient function ϕ(n).
>>> euler_totient(1)
1
... | import random
def is_prime(num: int) -> bool:
"""
Determines if a number num is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
... | from solution import is_prime, euler_totient, find_primitive_root, diffie_hellman_key_exchange
def test_is_prime():
assert is_prime(2) == True
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(97) == True
assert is_prime(100) == False
def test_euler_totient():
assert eul... | [
{
"docstring": "Determines if a number num is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Computes the Euler's Totient function ϕ(n).",
"function_declaration": "def euler_totient(n):",
"function_name... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom math import gcd\nfrom functools import reduce\n\ndef is_prime(num: int) -> bool:\n \"\"\"\n Check if a number is prime.\n \"\"\"\... | trial_gpt4o_8 | {
"original_instruction": "### Secure Communication with Diffie-Hellman Key Exchange\n\nYou are assigned the task of implementing part of a secure communication protocol based on the Diffie-Hellman key exchange algorithm. Your goal is to write functions that perform the key operations needed for Alice and Bob to secu... | 0.609666 | Data_Structure_2885 | C | [
"is_prime",
"euler_totient",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 4 | [
[
"diffie_hellman_key_exchange",
"is_prime"
],
[
"find_primitive_root",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e6b63027edbadfa0022fb3c8cb1b62c444dfdbe9 | 784cc5b01d108d2eaa481c28b5faaec06df78aac | |||
v1.0 | complete | Data_Structure | Data_Structure_1764_C | class RBNode:
def __init__(self, val, is_red, parent=None, left=None, right=None):
self.val = val
self.parent = parent
self.left = left
self.right = right
self.color = is_red # 1 for red, 0 for black
def is_valid_rbtree(root: RBNode) -> bool:
"""Determine if a given tre... | class RBNode:
def __init__(self, val, is_red, parent=None, left=None, right=None):
self.val = val
self.parent = parent
self.left = left
self.right = right
self.color = is_red # 1 for red, 0 for black
def is_valid_rbtree(root):
"""
Determine if a given tree is a vali... | from solution import RBNode, is_valid_rbtree, count_red_nodes, verify_properties
def test_is_valid_rbtree_valid():
root = RBNode(10, 0)
root.left = RBNode(5, 1, root)
root.right = RBNode(15, 1, root)
root.left.left = RBNode(2, 0, root.left)
root.left.right = RBNode(8, 0, root.left)
assert is_va... | [] | [
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class RBNode:\n def __init__(self, val, is_red, parent=None, left=None, right=None):\n self.val = val\n self.parent = parent\n self.le... | trial_gpt4o_9 | {
"original_instruction": "A Red-Black Tree (RBTree) is a balanced binary search tree with distinct properties that ensure the tree remains balanced during insertions and deletions. You are required to implement certain functions to manipulate the RBTree. Specifically, you must:\n\n1. Implement a function to determin... | 0.499992 | Data_Structure_1764 | C | [
"is_valid_rbtree",
"count_red_nodes",
"verify_properties"
] | 3 | [
[
"verify_properties",
"is_valid_rbtree"
]
] | 1 | [] | false | [
"RBNode"
] | true | pytest | true | [] | true | dcb2b1816d613e471c173efa457ab93283976dd9 | 9891e96198f7783707b8fda2d9aae7beb9806aad | |||
v1.0 | complete | Data_Structure | Data_Structure_3435_C | from typing import List
def circular_house_robber(houses: List[int]) -> int:
""" Calculate the maximum amount of money that can be robbed from circular houses
without alerting the police.
>>> circular_house_robber([2, 3, 2])
3
>>> circular_house_robber([1, 2, 3, 1])
4
>>> circular_house_rob... | from typing import List
def house_robber(houses: List[int]) -> int:
n = len(houses)
if n == 0:
return 0
if n == 1:
return houses[0]
dp = [0] * n
dp[0] = houses[0]
dp[1] = max(houses[0], houses[1])
for i in range(2, n):
dp[i] = max(dp[i-1], dp[i-2] + houses[... | from solution import circular_house_robber
def test_empty_list():
assert circular_house_robber([]) == 0
def test_single_house():
assert circular_house_robber([5]) == 5
def test_two_houses():
assert circular_house_robber([2, 3]) == 3
def test_three_houses():
assert circular_house_robber([2, 3, 2]) ==... | [
{
"docstring": null,
"function_declaration": "def house_robber(houses):",
"function_name": "house_robber",
"parameter_list": "(houses)"
},
{
"docstring": null,
"function_declaration": "def circular_house_robber(houses):",
"function_name": "circular_house_robber",
"parameter_list"... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rob_linear(houses: List[int]) -> int:\n \"\"\"\n Solves the house robbery problem for a linear street.\n \"\"\"\n p... | trial_gpt4o_4 | {
"original_instruction": "### Robbing Circular Houses\n\nYou are a professional robber planning to rob houses along a circular street. Each house has a certain amount of money stashed, and the only constraint stopping you from robbing each of them is that adjacent houses have a security system connected, which will ... | 0.562826 | Data_Structure_3435 | C | [
"house_robber",
"circular_house_robber"
] | 2 | [
[
"circular_house_robber",
"house_robber"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 73f4852397030084f051f556c80fe88f09c75267 | 4e026906b29b85ec0afd9748c0e2572d467c4c34 | |||
v1.0 | complete | Data_Structure | Data_Structure_1961_C | from typing import Dict, Set, List
def find_all_cliques(edges: Dict[int, Set[int]]) -> List[List[int]]:
""" Find all maximal cliques in an undirected graph using the Bron-Kerbosch Algorithm.
Parameters:
edges: A dictionary where keys are integers representing vertices, and values are sets of integ... | from typing import Dict, Set, List
def bron_kerbosch(R: Set[int], P: Set[int], X: Set[int], result: List[List[int]], graph: Dict[int, Set[int]]):
if not P and not X:
result.append(list(R))
return
for v in list(P):
bron_kerbosch(R.union({v}), P.intersection(graph[v]), X.intersection(grap... | from solution import find_all_cliques
def test_single_vertex():
edges = {0: set()}
assert find_all_cliques(edges) == [[0]]
def test_no_edges():
edges = {
0: set(),
1: set(),
2: set()
}
assert find_all_cliques(edges) == [[0], [1], [2]]
def test_fully_connected():
edges ... | [
{
"docstring": null,
"function_declaration": "def bron_kerbosch(R, P, X, result, graph):",
"function_name": "bron_kerbosch",
"parameter_list": "(R, P, X, result, graph)"
},
{
"docstring": null,
"function_declaration": "def find_all_cliques(edges):",
"function_name": "find_all_cliques... | [
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 find_all_cliques(edges):\n \"\"\"\n Finds all maximal cliques in an undirected graph using the Bron-Kerbosch algorithm.\n\n Parameters:\n edge... | trial_gpt4o_2 | {
"original_instruction": "Finding All Cliques in an Undirected Graph\n\n#### Problem Statement\nGiven an undirected graph represented by a dictionary where the keys are vertex identifiers and the values are sets of vertices connected to the key vertex, write an algorithm to find all maximal cliques in the graph usin... | 0.421551 | Data_Structure_1961 | C | [
"bron_kerbosch",
"find_all_cliques"
] | 2 | [
[
"find_all_cliques",
"bron_kerbosch"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9cbd5a067d2175c0a9a51d6b5f903b9cdd6b825e | b75f97d23d8a0a62603aa0b9f760100d26f4dc8d | |||
v1.0 | complete | Data_Structure | Data_Structure_2336_C | from typing import List
def optimized_insertion_sort(arr: List[int]) -> List[int]:
""" Sort a given list of integers using an optimized insertion sort with binary search.
Args:
arr (List[int]): List of integers to be sorted.
Returns:
List[int]: Sorted list of integers.
Examples:
>>> ... | from typing import List
def binary_search(arr: List[int], val: int, start: int, end: int) -> int:
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
start = mid + 1
else:
end = mid
return start
def optimized_insertion_sort(arr: List[int]) -> List[int... | from solution import optimized_insertion_sort
def test_optimized_insertion_sort():
# Test empty array
assert optimized_insertion_sort([]) == []
# Test single element array
assert optimized_insertion_sort([1]) == [1]
# Test already sorted array
assert optimized_insertion_sort([1, 2, 3, 4, 5]) ... | [
{
"docstring": null,
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": null,
"function_declaration": "def optimized_insertion_sort(arr):",
"function_name": "optimized_inse... | [
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 that uses binary search ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implementing Optimized Insertion Sort\n\n**Scenario**:\nYou are working as a software engineer at a logistics company that frequently deals with small datasets of shipment weights that need to be sorted for processing. You've been tasked with optimizing the sorting of these we... | 0.652409 | Data_Structure_2336 | C | [
"binary_search",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bc8449276a6c4a9b3b991d507a1506e597a55b56 | dce75e76789ee21904016dbad311395595e3e737 | |||
v1.0 | complete | Data_Structure | Data_Structure_2799_C | from typing import List
import math
def _l2_distance(vec: List[float]) -> float:
"""
Helper function to calculate the L2 norm (Euclidean norm) of a vector.
"""
pass
def cosine_similarity(vec1: List[float], vec2: List[float]) -> float:
"""
Calculate the cosine similarity between two vectors.
... | from typing import List
import math
def _l2_distance(vec: List[float]) -> float:
"""
Helper function to calculate the L2 norm (Euclidean norm) of a vector.
"""
return math.sqrt(sum(x ** 2 for x in vec))
def cosine_similarity(vec1: List[float], vec2: List[float]) -> float:
"""
Calculate the cos... | from solution import cosine_similarity
def test_cosine_similarity_identical_vectors():
assert math.isclose(cosine_similarity([1, 1], [1, 1]), 1.0)
def test_cosine_similarity_orthogonal_vectors():
assert math.isclose(cosine_similarity([1, 0], [0, 1]), 0.0)
def test_cosine_similarity_opposite_vectors():
as... | [
{
"docstring": "Helper function to calculate the L2 norm (Euclidean norm) of a vector.",
"function_declaration": "def _l2_distance(vec):",
"function_name": "_l2_distance",
"parameter_list": "(vec)"
},
{
"docstring": "Calculate the cosine similarity between two vectors.",
"function_declar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import List\n\ndef _l2_distance(vec: List[float]) -> float:\n \"\"\"\n Computes the L2 norm (Euclidean distance) of a vector.\n... | trial_gpt4o_2 | {
"original_instruction": "### Cosine Similarity Implementation\n\n**Objective**: Implement a function to calculate the cosine similarity between two one-dimensional lists of numerical data.\n\n**Function Signature**:\n```python\ndef cosine_similarity(vec1: List[float], vec2: List[float]) -> float:\n```\n\n**Input**:... | 0.601664 | Data_Structure_2799 | C | [
"_l2_distance",
"cosine_similarity"
] | 2 | [
[
"cosine_similarity",
"_l2_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fd4ab19dbed9aca2a69c43af4ec29bd9686bf61d | 69de73a1fd540eb9ba2792cc387a5c22bf9d0207 | |||
v1.0 | complete | Data_Structure | Data_Structure_2970_C | from typing import Tuple, Dict
def classify_vector(x: Tuple[float, ...], tSet: Dict[Tuple[float, ...], str]) -> str:
""" Classify the vector x based on the nearest neighbor in the training set tSet.
Args:
x : tuple
Vector to classify.
tSet : dict
Training set where the keys are vec... | import math
def euclidean_distance(v1, v2):
"""
Compute the Euclidean distance between two vectors v1 and v2.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def classify_vector(x, tSet):
"""
Classify the vector x based on the nearest neighbor in the training set tSet.
Arg... | from solution import classify_vector
def test_basic_case():
x = (2.5, 3.6)
tSet = {
(1.0, 2.0): 'A',
(4.5, 3.2): 'B',
(2.5, 4.0): 'C'
}
assert classify_vector(x, tSet) == 'C'
def test_single_point():
x = (1.0, 2.0)
tSet = {
(1.0, 2.0): 'A'
}
assert class... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(vec1, vec2):\n return math.sqrt(sum((a - b) ** 2 for a, b in zip(vec1, vec2)))\n\ndef classify_vector(x, tSet):\n ... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nYou are tasked with developing a simple classification model using the nearest neighbor algorithm. Your function will receive a vector to classify and a labeled training set. The functionality should accurately match the provided vector to its nearest neighbor in the training ... | 0.515602 | Data_Structure_2970 | C | [
"euclidean_distance",
"classify_vector"
] | 2 | [
[
"classify_vector",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 37aa7c295ee69c8ca8aaa43a9df2ad044275e432 | bc470c2e7720da2c9a3f9f7309216886f2d068e6 | |||
v1.0 | complete | Data_Structure | Data_Structure_3193_C | from typing import List
def shortest_distance(grid: List[List[int]]) -> int:
"""
Compute the shortest total distance from a new facility to all buildings in a city grid.
Args:
- grid (List[List[int]]): A 2D list of integers representing the city layout (0 for empty space, 1 for building, 2 for ob... | from collections import deque
from typing import List, Tuple
def bfs(grid: List[List[int]], start: Tuple[int, int], distance: List[List[int]], reach_cnt: List[List[int]], num_building: int):
rows, cols = len(grid), len(grid[0])
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
queue = deque([(start[0], ... | from solution import shortest_distance
def test_example_1():
grid = [
[1, 0, 2, 0, 1],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0]
]
assert shortest_distance(grid) == 7
def test_example_2():
grid = [
[1, 0, 2],
[0, 2, 2],
[2, 2, 1]
]
assert shortest_distanc... | [
{
"docstring": null,
"function_declaration": "def bfs(grid, start, distance, reach_cnt, num_building):",
"function_name": "bfs",
"parameter_list": "(grid, start, distance, reach_cnt, num_building)"
},
{
"docstring": null,
"function_declaration": "def shortest_distance(grid):",
"funct... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List, Tuple\n\ndef bfs(grid: List[List[int]], start_row: int, start_col: int, distances: List[List[int]], re... | trial_gpt4o_1 | {
"original_instruction": "### Context\nImagine you are an urban planner tasked with placing a new facility in a city grid that should be as accessible as possible to all residential buildings. The city grid is given as a 2D matrix where:\n- `0` represents an empty space,\n- `1` represents a residential building, and... | 0.630135 | Data_Structure_3193 | C | [
"bfs",
"shortest_distance"
] | 2 | [
[
"shortest_distance",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ae132356d816042bd5be388e6f56d51fb6f6606e | c685bc5b9acd51f46d0d93c692767075d313d2ad | |||
v1.0 | complete | Data_Structure | Data_Structure_3086_C | from typing import List
def maximum_water_flow(adjacency_matrix: List[List[int]]) -> int:
""" Determine the maximum flow of water from the source node (node 0)
to the sink node (node n-1) in a given network represented by an n×n
adjacency matrix.
>>> adjacency_matrix = [
... [0, 16, 13, 0, 0... | from typing import List
from collections import deque
def bfs(rGraph, s, t, parent):
visited = [False] * len(rGraph)
queue = deque([s])
visited[s] = True
while queue:
u = queue.popleft()
for ind, val in enumerate(rGraph[u]):
if visited[ind] == False and val > 0:
... | from solution import maximum_water_flow
def test_example_case():
adjacency_matrix = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_water_flow(adjacency_matrix) ==... | [
{
"docstring": null,
"function_declaration": "def bfs(rGraph, s, t, parent):",
"function_name": "bfs",
"parameter_list": "(rGraph, s, t, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_water_flow(adjacency_matrix):",
"function_name": "maximum_water_flow",
"p... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(rGraph, s, t, parent):\n visited = [False] * len(rGraph)\n queue = deque([s])\n vis... | trial_gpt4o_0 | {
"original_instruction": "#### Problem Context\n\nCompany XYZ is facing a major challenge in ensuring optimal distribution of water through their water supply network. As a solution architect, you are tasked with finding the maximum flow of water from the source to the destination in their supply network.\n\nGiven a... | 0.592058 | Data_Structure_3086 | C | [
"bfs",
"maximum_water_flow"
] | 2 | [
[
"maximum_water_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1843cbef4ac46b647fa87a3d796b8e0193ef67eb | 1af314a1116b89aed06dfb4021745951238448af | |||
v1.0 | complete | Data_Structure | Data_Structure_2983_C | class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def add_linked_lists(left: ListNode, left_neg: bool, right: ListNode, right_neg: bool) -> ListNode:
"""
Add two numbers represented by linked lists, considering the negativity of the numbers.
... | class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def linked_list_to_number(node: ListNode) -> int:
num = 0
place = 1
while node:
num += node.value * place
place *= 10
node = node.next
return num
def number_to_linked... | import pytest
from solution import ListNode, add_linked_lists
def build_linked_list(nums):
head = current = ListNode(nums[0])
for num in nums[1:]:
current.next = ListNode(num)
current = current.next
return head
def linked_list_to_str(head):
result = []
while head:
result.ap... | [] | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, value=0, next=None):\n self.value = value\n self.next = next\n\ndef to_number(node: ListNode, is_negativ... | trial_gpt4o_5 | {
"original_instruction": "## Linked List Addition with Negatives\n\n### Problem Statement:\nYou are given two linked lists representing two integers. The digits are stored in reverse order and each of their nodes contain a single digit. You need to add the two numbers and return the result as a new linked list.\n\nT... | 0.60577 | Data_Structure_2983 | C | [
"linked_list_to_number",
"number_to_linked_list",
"add_linked_lists"
] | 3 | [
[
"add_linked_lists",
"linked_list_to_number"
],
[
"add_linked_lists",
"number_to_linked_list"
]
] | 2 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | 3980affc15d54133d9e916f62a92cdcd5b164717 | e8ad1d84f0fc2973b08d6efeaeadc0ea61e5769c | |||
v1.0 | complete | Data_Structure | Data_Structure_3257_C | from typing import List
import random
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if the array is sorted.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def recursive_bogo_sort(arr: List[int]) -> List[int]:
"""
Recursively Bogo Sort the array.
Re... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if the array is sorted.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def recursive_bogo_sort(arr: List[int]) -> List[int]:
"""
Recursively Bogo Sort the array.
"""... | from solution import recursive_bogo_sort
def test_recursive_bogo_sort_sorted():
assert recursive_bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_recursive_bogo_sort_reverse_sorted():
assert recursive_bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_recursive_bogo_sort_unsorted():
assert recu... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Recursively Bogo Sort the array.",
"function_declaration": "def recursive_bogo_sort(arr):",
"fu... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to check if an array is sorted.\n \"\"\"\... | trial_gpt4o_1 | {
"original_instruction": "You have been tasked with writing a custom sorting algorithm based on the principles of Bogo Sort, but with an important twist to make it slightly more practical. Instead of sorting the entire array through shuffling, the algorithm should recursively break down the array into smaller sub-ar... | 0.674912 | Data_Structure_3257 | C | [
"is_sorted",
"recursive_bogo_sort"
] | 2 | [
[
"recursive_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aad8ce70944b3c2ff282f67b0f3599dd7b5af3e9 | dede7e21b18debdf772e75e5ea5b3a6fa898b09a | |||
v1.0 | complete | Data_Structure | Data_Structure_3335_C | from typing import List
import random
def bogoSort(arr: List[int], max_iterations: int = 100000) -> List[int]:
""" Sorts an array of integers by randomly shuffling it until it is sorted or max_iterations is reached.
>>> bogoSort([3, 2, 1])
[1, 2, 3]
>>> bogoSort([1, 2, 3])
[1, 2, 3]
... | from typing import List
import random
def is_sorted(arr: List[int]) -> bool:
"""Helper function to check if an array is sorted."""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogoSort(arr: List[int], max_iterations: int = 100000) -> List[int]:
... | from solution import bogoSort
def test_bogo_sort_sorted_array():
assert bogoSort([1, 2, 3]) == [1, 2, 3]
def test_bogo_sort_reverse_array():
result = bogoSort([3, 2, 1])
assert result == [1, 2, 3]
def test_bogo_sort_with_duplicates():
result = bogoSort([5, 1, 3, 3, 2])
assert result == so... | [
{
"docstring": "Helper function to check if an array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the array by randomly shuffling it until it is sorted or max_iterations is reached.",
"functio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List, Union\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to check if the array is sorted.\n ... | trial_gpt4o_2 | {
"original_instruction": "### Objective\n\nImplement a sorting algorithm based on the principles of randomness. You'll create a sort function that keeps randomly shuffling an array until it is sorted.\n\n### Detailed Problem Statement\n\nYou are required to implement the `bogoSort` function that sorts an array of in... | 0.63602 | Data_Structure_3335 | C | [
"is_sorted",
"bogoSort"
] | 2 | [
[
"bogoSort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6388a9b032b336ace3df24a4647497f48ade2625 | c3568fdc22d669194b7add92941d1ad5aad0e1c4 | |||
v1.0 | complete | Data_Structure | Data_Structure_1959_C | def improved_radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
""" Implement an improved version of the Radix Sort algorithm.
Args:
arr (List[int]): A list of non-negative integers to be sorted.
simulation (bool): Optional boolean flag to enable printing intermediate states of the ... | from typing import List
def improved_radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
if not arr:
return arr
max_num = max(arr)
exp = 1
radix = 10
while max_num // exp > 0:
counting_sort(arr, exp, radix, simulation)
exp *= 10
return arr
def counting... | from solution import improved_radix_sort
def test_empty_list():
assert improved_radix_sort([]) == []
def test_single_element():
assert improved_radix_sort([1]) == [1]
assert improved_radix_sort([0]) == [0]
def test_multiple_elements():
assert improved_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == ... | [
{
"docstring": null,
"function_declaration": "def improved_radix_sort(arr, simulation=False):",
"function_name": "improved_radix_sort",
"parameter_list": "(arr, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, radix, simulation):",
"func... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def improved_radix_sort(arr, simulation=False):\n if len(arr) <= 1:\n return arr\n\n def counting_sort(arr, exp, simulation):\n n = len(ar... | trial_gpt4o_2 | {
"original_instruction": "### Coding Task: Implement an Improved Radix Sort\n\nYou are required to implement an improved version of the Radix Sort algorithm. Your task involves enhancing the provided implementation to handle some of the common issues and edge cases described above.\n\n### Function Signature:\n```pyt... | 0.668514 | Data_Structure_1959 | C | [
"improved_radix_sort",
"counting_sort"
] | 2 | [
[
"improved_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2b20ea4d680a167727126efd1753ab80805a7e25 | 8886fa5cbf4ce7966b170f583adf9099911e03d4 | |||
v1.0 | complete | Data_Structure | Data_Structure_2916_C | def reverse_recursive(s: str) -> str:
"""Reverse a string recursively.
Args:
s (str): The string to reverse.
Returns:
str: The reversed string.
"""
pass
def reverse_iterative(s: str) -> str:
"""Reverse a string iteratively.
Args:
s (str): The string to reverse.
... | def reverse_recursive(s: str) -> str:
if len(s) == 0:
return s
else:
return s[-1] + reverse_recursive(s[:-1])
def reverse_iterative(s: str) -> str:
reversed_s = []
for char in s:
reversed_s.insert(0, char)
return ''.join(reversed_s)
def reverse_pythonic(s: str) -> str:
... | from solution import reverse_string, reverse_recursive, reverse_iterative, reverse_pythonic, reverse_ultra_pythonic
def test_reverse_recursive():
assert reverse_recursive("hello") == "olleh"
assert reverse_recursive("") == ""
assert reverse_recursive("a") == "a"
assert reverse_recursive("ab") == "ba"
... | [
{
"docstring": null,
"function_declaration": "def reverse_recursive(s):",
"function_name": "reverse_recursive",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def reverse_iterative(s):",
"function_name": "reverse_iterative",
"parameter_list": "(s)"
},
... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def reverse_string(s: str) -> dict:\n \"\"\"\n This function takes a string s and returns a dictionary with the reversed string\n obtained by differe... | trial_gpt4o_4 | {
"original_instruction": "### Reversing a String using Different Algorithms\n\n#### Problem Statement\nYou are provided with four different methods for reversing a string: recursive, iterative, pythonic, and ultra pythonic. You need to implement the following Python function that takes a string `s` as input and uses... | 0.673714 | Data_Structure_2916 | C | [
"reverse_recursive",
"reverse_iterative",
"reverse_pythonic",
"reverse_ultra_pythonic",
"reverse_string"
] | 5 | [
[
"reverse_string",
"reverse_iterative"
],
[
"reverse_string",
"reverse_pythonic"
],
[
"reverse_string",
"reverse_recursive"
],
[
"reverse_string",
"reverse_ultra_pythonic"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | b45f650343e9e8d296f26e6fa5da1cce706be2c1 | 345503f790e2e1a9a539f819d1b0d54f65dc7761 | |||
v1.0 | complete | Data_Structure | Data_Structure_3110_C | def nearest_neighbor_classifier(x: tuple, train_set: dict) -> str:
""" Returns the class of the nearest point in the train_set to the point x.
>>> nearest_neighbor_classifier((1, 2), {(3, 4): "A", (1, 1): "B", (2, 2): "C"}) == "B"
>>> nearest_neighbor_classifier((1, 2), {(3, 4): "A"}) == "A"
>>> nearest... | import math
def euclidean_distance(point1, point2):
"""
Computes the Euclidean distance between two points.
"""
return math.sqrt(sum((p1 - p2) ** 2 for p1, p2 in zip(point1, point2)))
def nearest_neighbor_classifier(x, train_set):
"""
Returns the class of the nearest point in the train_set to ... | from solution import nearest_neighbor_classifier
def test_simple_case():
x = (1, 2)
train_set = {
(3, 4): "A",
(1, 1): "B",
(2, 2): "C"
}
assert nearest_neighbor_classifier(x, train_set) == "B"
def test_single_data_point():
x = (1, 2)
train_set = {
(3, 4): "A"
... | [] | [
0,
0,
0,
1,
1,
1,
0,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(point1, point2):\n return math.sqrt(sum((a - b) ** 2 for a, b in zip(point1, point2)))\n\ndef nearest_neighbor_classi... | trial_gpt4o_9 | {
"original_instruction": "### Nearest Neighbor Algorithm Implementation\n\n#### Background \nYou are working on a basic nearest neighbor classifier to predict the class of a given point based on the closest data points in a training set.\n\n#### Problem Statement\nWrite a function `nearest_neighbor_classifier(x, tra... | 0.62828 | Data_Structure_3110 | C | [
"euclidean_distance",
"nearest_neighbor_classifier"
] | 2 | [
[
"nearest_neighbor_classifier",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3377e1556b0d4ab51a8059e3f9611f3dc6c8f9d7 | 6e39a1a972937fefddbf09788160e7b0b4f818e8 | |||
v1.0 | complete | Data_Structure | Data_Structure_3398_C | def enhanced_interpolation_search(array: List[int], search_key: int) -> int:
"""
Enhanced Interpolation Search Algorithm with a fallback mechanism to binary search.
:param array: List[int] - The sorted array to be searched.
:param search_key: int - The key to be searched in the array.
:returns:... | from typing import List
def enhanced_interpolation_search(array: List[int], search_key: int) -> int:
"""
Enhanced Interpolation Search Algorithm with a fallback mechanism to binary search.
:param array: List[int] - The sorted array to be searched.
:param search_key: int - The key to be searched in... | from solution import enhanced_interpolation_search
def test_search_element_present():
assert enhanced_interpolation_search([10, 20, 30, 40, 50], 30) == 2
assert enhanced_interpolation_search([5, 10, 12, 14, 17, 20, 21], 14) == 3
assert enhanced_interpolation_search([1, 2, 3, 4, 5], 1) == 0
assert enhan... | [
{
"docstring": "Enhanced Interpolation Search Algorithm with a fallback mechanism to binary search.\n\n:param array: List[int] - The sorted array to be searched.\n:param search_key: int - The key to be searched in the array.\n:returns: int - Index of search_key in array if found, else -1.",
"function_declar... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef enhanced_interpolation_search(array: List[int], search_key: int) -> int:\n def binary_search(array: List[int], low: int, hig... | trial_gpt4o_1 | {
"original_instruction": "### Question: Enhanced Interpolation Search\n\nYou are tasked with implementing an enhanced version of the interpolation search algorithm that gracefully handles edge cases and optimizes performance for non-uniform distributions. Your implementation should switch to binary search if the for... | 0.531565 | Data_Structure_3398 | C | [
"enhanced_interpolation_search",
"binary_search"
] | 2 | [
[
"enhanced_interpolation_search",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 268f08699f51285b11c915c4ba367eb8c8b7ebbb | 319d8a5b2a09ba4cddc698638c5876b07ea011bc | |||
v1.0 | complete | Data_Structure | Data_Structure_2737_C | class TreeNode:
def __init__(self, key):
self.val = key
self.left = None
self.right = None
def insert(root: TreeNode, key: int) -> TreeNode:
"""
Insert a key into the BST.
>>> root = insert(None, 5)
>>> root.val
5
>>> root = insert(root, 3)
>>> root.left.val
... | class TreeNode:
def __init__(self, key):
self.val = key
self.left = None
self.right = None
def insert(root, key):
if root is None:
return TreeNode(key)
else:
if key < root.val:
root.left = insert(root.left, key)
else:
root.right = inse... | import pytest
from solution import TreeNode, insert, search, delete, kth_smallest
def test_insert_and_search():
root = None
root = insert(root, 5)
root = insert(root, 3)
root = insert(root, 7)
root = insert(root, 2)
root = insert(root, 4)
assert search(root, 5)
assert search(root, ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key):\n self.val = key\n self.left = None\n self.right = None\n\ndef insert(root, key):\n if r... | trial_gpt4o_0 | {
"original_instruction": "You are tasked to implement a Binary Search Tree (BST) with basic functionalities: insertion, search, and deletion. Additionally, you should implement a function to find the kth smallest element in the BST.\n\n### Requirements\n1. **Insertion**:\n ```python\n def insert(root: TreeNode, ... | 0.550895 | Data_Structure_2737 | C | [
"insert",
"search",
"minValueNode",
"delete",
"inorderTraversal",
"kth_smallest"
] | 6 | [
[
"delete",
"minValueNode"
],
[
"kth_smallest",
"inorderTraversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | a8a7134ee451970316abbcf7b9268304b4db808e | 4a90f1d6c2fbfd1cd2bbfd962279b20611982228 | |||
v1.0 | complete | Data_Structure | Data_Structure_2757_C | import random
from typing import Dict, List
def validate_chain(chain: Dict[str, Dict[str, float]]) -> bool:
"""
Validate the Markov chain.
Args:
chain (dict): The Markov chain represented as a dictionary of states and transition probabilities
Returns:
bool: True if the Markov chain is... | import random
def validate_chain(chain):
"""
Validate the Markov chain.
Args:
chain (dict): The Markov chain represented as a dictionary.
Returns:
bool: True if valid, False otherwise.
"""
for state, transitions in chain.items():
total_prob = sum(transitions.values())
... | from solution import validate_chain, simulate_markov_chain
def test_validate_chain_valid():
chain = {
'A': {'A': 0.6, 'E': 0.4},
'E': {'A': 0.7, 'E': 0.3}
}
assert validate_chain(chain) == True
def test_validate_chain_invalid_sum_greater_than_one():
chain = {
'A': {'A': 0.6, 'E... | [
{
"docstring": "Validate the Markov chain.\n\nArgs:\nchain (dict): The Markov chain represented as a dictionary.\n\nReturns:\nbool: True if valid, False otherwise.",
"function_declaration": "def validate_chain(chain):",
"function_name": "validate_chain",
"parameter_list": "(chain)"
},
{
"doc... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef validate_chain(chain):\n \"\"\"\n Validate the Markov chain.\n \n Args:\n chain (dict): The Markov chain represented as a ... | trial_gpt4o_0 | {
"original_instruction": "You are provided with a Markov Chain simulation function. A Markov Chain in this context is defined by a dictionary where keys represent states and values are dictionaries that map from the current state to the probabilities of transitioning to other states. \n\nYour task is to implement a ... | 0.49633 | Data_Structure_2757 | C | [
"validate_chain",
"simulate_markov_chain",
"_next_state"
] | 3 | [
[
"simulate_markov_chain",
"_next_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7928337ad5ffb54f1f343a810f4948942479509f | 442a33cc418c832cbb1f8353c0f7ec6924004666 | |||
v1.0 | complete | Data_Structure | Data_Structure_3106_C | def ordered_insert(array, val):
""" Inserts val into array such that the resultant array remains sorted.
>>> ordered_insert([1, 3, 5, 6], 5)
[1, 3, 5, 5, 6]
>>> ordered_insert([1, 3, 5, 6], 2)
[1, 2, 3, 5, 6]
>>> ordered_insert([1, 3, 5, 6], 7)
[1, 3, 5, 6, 7]
>>> ordered_insert([1, 3, 5... | def search_insert(array, val):
"""
Binary search function to find the appropriate insert position.
"""
low, high = 0, len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == val:
return mid
elif array[mid] < val:
low = mid + 1
... | from solution import ordered_insert
def test_ordered_insert_existing_value():
assert ordered_insert([1, 3, 5, 6], 5) == [1, 3, 5, 5, 6]
def test_ordered_insert_middle():
assert ordered_insert([1, 3, 5, 6], 2) == [1, 2, 3, 5, 6]
def test_ordered_insert_end():
assert ordered_insert([1, 3, 5, 6], 7) == [1, ... | [
{
"docstring": "Binary search function to find the appropriate insert position.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "Inserts val into array such that the resultant array remains sorte... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "def search_insert(array, val):\n \"\"\"\n Binary search to find the insertion position for val in a sorted array.\n \"\"\"\n... | trial_gpt4o_2 | {
"original_instruction": "#### Context\nYou are tasked with implementing an efficient ordered insertion mechanism into a sorted array. To achieve this, you will use the provided `search_insert` function to find the correct position and then insert the element in that position while maintaining the array order.\n\n##... | 0.686317 | Data_Structure_3106 | C | [
"search_insert",
"ordered_insert"
] | 2 | [
[
"ordered_insert",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 38c566ff5dbef330d5a17ee7896f32d948909814 | 59c989b24bbcf684df5c08c929bbffce23f6ae1d | |||
v1.0 | complete | Data_Structure | Data_Structure_2583_C | def is_prime(num: int, k: int = 5) -> bool:
"""
Miller-Rabin primality test.
num: Number to test for primality.
k: Number of iterations for accuracy.
Determines if a number is prime using the Miller-Rabin test.
>>> is_prime(2)
True
>>> is_prime(18)
False
>>> is_prime(17)
... | import random
def is_prime(num, k=5):
"""
Miller-Rabin primality test.
num: Number to test for primality.
k: Number of iterations for accuracy.
"""
if num <= 1 or num == 4: return False
if num <= 3: return True
# Find d such that d * 2^r = num-1 for some r >= 1
d = num - 1
... | import pytest
from solution import is_prime, gen_prime, generate_key, encrypt, decrypt
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
def test_gen_prime(... | [
{
"docstring": "Miller-Rabin primality test.\nnum: Number to test for primality.\nk: Number of iterations for accuracy.",
"function_declaration": "def is_prime(num, k=5):",
"function_name": "is_prime",
"parameter_list": "(num, k=5)"
},
{
"docstring": "Generate a prime number with k bits.\nk:... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(num, k=5):\n \"\"\"\n Returns True if num is a prime number, False otherwise using Miller-Rabin test.\n k is the number... | trial_gpt4o_5 | {
"original_instruction": "### RSA Encryption with Enhanced Key Generation\n\n#### Problem Statement\nYou are tasked with implementing an RSA encryption system with an improved prime generation algorithm. The existing code uses a simple brute force method, which is inefficient. Your goal is to:\n\n1. Implement an opt... | 0.620392 | Data_Structure_2583 | C | [
"is_prime",
"gen_prime",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"gen_prime",
"is_prime"
],
[
"generate_key",
"gen_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c710b057a89c1f804924accc07930807917743f1 | 07950447ce9ff6806c1d5814567276370d6f90bf | |||
v1.0 | complete | Data_Structure | Data_Structure_3518_C | from typing import List
def search_insert(sorted_part: List[int], value: int) -> int:
"""
This function finds the position where the 'value' should be inserted
in the 'sorted_part' list to keep it sorted.
"""
def insertion_sort(array: List[int]) -> List[int]:
"""
Sorts the given list of intege... | from typing import List
def search_insert(sorted_part: List[int], value: int) -> int:
"""
This function finds the position where the 'value' should be inserted
in the 'sorted_part' list to keep it sorted.
"""
for i in range(len(sorted_part)):
if value < sorted_part[i]:
return i
... | from solution import insertion_sort
def test_insertion_sort_empty():
assert insertion_sort([]) == []
def test_insertion_sort_single_element():
assert insertion_sort([1]) == [1]
def test_insertion_sort_sorted():
assert insertion_sort([1, 2, 3, 4]) == [1, 2, 3, 4]
def test_insertion_sort_reverse():
... | [
{
"docstring": "This function finds the position where the 'value' should be inserted\nin the 'sorted_part' list to keep it sorted.",
"function_declaration": "def search_insert(sorted_part, value):",
"function_name": "search_insert",
"parameter_list": "(sorted_part, value)"
},
{
"docstring":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(array: List[int]) -> List[int]:\n \"\"\"\n Sorts the input list using the insertion sort algorithm.\n \... | trial_gpt4o_2 | {
"original_instruction": "**Context**:\nYou work for a company that deals with various datasets and requires efficient sorting algorithms. While modern algorithms like quicksort and mergesort are generally preferred due to their better performance on large datasets, certain small or nearly-sorted datasets are still ... | 0.649719 | Data_Structure_3518 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 484b64f9e2b568b0aea225efbe9f268a6f5b2217 | ac6769e4ab544482114eb211096867fbddeb63f7 | |||
v1.0 | complete | Data_Structure | Data_Structure_3033_C | def simplified_diffie_hellman_key_exchange(a: int, p: int) -> bool:
""" Implementation of a simplified Diffie-Hellman key exchange.
This function will simulate a Diffie-Hellman key exchange between two users based on the given base number `a` and prime number `p`.
Args:
a (int): A base number that mus... | from sympy import isprime
from random import randint
def gcd(a, b):
while b:
a, b = b, a % b
return a
def is_primitive_root(a, p):
if not isprime(p):
return False
required_set = set(num for num in range(1, p) if gcd(num, p) == 1)
actual_set = set(pow(a, powers, p) for powers ... | import pytest
from solution import simplified_diffie_hellman_key_exchange
def test_simplified_diffie_hellman_key_exchange_valid_case():
assert simplified_diffie_hellman_key_exchange(3, 17) == True
def test_invalid_prime():
with pytest.raises(ValueError, match="p is not a prime number."):
simplified_di... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def is_primitive_root(a, p):",
"function_name": "is_primitive_root",
"parameter_list": "(a, p)"
},
{
"docstri... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(n):\n \"\"\" Check if a number is prime \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n ... | trial_gpt4o_1 | {
"original_instruction": "### Question: Implementation of a Simplified Diffie-Hellman Key Exchange\n\nYou have been provided with the basis of the Diffie-Hellman key exchange algorithm principles. Your task is to implement a simplified version of the Diffie-Hellman key exchange process by following the guidelines pr... | 0.531169 | Data_Structure_3033 | C | [
"gcd",
"is_primitive_root",
"simplified_diffie_hellman_key_exchange"
] | 3 | [
[
"is_primitive_root",
"gcd"
],
[
"simplified_diffie_hellman_key_exchange",
"is_primitive_root"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 2eb5e178b6605ea2d5d47545b1787c5e2363ad1f | 6ac147d9a8175a04e3bd5b5011dfd69ddd5cfa1d | |||
v1.0 | complete | Data_Structure | Data_Structure_3135_C | import math
from typing import Tuple, Dict, Any, Union
def distance(x: Tuple[float, ...], y: Tuple[float, ...]) -> float:
""" Calculates the Euclidean distance between two vectors x and y. """
assert len(x) == len(y), "The vectors must have the same length"
return math.sqrt(sum((xi - yi) ** 2 for xi, yi in... | import math
def distance(x, y):
"""Calculates the Euclidean distance between vector x and y."""
assert len(x) == len(y), "The vectors must have the same length"
return math.sqrt(sum((xi - yi) ** 2 for xi, yi in zip(x, y)))
def classify_point(new_point, training_set):
"""
Classifies a new point bas... | from solution import classify_point
def test_classify_point_typical():
assert classify_point((1.0, 2.0), {(0.0, 1.0): 'A', (2.0, 3.0): 'B', (1.0, 3.0): 'A'}) == 'A'
def test_classify_point_typical_2():
assert classify_point((1.5, 2.5), {(1.0, 2.0): 'C', (2.0, 3.0): 'D'}) == 'C'
def test_classify_point_edge_c... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(x, y):\n \"\"\"Calculates the Euclidean distance between vector x and y.\"\"\"\n assert len(x) == len(y), \"The vectors must... | trial_gpt4o_2 | {
"original_instruction": "You are given a dataset of points in a multidimensional space represented as (x, y, z, ...). You need to implement the Nearest Neighbor algorithm to classify a new data point based on this dataset.\n\n### Task\n\nWrite a function `classify_point(new_point, training_set)` that takes the foll... | 0.602843 | Data_Structure_3135 | C | [
"distance",
"classify_point"
] | 2 | [
[
"classify_point",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 480c2e41434d63b2512d5fe40f836e15579ae093 | 2b5c55b253ce952a2c354e9da6673e97e4b89a3d | |||
v1.0 | complete | Data_Structure | Data_Structure_1599_C | class TreeNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.left = None
self.right = None
def insert(root, key, value):
"""
Insert a node with key and value into the BST.
If key already exists, update the value.
Parameters:
root (T... | class TreeNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.left = None
self.right = None
def insert(root, key, value):
if root is None:
return TreeNode(key, value)
elif key < root.key:
root.left = insert(root.left, key, value)
... | import pytest
from solution import TreeNode, insert, search, delete
def test_insert_and_search():
root = None
root = insert(root, 50, "John Doe")
root = insert(root, 30, "Jane Smith")
root = insert(root, 70, "Emily Davis")
assert search(root, 50) == "John Doe"
assert search(root, 30) == "Jane S... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.left = None\n self.right = None\... | trial_gpt4o_1 | {
"original_instruction": "### Scenario\nA company is developing a software to manage their dynamically changing contact list. The contact list should allow for efficient searching, adding, and removing of contact names based on their unique IDs. Each contact is represented as a unique ID associated with a name.\n\n#... | 0.46921 | Data_Structure_1599 | C | [
"insert",
"search",
"find_min",
"delete"
] | 4 | [
[
"delete",
"find_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 78d80b6a3ece006cafe72d86fd5cf04347630bcd | 6f08f56f77116ebc320c352b8f6a62d700ad3640 | |||
v1.0 | complete | Data_Structure | Data_Structure_3998_C | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Uses binary search to find the index where `val` should be inserted to keep `array` sorted.
"""
pass
def insertion_sort(nums: List[int]) -> List[int]:
"""
Sorts the list of integers using the optimized insertion ... | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Uses binary search to find the index where `val` should be inserted to keep `array` sorted.
"""
low, high = 0, len(array)
while low < high:
mid = (low + high) // 2
if array[mid] < val:
... | from solution import insertion_sort, search_insert
def test_insertion_sort_example_1():
assert insertion_sort([4, 2, 6, 1, 3]) == [1, 2, 3, 4, 6]
def test_insertion_sort_example_2():
assert insertion_sort([10, 5, 3, 8, 6]) == [3, 5, 6, 8, 10]
def test_insertion_sort_empty():
assert insertion_sort([]) == ... | [
{
"docstring": "Uses binary search to find the index where `val` should be inserted to keep `array` sorted.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "Sorts the list of integers using the o... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n A helper function that uses binary search to determine the c... | trial_gpt4o_2 | {
"original_instruction": "**Title**: Optimized Insertion Sort using Binary Search\n\n**Scenario**:\nYou are working with a financial application that routinely sorts small lists of transactions. Given the frequency and nature of your dataset, you determine that optimizing the Insertion Sort algorithm—by using Binary... | 0.661914 | Data_Structure_3998 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3edbac8d592c70f520f1a8cb2f5c2005a60ffb19 | 52b9ec3add1990539567f4f9c3809c0a00e3b151 | |||
v1.0 | complete | Data_Structure | Data_Structure_3100_C | def get_flag(flags: int, index: int) -> bool:
""" Check if the feature at position `index` is enabled.
>>> get_flag(0b1010, 1)
True
>>> get_flag(0b1010, 2)
False
>>> get_flag(0b1010, 3)
True
>>> get_flag(0b1010, 0)
False
"""
def enable_flag(flags: int, index: int) -> int:
""... | def get_flag(flags, index):
return (flags & (1 << index)) != 0
def enable_flag(flags, index):
return flags | (1 << index)
def disable_flag(flags, index):
return flags & ~(1 << index)
def update_flag(flags, index, state):
if state:
return enable_flag(flags, index)
else:
return disa... | from solution import get_flag, enable_flag, disable_flag, update_flag
def test_get_flag():
assert get_flag(0b1010, 1) == True
assert get_flag(0b1010, 2) == False
assert get_flag(0b1010, 3) == True
assert get_flag(0b1010, 0) == False
def test_enable_flag():
assert enable_flag(0b0000, 1) == 0b0010
... | [
{
"docstring": null,
"function_declaration": "def get_flag(flags, index):",
"function_name": "get_flag",
"parameter_list": "(flags, index)"
},
{
"docstring": null,
"function_declaration": "def enable_flag(flags, index):",
"function_name": "enable_flag",
"parameter_list": "(flags,... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_flag(flags, index):\n \"\"\"\n Check if the feature at position 'index' is enabled.\n \"\"\"\n return (flags & (1 << index)) != 0\n\ndef e... | trial_gpt4o_2 | {
"original_instruction": "#### Problem Statement\n\nYou are given an integer that represents a sequence of flags, where each bit indicates the state of a specific feature (1 means \"enabled\" and 0 means \"disabled\"). Your task is to implement four functions to manipulate these flags:\n\n1. `get_flag(flags, index)`... | 0.455875 | Data_Structure_3100 | C | [
"get_flag",
"enable_flag",
"disable_flag",
"update_flag"
] | 4 | [
[
"update_flag",
"disable_flag"
],
[
"update_flag",
"enable_flag"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0195707b340ce96dd9a7874c7b52c411fa695793 | 8ab11eecd6ff88d09e1ee8a828d533372211c449 | |||
v1.0 | complete | Data_Structure | Data_Structure_3548_C | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort_simulation(arr: list[int], simulation: bool=False) -> list[int]:
""" Sorts the given list ... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort_simulation(arr, simulation=False):
"""
Sorts the given list using the Bogo Sort algori... | from solution import bogo_sort_simulation
def test_simple_unsorted_array():
assert bogo_sort_simulation([3, 2, 5, 1, 4], simulation=False) == [1, 2, 3, 4, 5]
def test_with_simulation():
# This test does not assert the printed result but checks functional behavior
assert bogo_sort_simulation([3, 2, 1], sim... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the given list using the Bogo Sort algorithm.\n\nParameters:\narr (list[int]): The list of intege... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef bogo_sort_simulation(arr: list[int], simulation: bool=False) -> list[int]:\n \"\"\"\n Sorts the given list using Bogo Sort algorith... | trial_gpt4o_2 | {
"original_instruction": "### Bogo Sort Simulation\n\n#### Context\nBogo Sort, also known as permutation sort, is an inefficient sorting algorithm that randomly shuffles an array until it finds a sorted permutation. Despite its inefficiency, Bogo Sort can be a useful educational tool for understanding the importance... | 0.640199 | Data_Structure_3548 | C | [
"is_sorted",
"bogo_sort_simulation"
] | 2 | [
[
"bogo_sort_simulation",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4255d0aa3347fd8054eb7e97f25835ec98b3f185 | 761c208ab64e088ac69b13596f18101be8f4b764 | |||
v1.0 | complete | Data_Structure | Data_Structure_3144_C | from typing import List
def optimized_hosoya_triangle(height: int) -> List[List[int]]:
""" Generate the Hosoya Triangle up to the specified height.
Args:
height (int): The height of the Hosoya Triangle.
Returns:
List[List[int]]: A list of lists representing the Hosoya Triangle.
Example:
... | from typing import List
def optimized_hosoya_triangle(height: int) -> List[List[int]]:
if height == 0:
return [[1]]
memo = {}
def hosoya(i, j):
if (i, j) in memo: # Use memoization to avoid recalculating
return memo[(i, j)]
if (j == 0) and (i in {0, 1}):
... | from solution import optimized_hosoya_triangle, print_optimized_hosoya_triangle
def test_optimized_hosoya_triangle_height_0():
assert optimized_hosoya_triangle(0) == [[1]]
def test_optimized_hosoya_triangle_height_1():
assert optimized_hosoya_triangle(1) == [[1], [1, 1]]
def test_optimized_hosoya_triangle_he... | [
{
"docstring": null,
"function_declaration": "def optimized_hosoya_triangle(height):",
"function_name": "optimized_hosoya_triangle",
"parameter_list": "(height)"
},
{
"docstring": null,
"function_declaration": "def print_optimized_hosoya_triangle(height):",
"function_name": "print_op... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef optimized_hosoya_triangle(height: int) -> List[List[int]]:\n if height == 0:\n return [[1]]\n \n memo = {}\n ... | trial_gpt4o_0 | {
"original_instruction": "### Question:\n\n#### Context:\nYou are required to implement an optimized version of the Hosoya Triangle, a triangular number arrangement where every element is the sum of the two elements directly above it (if they exist). The first two rows are explicitly defined.\n\n- 1\n- 1 1\n\nThe ... | 0.522537 | Data_Structure_3144 | C | [
"optimized_hosoya_triangle",
"print_optimized_hosoya_triangle"
] | 2 | [
[
"print_optimized_hosoya_triangle",
"optimized_hosoya_triangle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bcbc5e7019ae05d1473858af7707efc1f6254941 | eb9b8e6473fb382c92d5cc362824018249f9ad89 | |||
v1.0 | complete | Data_Structure | Data_Structure_2693_C | import random
from typing import Tuple
def generate_key(k: int, seed: int = None) -> Tuple[int, int, int]:
""" Generate RSA keys.
Args:
k (int): Number of bits in the modulus n.
seed (int, optional): Seed for random number generator.
Returns:
Tuple[int, int, int]: A tuple (n, e, d) where n is ... | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(length):
p = random.getrandbits(length)
p |= (1 << length - 1) | 1
return p
def generate_prime_number(length):
p = generate_prime_candidate(length)
while not isprime(p):
p = generate_prime_candidate(length)
... | from solution import generate_key, encrypt, decrypt
def test_key_generation():
n, e, d = generate_key(16, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_encryption_decryption():
n, e, d = generate_key(16, seed=42)
data = 42
encrypted_data = ... | [
{
"docstring": null,
"function_declaration": "def generate_prime_candidate(length):",
"function_name": "generate_prime_candidate",
"parameter_list": "(length)"
},
{
"docstring": null,
"function_declaration": "def generate_prime_number(length):",
"function_name": "generate_prime_numbe... | [
0,
0,
0,
1,
1,
1,
1,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_key(k: int, seed: int = None) -> (int, int, int):\n if seed is not None:\n ran... | trial_gpt4o_9 | {
"original_instruction": "### RSA Encryption Key Generation and Encryption/Decryption Functions\n\n**Context**:\nYou will be designing and implementing secure digital communication using the RSA algorithm. The RSA algorithm is widely used for securing sensitive data, especially in internet-based communications. Your... | 0.779167 | Data_Structure_2693 | C | [
"generate_prime_candidate",
"generate_prime_number",
"gcd",
"generate_key",
"encrypt",
"decrypt"
] | 6 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 3 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | cd609f21d64ae19ed6eb07dcc236397d5f10ef6c | 3f14fb827e5deb68a94813dcce7b07a3cf7d2000 | |||
v1.0 | complete | Data_Structure | Data_Structure_2763_C | from typing import List
def maximum_water_flow(pipes: List[List[int]]) -> int:
""" Calculate the maximum water flow in a given pipe network from source to sink.
pipes: A list of lists (2D list) representing the network capacity.
pipes[i][j] represents the pipe capacity from reservoir i to reservoi... | from collections import deque
def bfs(rGraph, s, t, parent):
visited = [False] * len(rGraph)
queue = deque([s])
visited[s] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(rGraph[u]):
if visited[v] == False and capacity > 0:
... | from solution import maximum_water_flow
def test_example_case():
pipes = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_water_flow(pipes) == 23
def test_no_path(... | [
{
"docstring": null,
"function_declaration": "def bfs(rGraph, s, t, parent):",
"function_name": "bfs",
"parameter_list": "(rGraph, s, t, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_water_flow(pipes):",
"function_name": "maximum_water_flow",
"parameter_li... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(residual_capacity, source, sink, parent):\n n = len(residual_capacity)\n visited = [False] * n\n queue = deq... | trial_gpt4o_2 | {
"original_instruction": "### Maximum Water Flow in a Pipe Network\n\n#### Scenario\nYou are given a network of pipes linking various reservoirs. Each pipe has a certain capacity which denotes the maximum amount of water it can transfer per unit time. Your task is to determine the maximum possible amount of water th... | 0.697842 | Data_Structure_2763 | C | [
"bfs",
"maximum_water_flow"
] | 2 | [
[
"maximum_water_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | debcb737e18b89d3892eb644cde17c8e8f089792 | b63155a9913bf0b7b4006ed89f4afec3aeb3d642 | |||
v1.0 | complete | Data_Structure | Data_Structure_3524_C | from typing import List
def find_all_primitive_roots(n: int) -> List[int]:
""" Write a function that, given a positive integer `n`, finds all primitive roots of `n`.
>>> find_all_primitive_roots(10) == []
>>> find_all_primitive_roots(13) == [2, 6, 7, 11]
>>> find_all_primitive_roots(1) == [0]
"""
... | from typing import List
import math
def gcd(a, b):
while b:
a, b = b, a % b
return a
def euler_totient(n):
amount = 0
for k in range(1, n + 1):
if math.gcd(n, k) == 1:
amount += 1
return amount
def find_all_primitive_roots(n: int) -> List[int]:
if n == 1:
r... | from solution import find_all_primitive_roots
def test_find_all_primitive_roots():
assert find_all_primitive_roots(1) == [0]
assert find_all_primitive_roots(2) == [1]
assert find_all_primitive_roots(3) == [2]
assert find_all_primitive_roots(4) == []
assert find_all_primitive_roots(5) == [2, 3]
... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": null,
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom math import gcd\n\ndef euler_totient(n: int) -> int:\n \"\"\"\n Compute Euler's Totient function for a given n\n \"\"\"... | trial_gpt4o_2 | {
"original_instruction": "### Task:\nWrite a function that, given a positive integer `n`, finds all primitive roots of `n`.\n\n### Function Signature:\n```python\ndef find_all_primitive_roots(n: int) -> List[int]:\n```\n\n### Input:\n- `n`: A positive integer (1 ≤ n ≤ 10^4).\n\n### Output:\n- A list of integers repr... | 0.554729 | Data_Structure_3524 | C | [
"gcd",
"euler_totient",
"find_all_primitive_roots"
] | 3 | [
[
"find_all_primitive_roots",
"euler_totient"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 34537b79ed96674d6307550720a5075786d0fc89 | 8e8985ad46bf1c3c427b2aec357a25703d976eac | |||
v1.0 | complete | Data_Structure | Data_Structure_4019_C | def gcd(a: int, b: int) -> int:
"""
Returns the greatest common divisor (GCD) of a and b.
>>> gcd(48, 18)
6
>>> gcd(54, 24)
6
"""
pass
def lcm(a: int, b: int) -> int:
"""
Returns the least common multiple (LCM) of a and b.
>>> lcm(4, 5)
20
>>> lcm(6, 8)
24
""... | import math
def gcd(a, b):
"""
Returns the greatest common divisor (GCD) of a and b.
"""
while b:
a, b = b, a % b
return abs(a)
def lcm(a, b):
"""
Returns the least common multiple (LCM) of a and b.
"""
return abs(a * b) // gcd(a, b)
def trailing_zero(x):
"""
Retur... | from solution import gcd, lcm, trailing_zero, gcd_bit
def test_gcd():
assert gcd(48, 18) == 6
assert gcd(54, 24) == 6
assert gcd(101, 103) == 1
assert gcd(-48, 18) == 6
assert gcd(0, 5) == 5
assert gcd(5, 0) == 5
def test_lcm():
assert lcm(4, 5) == 20
assert lcm(6, 8) == 24
assert ... | [
{
"docstring": "Returns the greatest common divisor (GCD) of a and b.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the least common multiple (LCM) of a and b.",
"function_declaration": "def lcm(a, b):",
"fun... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"\n Returns the greatest common divisor of a and b using Euclid's algorithm.\n \"\"\"\n while b:\n a, b = b, a % b\n ... | trial_gpt4o_2 | {
"original_instruction": "#### Context\nYou are developing a system that heavily relies on mathematical operations related to integers. As part of this system, you need robust implementations for calculating the greatest common divisor (GCD), the least common multiple (LCM), and counting trailing zeros in the binary... | 0.78048 | Data_Structure_4019 | C | [
"gcd",
"lcm",
"trailing_zero",
"gcd_bit"
] | 4 | [
[
"gcd_bit",
"trailing_zero"
],
[
"lcm",
"gcd"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2f91e322ffb591a638d99844a81bf9f84ea0b487 | 19f3a4c97853857155c5dd2285c03a3443b84a23 | |||
v1.0 | complete | Data_Structure | Data_Structure_4379_C | from typing import List
def inorder_from_pre_post(preorder: List[int], postorder: List[int]) -> List[int]:
""" Given preorder and postorder traversal of a full binary tree, return the inorder traversal.
>>> inorder_from_pre_post([1, 2, 4, 5, 3, 6, 7], [4, 5, 2, 6, 7, 3, 1])
[4, 2, 5, 1, 6, 3, 7]
>>> i... | from typing import List
class TreeNode:
def __init__(self, value=0):
self.value = value
self.left = None
self.right = None
def build_tree_from_pre_post(preorder: List[int], postorder: List[int]) -> TreeNode:
if not preorder or not postorder:
return None
root = TreeNode(pre... | from solution import inorder_from_pre_post
def test_inorder_from_pre_post_case1():
preorder = [1, 2, 4, 5, 3, 6, 7]
postorder = [4, 5, 2, 6, 7, 3, 1]
expected = [4, 2, 5, 1, 6, 3, 7]
assert inorder_from_pre_post(preorder, postorder) == expected
def test_inorder_from_pre_post_case2():
preorder = [2... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\ndef c... | trial_gpt4o_2 | {
"original_instruction": "You are given two arrays, `preorder` and `postorder`, of integers representing the preorder and postorder traversal of a full binary tree respectively. Your task is to reconstruct the binary tree and return its inorder traversal.\n\n### Function Signature\n```python\ndef inorder_from_pre_po... | 0.485517 | Data_Structure_4379 | C | [
"build_tree_from_pre_post",
"inorder_traversal",
"inorder_from_pre_post"
] | 3 | [
[
"inorder_from_pre_post",
"build_tree_from_pre_post"
],
[
"inorder_from_pre_post",
"inorder_traversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 5953fc2d271cd98fb080f6396e0406dd6c715393 | dca52a100d25027f148b4adc40744f87c47b53af | |||
v1.0 | complete | Data_Structure | Data_Structure_3830_C | import math
from typing import Tuple, Dict
def distance(x: Tuple[float, ...], y: Tuple[float, ...]) -> float:
"""
Calculate the Euclidean distance between two n-dimensional points x and y.
>>> distance((1.0, 2.0), (1.0, 2.0))
0.0
>>> distance((1.0, 2.0), (4.0, 6.0))
5.0
"""
pass
def ne... | import math
def distance(x, y):
"""
Calculate the Euclidean distance between two n-dimensional points x and y.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(x, y)))
def nearest_neighbor(x, tSet):
"""
Find the classification of the nearest neighbor to the point x from the set tSet.
... | from solution import distance, nearest_neighbor
def test_distance_same_point():
assert distance((1.0, 2.0), (1.0, 2.0)) == 0.0
def test_distance_different_points():
assert distance((1.0, 2.0), (4.0, 6.0)) == 5.0
def test_nearest_neighbor_single_point():
tSet = {(2.0, 3.0): 'A'}
assert nearest_neighbo... | [
{
"docstring": "Calculate the Euclidean distance between two n-dimensional points x and y.",
"function_declaration": "def distance(x, y):",
"function_name": "distance",
"parameter_list": "(x, y)"
},
{
"docstring": "Find the classification of the nearest neighbor to the point x from the set t... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(x, y):\n \"\"\"\n Returns the Euclidean distance between points x and y.\n \"\"\"\n return math.sqrt(sum((xi - yi) ** ... | trial_gpt4o_2 | {
"original_instruction": "### Nearest Neighbor Classification Task\n\n#### Scenario\nYou are tasked with implementing a simpler form of a classifier which uses the Nearest Neighbor algorithm. This classifier will be used in a small-scale recommendation system.\n\n#### Objective\nYour task is to implement a function ... | 0.714598 | Data_Structure_3830 | C | [
"distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f4c4559f4afca26a5a49f60e10fc73d2e099653a | 8d0f8004aa9e4a734a4c24492495ed1451acc6d1 | |||
v1.0 | complete | Data_Structure | Data_Structure_4402_C | def optimized_bucket_sort(arr: list[float]) -> list[float]:
""" Sorts a list of floating-point numbers in the range [0, 1) using the Bucket Sort algorithm.
>>> optimized_bucket_sort([0.23, 0.45, 0.12, 0.89, 0.25]) == [0.12, 0.23, 0.25, 0.45, 0.89]
>>> optimized_bucket_sort([0.5, 0.25, 0.75, 0.1, 0.9, 0.60])... | def insertion_sort(arr):
"""
Perform an insertion sort on the list `arr`.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def optimized_bucket_sort(a... | from solution import optimized_bucket_sort
def test_optimized_bucket_sort_sorted_input():
assert optimized_bucket_sort([0.1, 0.2, 0.3, 0.4, 0.5]) == [0.1, 0.2, 0.3, 0.4, 0.5]
def test_optimized_bucket_sort_reverse_sorted():
assert optimized_bucket_sort([0.5, 0.4, 0.3, 0.2, 0.1]) == [0.1, 0.2, 0.3, 0.4, 0.5]
... | [
{
"docstring": "Perform an insertion sort on the list `arr`.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts a list of floating-point numbers in the range [0, 1) using the\nBucket Sort algorithm.",
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insertion_sort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while j >= 0 and key < arr[j]:\n arr[j... | trial_gpt4o_2 | {
"original_instruction": "#### Background Scenario\n\nYou are part of a team developing a high-frequency trading application where actions must be taken on financial markets in real-time. Given a series of trades occurring in real-time, it's crucial to maintain a sorted list of trade values to ensure the accuracy of... | 0.602894 | Data_Structure_4402 | C | [
"insertion_sort",
"optimized_bucket_sort"
] | 2 | [
[
"optimized_bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9569950496efdb9ae77d371106ba4f1e1fb95e61 | 30fbac7bd819a68cc48cf0e7cca031bef31abf74 | |||
v1.0 | complete | Data_Structure | Data_Structure_3210_C | from typing import List
def optimized_merge_sort(arr: List[int]) -> List[int]:
""" Sort an array of integers in ascending order using an optimized version of merge sort.
The function should aim to:
1. Implement the basic merge sort algorithm.
2. Optimize the merge step to reduce additional space comple... | from typing import List
def insertion_sort(arr: List[int], left: int, right: int) -> None:
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def merge(arr: List[int], lef... | from solution import optimized_merge_sort
def test_optimized_merge_sort_empty():
assert optimized_merge_sort([]) == []
def test_optimized_merge_sort_single_element():
assert optimized_merge_sort([1]) == [1]
def test_optimized_merge_sort_sorted():
assert optimized_merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, ... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def merge(arr, left, middle, right):",
"function_name": "merge",
"param... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[int], left: int, right: int):\n for i in range(left + 1, right + 1):\n key = arr[i]\n ... | trial_gpt4o_1 | {
"original_instruction": "### Question: Implementing and Optimizing Merge Sort\n\n#### Context:\nYou are tasked with implementing a custom sorting function for a large-scale application where stability (maintaining the relative order of records with equal keys) is crucial. The application frequently processes large ... | 0.606633 | Data_Structure_3210 | C | [
"insertion_sort",
"merge",
"optimized_merge_sort_helper",
"optimized_merge_sort"
] | 4 | [
[
"optimized_merge_sort",
"optimized_merge_sort_helper"
],
[
"optimized_merge_sort_helper",
"insertion_sort"
],
[
"optimized_merge_sort_helper",
"merge"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 33ec22e947fcc6a5c61c1c9157231c642ea04608 | 57838fac08dc60d30a38c691c307b51f49649350 | |||
v1.0 | complete | Data_Structure | Data_Structure_4344_C | from typing import List
def power_of_twos(arr: List[int]) -> List[bool]:
"""
Determine if each integer in the array is a power of two.
:param arr: List[int] - A list of integers to check.
:return: List[bool] - A list with boolean values indicating whether each integer is a power of two.
"""
pa... | from typing import List
def is_power_of_two(n: int) -> bool:
"""
Check if a given integer is a power of two.
:param n: int - Integer to check.
:return: bool - Whether the integer is a power of two.
"""
if n <= 0:
return False
return (n & (n - 1)) == 0
def power_of_twos(arr: List[i... | from solution import power_of_twos
def test_power_of_twos_with_mixed_input():
assert power_of_twos([1, 2, 3, 4, 5]) == [True, True, False, True, False]
def test_power_of_twos_with_only_powers_of_two():
assert power_of_twos([16, 32, 64, 128, 256]) == [True, True, True, True, True]
def test_power_of_tw... | [
{
"docstring": "Check if a given integer is a power of two.\n\n:param n: int - Integer to check.\n:return: bool - Whether the integer is a power of two.",
"function_declaration": "def is_power_of_two(n):",
"function_name": "is_power_of_two",
"parameter_list": "(n)"
},
{
"docstring": "Determi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef power_of_twos(arr: List[int]) -> List[bool]:\n \"\"\"\n Determine if each integer in the array is a power of two.\n\n ... | trial_gpt4o_2 | {
"original_instruction": "Power of Two Array Check\n\n#### Context\nGiven the need to frequently verify whether elements in an array are powers of two, it's essential to extend the individual power-of-two check to work on arrays efficiently.\n\n#### Objective\nWrite a function `power_of_twos(arr)` that, given an arr... | 0.698782 | Data_Structure_4344 | C | [
"is_power_of_two",
"power_of_twos"
] | 2 | [
[
"power_of_twos",
"is_power_of_two"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b842343cc15a9f83f2b7fad49385ac0c486740dc | 03f66895678e17ca3e747277cdf793398c9816c6 | |||
v1.0 | complete | Data_Structure | Data_Structure_3138_C | from typing import Tuple
def secure_diffie_hellman(a: int, p: int) -> Tuple[int, int]:
"""
Implement a secure communication using the Diffie-Hellman key exchange algorithm.
Arguments:
a -- A primitive root of prime number `p`.
p -- A large prime number.
Returns:
A tuple containing... | import random
from typing import Tuple
def modular_exponentiation(base: int, ex: int, mod: int) -> int:
"""
Perform modular exponentiation.
base^ex % mod
"""
result = 1
base = base % mod
while ex > 0:
if (ex % 2) == 1: # If ex is odd, multiply base with the result
resul... | from solution import secure_diffie_hellman
def test_secure_diffie_hellman_example():
a = 2
p = 23
shared_key_alice, shared_key_bob = secure_diffie_hellman(a, p)
assert shared_key_alice == shared_key_bob, "Shared keys do not match!"
def test_secure_diffie_hellman_small_prime():
a = 5
p = 19
... | [
{
"docstring": "Perform modular exponentiation.\nbase^ex % mod",
"function_declaration": "def modular_exponentiation(base, ex, mod):",
"function_name": "modular_exponentiation",
"parameter_list": "(base, ex, mod)"
},
{
"docstring": "Perform Diffie-Hellman key exchange algorithm to generate\n... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Tuple\nimport random\n\ndef mod_exp(base: int, exp: int, mod: int) -> int:\n \"\"\"\n Modular exponentiation: (base^exp) % mod\n \... | trial_gpt4o_2 | {
"original_instruction": "### Secure Communication System with Diffie-Hellman\n\nIn this task, you will implement a secure communication using the Diffie-Hellman key exchange algorithm. The algorithm will enable two parties, Alice and Bob, to generate a shared secret key that can be used for encrypting their message... | 0.454352 | Data_Structure_3138 | C | [
"modular_exponentiation",
"secure_diffie_hellman"
] | 2 | [
[
"secure_diffie_hellman",
"modular_exponentiation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 771c7885bb0859c8b5635af29eca7928e3e850a4 | 34c7581f64ba1def44c3683fe747b19d8605fb6c | |||
v1.0 | complete | Data_Structure | Data_Structure_3025_C | from typing import List
def enhanced_radix_sort(arr: List[int]) -> List[int]:
""" Sort a list of non-negative integers using Enhanced Radix Sort.
>>> enhanced_radix_sort([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66, 75, 90, 170, 802]
>>> enhanced_radix_sort([333, 3, 5555, 55, 5])
[3,... | def enhanced_radix_sort(arr):
"""
Sorts a list of non-negative integers using Radix Sort.
:param arr: List of non-negative integers
:return: List of integers sorted in ascending order
"""
if len(arr) == 0:
return arr
max_num = max(arr)
exp = 1
while max_num... | from solution import enhanced_radix_sort
def test_radix_sort_basic():
input_list = [170, 45, 75, 90, 802, 24, 2, 66]
assert enhanced_radix_sort(input_list) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_with_duplicates():
input_list = [5, 3, 5, 3, 2, 1, 4, 5, 1]
assert enhanced_radix_sort(in... | [
{
"docstring": "Sorts a list of non-negative integers using Radix Sort.\n\n:param arr: List of non-negative integers\n:return: List of integers sorted in ascending order",
"function_declaration": "def enhanced_radix_sort(arr):",
"function_name": "enhanced_radix_sort",
"parameter_list": "(arr)"
},
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n \"\"\"\n A helper function to perform counting sort based on the exponent value.\n It sorts the array according to the... | trial_gpt4o_2 | {
"original_instruction": "### Coding Exercise: Implement Enhanced Radix Sort\n\n#### Context\nYou have been tasked with sorting a large list of non-negative integers efficiently. The existing sorting algorithms are either too slow for large inputs or not well-suited for integers with a variable number of digits. Rad... | 0.688582 | Data_Structure_3025 | C | [
"enhanced_radix_sort",
"counting_sort"
] | 2 | [
[
"enhanced_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ac0f9c8b08c5c71e7d779f384494ad66583eec82 | cec11da01f8f5c9d2911f1124e0edde93af15370 | |||
v1.0 | complete | Data_Structure | Data_Structure_4342_C | import random
def __choose_state(prob_dist):
"""
Helper function to choose the next state based on a probability distribution.
"""
states = list(prob_dist.keys())
probabilities = list(prob_dist.values())
return random.choices(states, probabilities)[0]
def generate_markov_sequence(chain, initia... | import random
def __choose_state(prob_dist):
"""
Helper function to choose the next state based on a probability distribution.
"""
states = list(prob_dist.keys())
probabilities = list(prob_dist.values())
return random.choices(states, probabilities)[0]
def generate_markov_sequence(chain, initia... | from solution import generate_markov_sequence
def test_generate_sequence_basic_case():
chain = {
'A': {'A': 0.6, 'E': 0.4},
'E': {'A': 0.7, 'E': 0.3}
}
initial_state = 'A'
transitions = 5
sequence = generate_markov_sequence(chain, initial_state, transitions)
assert len(sequence... | [
{
"docstring": "Helper function to choose the next state based on a probability distribution.",
"function_declaration": "def __choose_state(prob_dist):",
"function_name": "__choose_state",
"parameter_list": "(prob_dist)"
},
{
"docstring": "Generates a sequence of states given a Markov chain,... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_markov_sequence(chain, initial_state, transitions):\n \"\"\"\n Generates a sequence of states based on the given Markov ch... | trial_gpt4o_1 | {
"original_instruction": "You are tasked with extending the functionality of a Markov chain. Specifically, you need to implement a function that generates a finite sequence of states given an initial state and a predefined number of transitions.\n\n### Requirements\n* Implement a function `generate_markov_sequence(c... | 0.522216 | Data_Structure_4342 | C | [
"__choose_state",
"generate_markov_sequence"
] | 2 | [
[
"generate_markov_sequence",
"__choose_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6104e7464d956196a03dfe23d046a3fe59963944 | d86e0b35c2eaf53cfa792666bd1575b65a8c94e4 | |||
v1.0 | complete | Data_Structure | Data_Structure_3831_C | def gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor of integers a and b using Euclid's Algorithm.
:param a: First non-negative integer
:param b: Second non-negative integer
:return: The greatest common divisor of a and b
:raises ValueError: If either input is negative or ze... | def gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor of integers a and b using Euclid's Algorithm.
:param a: First non-negative integer
:param b: Second non-negative integer
:return: The greatest common divisor of a and b
:raises ValueError: If either input is negative or ze... | import pytest
from solution import gcd, lcm, trailing_zero
def test_gcd_valid_cases():
assert gcd(48, 18) == 6
assert gcd(54, 24) == 6
assert gcd(101, 10) == 1
def test_gcd_edge_cases():
with pytest.raises(ValueError):
gcd(0, 5)
with pytest.raises(ValueError):
gcd(-2, 4)
with p... | [
{
"docstring": "Computes the greatest common divisor of integers a and b using Euclid's Algorithm.\n\n:param a: First non-negative integer\n:param b: Second non-negative integer\n:return: The greatest common divisor of a and b\n:raises ValueError: If either input is negative or zero",
"function_declaration"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a: int, b: int) -> int:\n \"\"\"\n Computes the greatest common divisor of integers a and b using Euclid's Algorithm.\n\n :param a: First non... | trial_gpt4o_2 | {
"original_instruction": "**Question**: You are given three tasks to implement in Python:\n\n1. Write a function that computes the greatest common divisor (GCD) of two non-negative integers using Euclid's algorithm. The function should handle edge cases such as zero inputs and negative values gracefully by raising a... | 0.80569 | Data_Structure_3831 | C | [
"gcd",
"lcm",
"trailing_zero"
] | 3 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9a478a2fcea4a5696aa0542e29c4ba9a0b6fe5fb | 22da9cf8109384007c970ae657a2f57fe7df6cb5 | |||
v1.0 | complete | Data_Structure | Data_Structure_4471_C | def insertion_sort_with_binary_search(array: List[int]) -> List[int]:
""" Sort an array of integers using insertion sort with binary search.
>>> insertion_sort_with_binary_search([4, 3, 2, 10, 12, 1, 5, 6])
[1, 2, 3, 4, 5, 6, 10, 12]
>>> insertion_sort_with_binary_search([100, 20, 15, 30, 5, 75, 40])
... | from typing import List
def search_insert(array: List[int], value: int, start: int, end: int) -> int:
"""
Perform binary search to find the index at which the value should be inserted
to keep the sorted order.
"""
while start < end:
mid = (start + end) // 2
if array[mid] < value:
... | from solution import insertion_sort_with_binary_search
def test_insertion_sort_example():
assert insertion_sort_with_binary_search([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12]
def test_insertion_sort_with_negative_numbers():
assert insertion_sort_with_binary_search([-1, -3, -2, -10, 0]) == [-10, ... | [
{
"docstring": "Perform binary search to find the index at which the value should be inserted\nto keep the sorted order.",
"function_declaration": "def search_insert(array, value, start, end):",
"function_name": "search_insert",
"parameter_list": "(array, value, start, end)"
},
{
"docstring"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef binary_search(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Helper function to find the index to ins... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort with Binary Search\n\nYou are required to implement the insertion sort algorithm utilizing the binary search method provided in the `search_insert` function. The goal is to efficiently sort an array of integers by inserting each new element at its correct position within ... | 0.7086 | Data_Structure_4471 | C | [
"search_insert",
"insertion_sort_with_binary_search"
] | 2 | [
[
"insertion_sort_with_binary_search",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5c65992edc9cb0b3d091c9a500ee6c32e6aa94c3 | 87276ad86ae83bc56982b82529c641e534877e60 | |||
v1.0 | complete | Data_Structure | Data_Structure_4722_C | from typing import Tuple, Dict, Any
def nearest_neighbor(x: Tuple[float, ...], tSet: Dict[Tuple[float, ...], Any]) -> Any:
"""
Finds the nearest neighbor for the point x in the training set tSet.
Arguments:
x: A tuple representing the query point's feature vector.
tSet: A dictionary where ... | from typing import Tuple, Dict, Any
import math
import numpy as np
def euclidean_distance(a: Tuple[float, ...], b: Tuple[float, ...]) -> float:
"""
Calculates the Euclidean distance between two multi-dimensional points.
"""
return math.sqrt(sum((a_i - b_i) ** 2 for a_i, b_i in zip(a, b)))
def nearest_... | from solution import nearest_neighbor
def test_nearest_neighbor_single_point():
query_point = (2.0, 3.0)
training_set = {
(1.0, 2.0): 'A'
}
assert nearest_neighbor(query_point, training_set) == 'A'
def test_nearest_neighbor_multiple_points():
query_point = (2.0, 3.0)
training_set = {
... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Tuple, Dict, Any\nimport math\n\ndef nearest_neighbor(x: Tuple[float, ...], tSet: Dict[Tuple[float, ...], Any]) -> Any:\n \"\"\"\n Fi... | trial_gpt4o_1 | {
"original_instruction": "Implementing and Enhancing Nearest Neighbor Algorithm\n\nYou have been given a task to implement the nearest neighbor algorithm. The algorithm is used to classify a query point based on its similarity to points in a training set. The training set consists of multi-dimensional feature vector... | 0.634483 | Data_Structure_4722 | C | [
"euclidean_distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 087c7676ac4c6b9859c2868db3adaf38e06125a7 | 4d160b46effb450407f95cdc019b342e0736d86c | |||
v1.0 | complete | Data_Structure | Data_Structure_4565_C | import cmath
from math import ceil, log2
from typing import List
def enhanced_fft(x: List[complex]) -> List[complex]:
""" Compute the Discrete Fourier Transform (DFT) using an enhanced variant of the Cooley-Tukey FFT algorithm.
If the size of x is not a power of two, pad x with zeroes until its size reaches th... | import cmath
from math import ceil, log2
def _fft(x):
N = len(x)
if N <= 1:
return x
even = _fft(x[0::2])
odd = _fft(x[1::2])
T = [cmath.exp(-2j * cmath.pi * k / N) * odd[k] for k in range(N // 2)]
return [even[k] + T[k] for k in range(N // 2)] + [even[k] - T[k] for k in range(N // 2)]
... | from solution import enhanced_fft
def test_fft_basic():
# Test case from the examples
input_data = [2.0+2j, 1.0+3j, 3.0+1j, 2.0+2j]
expected_output = [8+8j, 2j, 2-2j, -2+0j]
output = enhanced_fft(input_data)
assert len(output) == len(expected_output)
assert all(abs(output[i] - expected_output[i... | [
{
"docstring": null,
"function_declaration": "def _fft(x):",
"function_name": "_fft",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def enhanced_fft(x):",
"function_name": "enhanced_fft",
"parameter_list": "(x)"
}
] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport cmath\n\ndef enhanced_fft(x: List[complex]) -> List[complex]:\n n = len(x)\n \n # Helper function to find the next po... | trial_gpt4o_2 | {
"original_instruction": "### Question\n\n**Objective**: Implement an enhanced variant of the Cooley-Tukey FFT algorithm to handle input arrays of any size, padding the array with zeroes to the next power of two if necessary.\n\n#### Problem Statement\nGiven an array \\( x \\) of complex numbers, implement the funct... | 0.602232 | Data_Structure_4565 | C | [
"_fft",
"enhanced_fft"
] | 2 | [
[
"enhanced_fft",
"_fft"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3acb21682b25b20fc2b75b8c01c5564052955893 | 7a60e05aaf6de24632d4e421d830f205dad665de | |||
v1.0 | complete | Data_Structure | Data_Structure_3501_C | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Helper function using binary search to find the correct position to insert val in array.
"""
pass
def binary_insertion_sort(array: List[int]) -> List[int]:
"""
Sorts an array using a combination of Insertion Sort... | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Helper function using binary search to find the correct position to insert val in array.
"""
left, right = 0, len(array)
while left < right:
mid = (left + right) // 2
if array[mid] < val:
l... | from solution import binary_insertion_sort
def test_empty_array():
assert binary_insertion_sort([]) == []
def test_single_element_array():
assert binary_insertion_sort([1]) == [1]
def test_sorted_array():
assert binary_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
... | [
{
"docstring": "Helper function using binary search to find the correct position to insert val in array.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "Sorts an array using a combination of Ins... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n Perform binary search to find the index to insert `val` in `... | trial_gpt4o_1 | {
"original_instruction": "You are given an array of integers and asked to implement an efficient sorting algorithm using a combination of Insertion Sort and Binary Search to reduce the number of comparisons while sorting. Your task is to write a function that sorts the array in ascending order.\n\nYour implementatio... | 0.662723 | Data_Structure_3501 | C | [
"search_insert",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 47510ab45116a04a19a1e44287dd089028323ea8 | 185f977ea395de9388a4ce281dfdb31e6d20d70a | |||
v1.0 | complete | Data_Structure | Data_Structure_4155_C | from typing import List
def count_ones_recur(n: int) -> int:
"""
Counts the number of '1' bits in the binary representation of an integer using recursion and
Brian Kernighan's Algorithm.
"""
if n == 0:
return 0
return 1 + count_ones_recur(n & (n - 1))
def count_ones_iter(n: int) -> int... | from typing import List
def count_ones_recur(n: int) -> int:
"""
Counts the number of '1' bits in the binary representation of an integer using recursion and
Brian Kernighan's Algorithm.
This is for demonstration purposes and won't be used in the final implementation.
"""
if n == 0:
... | from solution import count_ones_recur, count_ones_iter, count_ones_list
def test_count_ones_recur():
assert count_ones_recur(0) == 0
assert count_ones_recur(3) == 2
assert count_ones_recur(5) == 2
assert count_ones_recur(11) == 3
assert count_ones_recur(8) == 1
assert count_ones_recur(15) == 4
... | [
{
"docstring": "Counts the number of '1' bits in the binary representation of an integer using recursion and\nBrian Kernighan's Algorithm.\n\nThis is for demonstration purposes and won't be used in the final implementation.",
"function_declaration": "def count_ones_recur(n):",
"function_name": "count_on... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef count_ones_iter(n: int) -> int:\n \"\"\"\n Count the number of '1' bits in the binary representation of an integer using\... | trial_gpt4o_1 | {
"original_instruction": "#### Hamming Weight Calculation with Extended Functionality\n\nYou are given two functions `count_ones_recur(n)` and `count_ones_iter(n)` that use Brian Kernighan's Algorithm to count '1' bits in a binary representation of an unsigned integer.\n\nYour task is to implement a new function `co... | 0.691235 | Data_Structure_4155 | C | [
"count_ones_recur",
"count_ones_iter",
"count_ones_list"
] | 3 | [
[
"count_ones_list",
"count_ones_iter"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8d1b0f4b25aeb1e3941228eb5804a64b893087b9 | 0cda5d2c00c4b0f414a5c3856c89eac1b97614f3 | |||
v1.0 | complete | Data_Structure | Data_Structure_5091_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
""" Sorts an array of integers using the merge sort algorithm.
>>> merge_sort([34, 7, 23, 32, 5, 62])
[5, 7, 23, 32, 34, 62]
>>> merge_sort([4, 3, 2, 1])
[1, 2, 3, 4]
>>> merge_sort([1])
[1]
>>> merge_sort([])
... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half,... | from solution import merge_sort
def test_merge_sort_with_random_array():
assert merge_sort([34, 7, 23, 32, 5, 62]) == [5, 7, 23, 32, 34, 62]
def test_merge_sort_with_reverse_sorted_array():
assert merge_sort([4, 3, 2, 1]) == [1, 2, 3, 4]
def test_merge_sort_with_single_element():
assert merge_sort([1]) =... | [
{
"docstring": "Sorts an array of integers using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into one sorted list.",
"function_declaration": "def merge(left... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Implementation of the merge sort algorithm.\n \"\"\"\n if len(a... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Implementation Question\n\nYou have been assigned a task to implement the Merge Sort algorithm. Merge Sort is a classic divide-and-conquer algorithm that is efficient and guarantees a time complexity of O(n log(n)) for sorting an array of elements. Your task is to implement t... | 0.623108 | Data_Structure_5091 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2ed3f94a4de6b5e40b5b6d29c44336d46ee1b68a | 5fac0cc3300d7d794f8d89f9532ff4d0d2fb43ce | |||
v1.0 | complete | Data_Structure | Data_Structure_4170_C | from typing import Tuple
def generate_key(k: int, seed: int = None) -> Tuple[int, int, int]:
""" Generate RSA public and private keys with bit-length k.
Args:
k (int): Bit-length of the modulus.
seed (int, optional): Seed for random number generation.
Returns:
Tuple[int, int, ... | import random
from sympy import isprime, mod_inverse
def generate_prime_number(bit_length):
while True:
num = random.getrandbits(bit_length)
if isprime(num):
return num
def generate_key(k: int, seed: int = None):
if k % 4 != 0:
raise ValueError("Bit length k must be a multi... | import pytest
from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert e == 65537
def test_encrypt_decrypt():
n, e, d = generate_key(16, seed=42)
dat... | [
{
"docstring": null,
"function_declaration": "def generate_prime_number(bit_length):",
"function_name": "generate_prime_number",
"parameter_list": "(bit_length)"
},
{
"docstring": null,
"function_declaration": "def generate_key(k, seed=None):",
"function_name": "generate_key",
"p... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime_number(bit_length):\n while True:\n num = random.getrandbits(bit_length)... | trial_gpt4o_0 | {
"original_instruction": "### RSA Encryption and Decryption (Advanced)\n\nYou are tasked to implement a secure communication channel using the RSA encryption algorithm. This requires generating keys (public and private), encrypting a message, and then decrypting it.\n\n**Function Specifications**:\n1. **generate_key... | 0.768047 | Data_Structure_4170 | C | [
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_prime_number"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | b9dab2afe0354a8501e9e54ee047a7030b028cf3 | cde976d1950a18a4564477c160125b3ffd97267c | |||
v1.0 | complete | Data_Structure | Data_Structure_5053_C | def reverse_string(s: str, method: str) -> str:
"""
Comprehensive function that reverses a given string based on the specified method.
Parameters:
s: A string to be reversed.
method: A string indicating the method of reversal. Can be one of ["recursive", "iterative", "pythonic", "ultra_pythonic... | def reverse_string(s: str, method: str) -> str:
if method == "recursive":
return recursive_reverse(s)
elif method == "iterative":
return iterative_reverse(s)
elif method == "pythonic":
return pythonic_reverse(s)
elif method == "ultra_pythonic":
return ultra_pythonic_rever... | from solution import reverse_string
def test_recursive_reverse():
assert reverse_string("example", "recursive") == "elpmaxe"
assert reverse_string("a", "recursive") == "a"
assert reverse_string("", "recursive") == ""
assert reverse_string("racecar", "recursive") == "racecar"
assert reverse_string("... | [
{
"docstring": null,
"function_declaration": "def reverse_string(s, method):",
"function_name": "reverse_string",
"parameter_list": "(s, method)"
},
{
"docstring": null,
"function_declaration": "def recursive_reverse(s):",
"function_name": "recursive_reverse",
"parameter_list": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def reverse_string(s: str, method: str) -> str:\n if method == \"recursive\":\n return _reverse_recursive(s)\n elif method == \"iterative\":\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Comprehensive String Reversal Function\n\nYou are tasked with creating a comprehensive function that reverses a given string. You must implement a function that allows selection between four different reversal techniques:\n\n1. **Recursive**: Using recursion to divide and conq... | 0.765603 | Data_Structure_5053 | C | [
"reverse_string",
"recursive_reverse",
"iterative_reverse",
"pythonic_reverse",
"ultra_pythonic_reverse"
] | 5 | [
[
"reverse_string",
"iterative_reverse"
],
[
"reverse_string",
"pythonic_reverse"
],
[
"reverse_string",
"recursive_reverse"
],
[
"reverse_string",
"ultra_pythonic_reverse"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | cbb89b36840261f9959686f54c5176452aa7210d | f8044582a6eb35ad623eb5114c9844467bd3c10a | |||
v1.0 | complete | Data_Structure | Data_Structure_3653_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert(node, val):
"""Inserts a value into the BST."""
pass
def delete(node, val):
"""Deletes a value from the BST."""
pass
def search(node, val):
"... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert(node, val):
"""Inserts a value into the BST."""
if not node:
return TreeNode(val)
if val < node.val:
node.left = insert(node.left, val)... | from solution import TreeNode, insert, delete, search, inorder_traversal
def test_insert():
root = TreeNode(5)
insert(root, 3)
insert(root, 7)
insert(root, 2)
insert(root, 4)
insert(root, 6)
insert(root, 8)
assert inorder_traversal(root) == [2, 3, 4, 5, 6, 7, 8]
def test_search():
... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef in... | trial_gpt4o_0 | {
"original_instruction": "### Binary Search Tree Operations\n\n**Context**:\nYou are tasked with implementing basic operations of a Binary Search Tree (BST). The operations will include inserting a value, deleting a value, and searching for a value in the tree. Additionally, you need to implement a method to retriev... | 0.542567 | Data_Structure_3653 | C | [
"insert",
"delete",
"find_min",
"search",
"inorder_traversal"
] | 5 | [
[
"delete",
"find_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 397da386d69cdc0561758abe5ced4584d144f84e | b68158ac6e7869846ba36f128aa1e331fa94d85c | |||
v1.0 | complete | Data_Structure | Data_Structure_3120_C | from typing import List
def custom_radix_sort(arr: List[int]) -> List[int]:
"""
Implement a function that sorts a list of non-negative integers using the Radix Sort algorithm.
The implementation must handle edge cases such as empty lists and lists with a single element,
ensure stability during so... | from typing import List
def counting_sort(arr: List[int], exp: int) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:... | from solution import custom_radix_sort
def test_custom_radix_sort_example_cases():
assert custom_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
assert custom_radix_sort([3, 3, 3, 3, 3]) == [3, 3, 3, 3, 3]
assert custom_radix_sort([100, 10, 1000, 1, 10, 100, 1000]) == [1,... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def custom_radix_sort(arr):",
"function_name": "custom_radix_sort",
"parameter_list": "(a... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef custom_radix_sort(arr: List[int]) -> List[int]:\n def counting_sort(arr, exp):\n n = len(arr)\n output = [0] *... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\n\nYou have been hired by a company that specializes in sorting large datasets of numerical information. The company is transitioning from traditional comparison-based sorts to more efficient linear time sorting algorithms and has asked you to implement and optimize Radix Sort ... | 0.65834 | Data_Structure_3120 | C | [
"counting_sort",
"custom_radix_sort"
] | 2 | [
[
"custom_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7323681527b859ef3f302b74b2f14c99a43481f4 | 4b6b0b5ab3f06a4a3eefb3e48c4543a8f0c606a6 | |||
v1.0 | complete | Data_Structure | Data_Structure_4457_C | from typing import List
def search_insert(array, val):
"""
Given a sorted array and a target value, return the index if the target is
found. If not, return the index where it would be if it were inserted in order.
"""
low = 0
high = len(array) - 1
while low <= high:
mid = low + (hig... | from typing import List
def search_insert(array, val):
"""
Given a sorted array and a target value, return the index if the target is
found. If not, return the index where it would be if it were inserted in order.
"""
low = 0
high = len(array) - 1
while low <= high:
mid = low + (hig... | from solution import insertion_sort
def test_insertion_sort_basic():
assert insertion_sort([6, 3, 7, 1, 5]) == [1, 3, 5, 6, 7]
def test_insertion_sort_empty():
assert insertion_sort([]) == []
def test_insertion_sort_single_element():
assert insertion_sort([1]) == [1]
def test_insertion_sort_sorted_list(... | [
{
"docstring": "Given a sorted array and a target value, return the index if the target is\nfound. If not, return the index where it would be if it were inserted in order.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n Given a sorted array and a target value, return the index if... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort Implementation using Binary Search\n\n**Challenge:** Implement an optimized version of the insertion sort algorithm using a helper function `search_insert` described below. Given an unsorted list of integers, sort the list in ascending order.\n\n**Function Signature:**\n`... | 0.62971 | Data_Structure_4457 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2c64487624a7af05423e46d2dc2866fe1b6e9c1d | df0ecad37467c3f58822393683d3d1e1849f5462 | |||
v1.0 | complete | Data_Structure | Data_Structure_4749_C | from typing import List
def advanced_radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
""" Implement an advanced version of the Radix Sort algorithm that can handle both positive and negative integers.
Args:
arr: List of integers (positive and negative).
simulation: Boolean flag t... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool=False) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = abs(arr[i]) // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i ... | from solution import advanced_radix_sort
def test_advanced_radix_sort_all_positive_numbers():
assert advanced_radix_sort([170, 45, 75, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 170, 802]
def test_advanced_radix_sort_all_negative_numbers():
assert advanced_radix_sort([-170, -45, -75, -802, -24, -2, -66]) == [-80... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation=False):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def advanced_radix_sort(arr, simulation=False):",
"functi... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool=False) -> List[int]:\n n = len(arr)\n output = [0] * n\n coun... | trial_gpt4o_0 | {
"original_instruction": "### Coding Assessment Task: Advanced Radix Sort Implementation\n\n#### Scenario\nImagine you are part of a team tasked with developing a high-performance sorting utility for a large dataset containing various integers. Your team decided to use Radix Sort due to its efficiency with non-compa... | 0.638353 | Data_Structure_4749 | C | [
"counting_sort",
"advanced_radix_sort"
] | 2 | [
[
"advanced_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b095f820d83f3fde507158fa4a5e8b9dfdf73f6c | cf9b27f3cd33ce21dfbb7ec466b9470450378ccc | |||
v1.0 | complete | Data_Structure | Data_Structure_3891_C | def reverse_string(s, method="iterative"):
"""
Reverses a given string `s` using the specified method.
Parameters:
s (str): The string to be reversed.
method (str): The method to use for reversing the string - "recursive", "iterative", "pythonic", "ultra_pythonic".
Returns:
str: Th... | def reverse_string(s, method="iterative"):
"""
Reverses a given string `s` using the specified method.
Parameters:
s (str): The string to be reversed.
method (str): The method to use for reversing the string - "recursive", "iterative", "pythonic", "ultra_pythonic".
Returns:
str: Th... | from solution import reverse_string
def test_reverse_string_recursive():
assert reverse_string("hello", "recursive") == "olleh"
assert reverse_string("world", "recursive") == "dlrow"
def test_reverse_string_iterative():
assert reverse_string("python") == "nohtyp" # By default using iterative method
a... | [
{
"docstring": "Reverses a given string `s` using the specified method.\n\nParameters:\ns (str): The string to be reversed.\nmethod (str): The method to use for reversing the string - \"recursive\", \"iterative\", \"pythonic\", \"ultra_pythonic\".\n\nReturns:\nstr: The reversed string.",
"function_declarati... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def reverse_string(s, method=\"iterative\"):\n \"\"\"\n Reverses a given string s using the specified method.\n \n Parameters:\n - s: The strin... | trial_gpt4o_2 | {
"original_instruction": "### String Reversing\n\nYou are tasked with implementing a function to reverse a given string. You will use one of the following methods of string reversal: recursive, iterative, or slicing.\n\n#### Requirements:\n1. Implement a function `reverse_string` that takes a string `s` and an optio... | 0.698467 | Data_Structure_3891 | C | [
"reverse_string",
"_reverse_recursive",
"_reverse_iterative"
] | 3 | [
[
"reverse_string",
"_reverse_iterative"
],
[
"reverse_string",
"_reverse_recursive"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f7622e57e849c4e7485f575fccb7e4d2155ad6ee | 6c47b431e0347ddc77143b72d1017d6e89262032 | |||
v1.0 | complete | Data_Structure | Data_Structure_3608_C | from typing import List
def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
""" Implement a sorting function using the Radix Sort algorithm.
Args:
arr (List[int]): A list of non-negative integers to be sorted.
simulation (bool): An optional flag that when set to True, will print... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool, iteration: int) -> List[int]:
n = len(arr)
output = [0] * n # output array to store sorted numbers
count = [0] * 10 # count array to store occurrences of digits
# Store count of occurrences in the count array
... | from solution import radix_sort
def test_radix_sort_with_simulation():
arr = [170, 45, 75, 90, 802, 24, 2, 66]
sorted_arr = radix_sort(arr, simulation=True)
assert sorted_arr == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_on_empty_list():
assert radix_sort([]) == []
def test_radix_sort_sing... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation, iteration):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation, iteration)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"funct... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool, iteration: int) -> List[int]:\n n = len(arr)\n output = [0] * n... | trial_gpt4o_1 | {
"original_instruction": "**Problem Description**:\n\nYou are required to implement a sorting function using the Radix Sort algorithm. The function must be capable of sorting a list of non-negative integers. The function should additionally support a simulation mode that prints the state of the list after each sorti... | 0.638123 | Data_Structure_3608 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0660919db11d99265d08c14ac5cfc168c42ae228 | d0d84cfa78f20cef4b4960084526f3bc08bcfdb7 | |||
v1.0 | complete | Data_Structure | Data_Structure_5066_C | def enhanced_comb_sort(arr):
""" Enhanced Comb Sort: Sorts an array with additional requirements of handling small arrays, duplicates, and maintaining stability.
>>> enhanced_comb_sort([23, -3, 4, 68, 34, 23, 93, 0])
[-3, 0, 4, 23, 23, 34, 68, 93]
>>> enhanced_comb_sort([2, 3, 2, 3, 1, 1, 3])
[1, 1,... | def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def enhanced_comb_sort(arr):
n = len(arr)
# Pre-check for small arrays
if n... | from solution import enhanced_comb_sort
def test_sorted_array():
assert enhanced_comb_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reversed_array():
assert enhanced_comb_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_unsorted_array():
assert enhanced_comb_sort([23, -3, 4, 68, 34, 23, 93, 0]) == [... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def enhanced_comb_sort(arr):",
"function_name": "enhanced_comb_sort",
"parameter_list": "(arr)"
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_comb_sort(arr):\n def insertion_sort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n ... | trial_gpt4o_2 | {
"original_instruction": "### Problem: Enhanced Comb Sort\n\nYou are given an array of integers and need to sort it using an enhanced version of the Comb Sort algorithm. Your task is to modify the given Comb Sort algorithm so that it can handle the following additional requirements:\n\n1. **Pre-check for Small Array... | 0.692758 | Data_Structure_5066 | C | [
"insertion_sort",
"enhanced_comb_sort"
] | 2 | [
[
"enhanced_comb_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ade15211aa3cdd1dea2f7c3284ccccf9061cbd3 | b6d257a0c257139d79f902aa26c1acde43f83283 | |||
v1.0 | complete | Data_Structure | Data_Structure_5068_C | from typing import Tuple, Dict, Any
def nearest_neighbor(x: Tuple[float], tSet: Dict[Tuple[float], Any]) -> Any:
""" Find the closest vector in the training set to the given vector and return the associated result.
Args:
x (Tuple[float]): A tuple representing the given vector.
tSet (Dict[Tuple[flo... | from typing import Tuple, Dict, Any
import math
def euclidean_distance(a: Tuple[float], b: Tuple[float]) -> float:
return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))
def nearest_neighbor(x: Tuple[float], tSet: Dict[Tuple[float], Any]) -> Any:
closest_vector = None
min_distance = float('inf')
fo... | from solution import nearest_neighbor
def test_nearest_neighbor_example():
x = (1.0, 2.0)
tSet = {
(1.1, 2.1): 'A',
(3.0, 4.0): 'B',
(6.0, 7.0): 'C'
}
assert nearest_neighbor(x, tSet) == 'A'
def test_nearest_neighbor_single_vector():
x = (1.0, 2.0)
tSet = {
(1.0... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(a, b):",
"function_name": "euclidean_distance",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def nearest_neighbor(x, tSet):",
"function_name": "nearest_neighbor",
"parameter_list":... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import Tuple, Dict, Any\n\ndef euclidean_distance(vec1: Tuple[float], vec2: Tuple[float]) -> float:\n return math.sqrt(sum((a - b)... | trial_gpt4o_1 | {
"original_instruction": "### Nearest Neighbor Algorithm with Constraints\n\nYou are given a nearest neighbor algorithm that finds the closest vector to a given vector from a training set and returns the result associated with that vector. Your task is to implement this functionality as accurately and efficiently as... | 0.644531 | Data_Structure_5068 | C | [
"euclidean_distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 813797e1d736e5e95e8bc9d4aed45bebe9cbddff | 00ac910a24ede7c71374337cb2abdd1587bf049f | |||
v1.0 | complete | Data_Structure | Data_Structure_5381_C | def calculate_gcd(a: int, b: int) -> int:
"""
Calculate the Greatest Common Divisor (GCD) of two non-zero integers.
>>> calculate_gcd(48, 18)
6
>>> calculate_gcd(-48, 18)
6
>>> calculate_gcd(24, 1)
1
"""
# Your implementation here
def calculate_lcm(a: int, b: int) -> int:
"... | def calculate_gcd(a: int, b: int) -> int:
"""
Calculate the Greatest Common Divisor (GCD) of two non-zero integers.
"""
if not isinstance(a, int) or not isinstance(b, int):
raise ValueError("Both inputs must be integers.")
if a == 0 or b == 0:
raise ValueError("Both input values must... | from solution import calculate_gcd, calculate_lcm
def test_calculate_gcd_positive_numbers():
assert calculate_gcd(48, 18) == 6
def test_calculate_gcd_negative_numbers():
assert calculate_gcd(-48, 18) == 6
assert calculate_gcd(48, -18) == 6
assert calculate_gcd(-48, -18) == 6
def test_calculate_gcd_wi... | [
{
"docstring": "Calculate the Greatest Common Divisor (GCD) of two non-zero integers.",
"function_declaration": "def calculate_gcd(a, b):",
"function_name": "calculate_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate the Least Common Multiple (LCM) of two non-zero integers.",
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_gcd(a, b):\n \"\"\"\n Returns the greatest common divisor (GCD) of a and b.\n \"\"\"\n if not isinstance(a, int) or not isinstance(b... | trial_gpt4o_1 | {
"original_instruction": "**Scenario**:\nYou are developing a microservice for a software system that processes large volumes of numerical data. The service needs to efficiently compute the GCD and LCM of integer pairs, including the ability to handle large values and edge cases robustly. As such, you are tasked wit... | 0.820347 | Data_Structure_5381 | C | [
"calculate_gcd",
"calculate_lcm"
] | 2 | [
[
"calculate_lcm",
"calculate_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 407347fe1fa1ebdc4500ded804cbad894bd515f3 | 76a553277cfef34b4395c9362c8e0f3b42319bda | |||
v1.0 | complete | Data_Structure | Data_Structure_5168_C | def bitonic_sort(arr, reverse=False):
""" Implement the Bitonic Sort algorithm.
The function should sort the array `arr` in ascending order if `reverse` is True,
otherwise sort it in descending order.
Args:
arr: List[int] - A list of integers where the size of `arr` is a power of two.
... | def bitonic_compare(arr, start, end, direction):
length = end - start
mid = length // 2
for i in range(start, start + mid):
if (direction and arr[i] > arr[i + mid]) or (not direction and arr[i] < arr[i + mid]):
arr[i], arr[i + mid] = arr[i + mid], arr[i]
def bitonic_merge(arr, start, en... | from solution import bitonic_sort
def test_bitonic_sort_ascending():
arr = [3, 7, 2, 8, 1, 5, 4, 6]
expected = [1, 2, 3, 4, 5, 6, 7, 8]
assert bitonic_sort(arr, reverse=True) == expected
def test_bitonic_sort_descending():
arr = [3, 7, 2, 8, 1, 5, 4, 6]
expected = [8, 7, 6, 5, 4, 3, 2, 1]
asse... | [
{
"docstring": null,
"function_declaration": "def bitonic_compare(arr, start, end, direction):",
"function_name": "bitonic_compare",
"parameter_list": "(arr, start, end, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, start, end, direction):",
"fun... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bitonic_sort(arr, reverse=False):\n def compare_and_swap(arr, i, j, direction):\n if (direction and arr[i] > arr[j]) or (not direction and arr[i... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with implementing the Bitonic Sort algorithm. This algorithm sorts using a divide-and-conquer approach and is notably efficient when parallelism is leveraged. Although in your implementation, you will not use parallel processing, the core principles of the Bitonic Sort must b... | 0.72235 | Data_Structure_5168 | C | [
"bitonic_compare",
"bitonic_merge",
"bitonic_sort_recursive",
"bitonic_sort"
] | 4 | [
[
"bitonic_merge",
"bitonic_compare"
],
[
"bitonic_sort",
"bitonic_sort_recursive"
],
[
"bitonic_sort_recursive",
"bitonic_merge"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 9e8930789aba6c03a59c094f0854b548a29122f7 | a66c3f594b97214e92211e889a2f4034f53dac2e | |||
v1.0 | complete | Data_Structure | Data_Structure_5458_C | from typing import List
def find_phrases_in_text(text: str, phrases: List[str]) -> List[List[int]]:
"""
Given a text and a list of phrases, return a list of lists where each inner list contains the starting indices
of the corresponding phrase found within the text.
This function should use the Knuth-M... | from typing import List
def kmp_search(pattern: str, text: str) -> List[int]:
"""
Perform KMP search of the pattern in the text and returns a list of starting indices
where the pattern is found in the text.
"""
def compute_lps(pattern: str) -> List[int]:
lps = [0] * len(pattern)
len... | from solution import find_phrases_in_text
def test_empty_text_and_phrases():
assert find_phrases_in_text('', []) == []
assert find_phrases_in_text('', ['hello']) == [[]]
assert find_phrases_in_text('hello', []) == []
def test_phrases_found_in_text():
assert find_phrases_in_text('hello there hero! hell... | [
{
"docstring": "Perform KMP search of the pattern in the text and returns a list of starting indices\nwhere the pattern is found in the text.",
"function_declaration": "def kmp_search(pattern, text):",
"function_name": "kmp_search",
"parameter_list": "(pattern, text)"
},
{
"docstring": null,... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef compute_kmp_table(pattern: str) -> List[int]:\n \"\"\"\n Computes the KMP partial match table (also known as \"failure fu... | trial_gpt4o_5 | {
"original_instruction": "You are given a large body of text and a set of phrases. Your task is to implement a function that identifies all the starting positions of each phrase within the given text using the Knuth-Morris-Pratt (KMP) algorithm for pattern matching. \n\n### Function Signature\n```python\ndef find_ph... | 0.619784 | Data_Structure_5458 | C | [
"kmp_search",
"find_phrases_in_text"
] | 2 | [
[
"find_phrases_in_text",
"kmp_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b07a5d2e47922004d7ae34374f74e8f7651acc4b | 29560129fc044d85d9fc68e9a8febfbc9f5701ac | |||
v1.0 | complete | Data_Structure | Data_Structure_4843_C | from typing import List
def search_insert(array: List[int], target: int) -> int:
"""
Implements binary search to find the insert position for a target in a sorted array.
"""
left, right = 0, len(array) - 1
while left <= right:
mid = (left + right) // 2
if array[mid] < target:
... | from typing import List
def search_insert(array: List[int], target: int) -> int:
"""
Implements binary search to find the insert position for a target in a sorted array.
"""
left, right = 0, len(array) - 1
while left <= right:
mid = (left + right) // 2
if array[mid] < target:
... | from solution import insertion_sort
def test_insertion_sort_sorted_array():
assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_insertion_sort_reverse_sorted_array():
assert insertion_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_insertion_sort_random_array():
assert insertion_sort([4,... | [
{
"docstring": "Implements binary search to find the insert position for a target in a sorted array.",
"function_declaration": "def search_insert(array, target):",
"function_name": "search_insert",
"parameter_list": "(array, target)"
},
{
"docstring": "Sorts an array of integers in ascending... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(arr: List[int], value: int) -> int:\n \"\"\"\n This function uses binary search to find the index where the... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort Implementation with Search Insert Function\n\n**Scenario**: \n\nYou are working on optimizing the insertion sort algorithm by using a helper function, `search_insert`, which utilizes binary search to determine the position for insertion of the next element. This should th... | 0.661469 | Data_Structure_4843 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 514bd8b130099d8e02f4c4ca0119c9ee504333cf | c1214788e5ef569e7550bd47ac2773c642cce54e | |||
v1.0 | complete | Data_Structure | Data_Structure_3866_C | from typing import Dict, List
def find_longest_path(graph: Dict[str, List[str]], start: str, end: str) -> List[str]:
""" Determine the longest path between two intersections in the network.
>>> graph = {
>>> 'A': ['B', 'C'],
>>> 'B': ['A', 'D', 'E'],
>>> 'C': ['A', 'F'],
>>> 'D': ['B'],
... | def dfs(graph, node, end, visited, path):
visited.add(node)
path.append(node)
if node == end:
yield path[:]
else:
for neighbor in graph[node]:
if neighbor not in visited:
yield from dfs(graph, neighbor, end, visited, path)
path.pop()
visited.remove(n... | from solution import find_longest_path
def test_basic_case():
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
assert find_longest_path(graph, 'A', 'F') == ['A', 'B', 'E', 'F']
def test_no_path_... | [
{
"docstring": null,
"function_declaration": "def dfs(graph, node, end, visited, path):",
"function_name": "dfs",
"parameter_list": "(graph, node, end, visited, path)"
},
{
"docstring": null,
"function_declaration": "def find_longest_path(graph, start, end):",
"function_name": "find_... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_longest_path(graph, start, end):\n def dfs(node, path):\n nonlocal longest_path\n if node == end:\n if len(path) > len(lo... | trial_gpt4o_1 | {
"original_instruction": "### Pathfinding in Simple Networks\n\n**Problem Description**:\n\nYou are given a simple transportation network represented as a graph, where intersections are nodes, and roads are edges. Each road has a length of 1 unit. Your task is to write a function to determine the longest path betwee... | 0.56017 | Data_Structure_3866 | C | [
"dfs",
"find_longest_path"
] | 2 | [
[
"find_longest_path",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9eae36b9b99953748eca4f392a78b4f17c05a9ea | 28232da2e2d8fc9e5ce2a70965356a69aaadeda5 | |||
v1.0 | complete | Data_Structure | Data_Structure_4271_C | import random
from typing import Tuple
def encrypt_message(message: str, key: int) -> str:
""" Encrypts the message using the shared key.
>>> encrypt_message("HELLO WORLD", 3)
'KHOOR#ZRUOG'
"""
encrypted_message = ''.join(chr((ord(char) + key - 32) % 95 + 32) for char in message)
return encrypt... | def encrypt_message(message, key):
""" Encrypts the message using the shared key. """
encrypted_message = ''.join(chr((ord(char) + key - 32) % 95 + 32) for char in message)
return encrypted_message
def decrypt_message(encrypted_message, key):
""" Decrypts the message using the shared key. """
decry... | from solution import encrypt_message, decrypt_message, secure_message_exchange
def test_encrypt_decrypt():
message = "HELLO WORLD"
key = 3
encrypted_message = encrypt_message(message, key)
decrypted_message = decrypt_message(encrypted_message, key)
assert message == decrypted_message
def test_secu... | [
{
"docstring": "Encrypts the message using the shared key. ",
"function_declaration": "def encrypt_message(message, key):",
"function_name": "encrypt_message",
"parameter_list": "(message, key)"
},
{
"docstring": "Decrypts the message using the shared key. ",
"function_declaration": "def... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef encrypt_message(message, key):\n \"\"\" Encrypts the message using the shared key. \"\"\"\n encrypted_message = ''.join(chr(((ord(c... | trial_gpt4o_2 | {
"original_instruction": "Secure Encrypted Message Exchange\n\n#### Objective\nBased on the Diffie-Hellman key exchange algorithm provided, your task is to implement a secure message exchange between Alice and Bob. They will use the shared secret key generated from the key exchange to encrypt and decrypt messages us... | 0.566646 | Data_Structure_4271 | C | [
"encrypt_message",
"decrypt_message",
"diffie_hellman_key_exchange",
"secure_message_exchange"
] | 4 | [
[
"secure_message_exchange",
"decrypt_message"
],
[
"secure_message_exchange",
"diffie_hellman_key_exchange"
],
[
"secure_message_exchange",
"encrypt_message"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | aec94ab979bfb410cd14c0b19570d4d3e01a7f80 | 73af8012e80ca42c9a907a4b01499597a06daa56 | |||
v1.0 | complete | Data_Structure | Data_Structure_5793_C | from typing import List
def optimized_gcd(nums: List[int]) -> int:
"""
Computes the greatest common divisor of a list of integers using bitwise operations.
Parameters:
nums (List[int]): A list of non-zero integers.
Returns:
int: The greatest common divisor of the list.
Exampl... | from typing import List
def gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor using the bitwise Stein's algorithm.
"""
if a == 0:
return b
if b == 0:
return a
# both a and b are nonzero
if a < 0:
a = -a
if b < 0:
b = -b
# find com... | from solution import optimized_gcd
def test_positive_numbers():
assert optimized_gcd([54, 24, 36]) == 6
def test_mixed_sign_numbers():
assert optimized_gcd([48, -180, 640]) == 4
def test_with_zeros():
assert optimized_gcd([0, 24, 36]) == 12 # any list will contain non-zero elements
def test_single_eleme... | [
{
"docstring": "Computes the greatest common divisor using the bitwise Stein's algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the greatest common divisor of a list of integers using bitwise operations.",
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom functools import reduce\n\ndef gcd(a: int, b: int) -> int:\n \"\"\"\n Calculate the greatest common divisor (GCD) of two i... | trial_gpt4o_1 | {
"original_instruction": "### Question: Advanced GCD Calculation with Constraints\n\nIn this question, you are tasked to implement a function that computes the greatest common divisor (GCD) of a list of integers. Your implementation should consider both positive and negative integers and leverage bitwise operations ... | 0.778014 | Data_Structure_5793 | C | [
"gcd",
"optimized_gcd"
] | 2 | [
[
"optimized_gcd",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d4274b9aa6188ef2a9f88faf22717b656b8f54b4 | f51c7cec910151c06ad767375d1a7406b211d1ef | |||
v1.0 | complete | Data_Structure | Data_Structure_4989_C | from typing import List
def next_sort(arr: List[float]) -> List[float]:
"""
Performs insertion sort on the provided list `arr`.
"""
def bucket_sort(arr: List[float]) -> List[float]:
"""
Sort the list of floating-point numbers using bucket sort algorithm.
>>> bucket_sort([42.3, 12.1, 13.5, 99.9... | from typing import List
def next_sort(arr: List[float]) -> List[float]:
"""
Performs insertion sort on the provided list `arr`.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j... | from solution import bucket_sort
def test_bucket_sort_basic():
assert bucket_sort([42.3, 12.1, 13.5, 99.9, 2.2, 54.4, 22.2]) == [2.2, 12.1, 13.5, 22.2, 42.3, 54.4, 99.9]
def test_bucket_sort_empty():
assert bucket_sort([]) == []
def test_bucket_sort_single_element():
assert bucket_sort([42.3]) == [42.3]
... | [
{
"docstring": "Performs insertion sort on the provided list `arr`.",
"function_declaration": "def next_sort(arr):",
"function_name": "next_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the list `arr` using bucket sort algorithm.",
"function_declaration": "def bucket_sort(arr... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[float]) -> List[float]:\n \"\"\"\n Performs an insertion sort on the given array and returns the... | trial_gpt4o_2 | {
"original_instruction": "### Bucket Sort Implementation Challenge\n\n**Context**:\nYou are tasked with enhancing a sorting system for an e-commerce platform. The system uses bucket sort to optimize the ranking of product prices for various categories. Your objective is to implement `bucket_sort` and `next_sort` fun... | 0.630887 | Data_Structure_4989 | C | [
"next_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"next_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 81b59b1fc3153db44363e107bcecb6303efbaf43 | 862b298789f3fcfcc0a3dd8cb0b97104463121d9 | |||
v1.0 | complete | Data_Structure | Data_Structure_4096_C | from typing import List
def search_insert(nums: List[int], x: int, low: int, high: int) -> int:
"""
A helper function that uses binary search to find the index where x should be inserted
in the list nums between indexes low and high.
"""
while low < high:
mid = (low + high) // 2
if ... | from typing import List
def search_insert(nums: List[int], x: int, low: int, high: int) -> int:
"""
A helper function that uses binary search to find the index where x should be inserted
in the list nums between indexes low and high.
"""
while low < high:
mid = (low + high) // 2
if ... | def test_insertion_sort_empty():
assert insertion_sort([]) == []
def test_insertion_sort_single_element():
assert insertion_sort([1]) == [1]
def test_insertion_sort_two_elements():
assert insertion_sort([2, 1]) == [1, 2]
def test_insertion_sort_multiple_elements():
assert insertion_sort([4, 2, 7, 1, ... | [
{
"docstring": "A helper function that uses binary search to find the index where x should be inserted\nin the list nums between indexes low and high.",
"function_declaration": "def search_insert(nums, x, low, high):",
"function_name": "search_insert",
"parameter_list": "(nums, x, low, high)"
},
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(arr: List[int], left: int, right: int, target: int) -> int:\n \"\"\"\n Uses binary search to find the index... | trial_gpt4o_1 | {
"original_instruction": "**Insertion Sort with Binary Search Optimization**\n\nYou are required to implement a modified version of the Insertion Sort algorithm that uses a binary search to find the correct insertion point of an element. This approach optimizes the searching part of the Insertion Sort but still requ... | 0.637426 | Data_Structure_4096 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 301bd274b0e945e35a2a9e6c82d9d0234e350611 | b59fc04fbd1a07af58ccf4e1e62406f895d6d262 | |||
v1.0 | complete | Data_Structure | Data_Structure_5701_C | def count_primes(a: int, b: int) -> int:
""" Count the number of prime numbers in the range [a, b] (inclusive).
>>> count_primes(1, 10) 4 # Primes: 2, 3, 5, 7
>>> count_primes(10, 20) 4 # Primes: 11, 13, 17, 19
>>> count_primes(-10, 10) 4 # Primes: 2, 3, 5, 7
>>> count_primes(30, 40) 2 # Primes... | import math
def is_prime(n):
"""
Check if a number is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import count_primes
def test_primes_in_small_range():
assert count_primes(1, 10) == 4 # Primes: 2, 3, 5, 7
def test_primes_in_mid_range():
assert count_primes(10, 20) == 4 # Primes: 11, 13, 17, 19
def test_primes_in_negative_to_positive_range():
assert count_primes(-10, 10) == 4 # Primes... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Count the number of prime numbers in the range [a, b] (inclusive).",
"function_declaration": "def count_primes(a, b):... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\... | trial_gpt4o_2 | {
"original_instruction": "### Question: Check Prime Intervals\n\nYou have been tasked with developing a function that checks the number of prime numbers in a given range \\([a, b]\\) inclusively.\n\n#### Task:\nWrite a Python function `count_primes(a: int, b: int) -> int` that returns the count of prime numbers betw... | 0.783543 | Data_Structure_5701 | C | [
"is_prime",
"count_primes"
] | 2 | [
[
"count_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 65968567ec36022fd7b5e2969134577544d3d599 | 4c957aad977951508dc71c5f0e9477ed7aa31a51 | |||
v1.0 | complete | Data_Structure | Data_Structure_4066_C | from typing import List
def stoogesort(arr: List[int], l: int, h: int) -> None:
"""
Sorts an array using the Stooge Sort algorithm recursively.
The function modifies the array in place.
Parameters:
arr (List[int]): The array to be sorted.
l (int): The starting index of the array to be sort... | from typing import List
def stoogesort(arr: List[int], l: int, h: int) -> None:
"""
Sorts an array using the Stooge Sort algorithm recursively.
The function modifies the array in place.
Parameters:
arr (List[int]): The array to be sorted.
l (int): The starting index of the array to be sort... | from solution import sort_array
def test_sort_array_sample_cases():
arr1 = [2, 4, 5, 3, 1]
sort_array(arr1)
assert arr1 == [1, 2, 3, 4, 5]
arr2 = [7, 3, 8]
sort_array(arr2)
assert arr2 == [3, 7, 8]
def test_sort_array_single_element():
arr = [5]
sort_array(arr)
assert arr == [... | [
{
"docstring": "Sorts an array using the Stooge Sort algorithm recursively.\nThe function modifies the array in place.\n\nParameters:\narr (List[int]): The array to be sorted.\nl (int): The starting index of the array to be sorted.\nh (int): The ending index of the array to be sorted.",
"function_declaratio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef stoogesort(arr: List[int], l: int = 0, h: int = None) -> None:\n \"\"\"\n Sorts the given array arr in non-decreasing ord... | trial_gpt4o_2 | {
"original_instruction": "You are given an array of integers that need to be sorted in non-decreasing order using an exotic sorting algorithm known as Stooge Sort. \n\n### Function Signature\n```python\ndef stoogesort(arr: List[int]) -> None:\n # Your code here\n```\n\n### Input\n- An array `arr` of integers, whe... | 0.69166 | Data_Structure_4066 | C | [
"stoogesort",
"sort_array"
] | 2 | [
[
"sort_array",
"stoogesort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 04ae9f44d2bd4733d111257d9821431dfc4eed73 | 92ff0c06f775e7ac5ea6167a56966bf1a0da77b9 | |||
v1.0 | complete | Data_Structure | Data_Structure_5835_C | import random
def visual_bogo_sort(arr, max_iterations):
"""
Performs a Bogo Sort on the array while visualizing each iteration.
Args:
arr (list of int): The array to be sorted.
max_iterations (int): Maximum number of iterations allowed.
Returns:
None: Prints the array at each ite... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def visual_bogo_sort(arr, max_iterations):
"""
Performs a Bogo Sort on the array while visualizing e... | from solution import visual_bogo_sort
import io
import sys
def test_visual_bogo_sort_sorted():
arr = [1, 2, 3, 4, 5]
max_iterations = 1000
captured_output = io.StringIO()
sys.stdout = captured_output
visual_bogo_sort(arr, max_iterations)
sys.stdout = sys.__stdout__
assert "Sorted after... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Performs a Bogo Sort on the array while visualizing each iteration.\n\nArgs:\narr (list of int): The ar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Utility function to check if the array is sorted.\n \"\"\"\n for i in range(len(arr) - 1):\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question\n\nYou have been provided with an implementation of Bogo Sort, a highly inefficient sorting algorithm. Your task is to implement a new sorting function to simulate and visualize each step of the sorting process. However, given the impracticality of Bogo Sort for real-world scen... | 0.599105 | Data_Structure_5835 | C | [
"is_sorted",
"visual_bogo_sort"
] | 2 | [
[
"visual_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fd2456dd773914c5d22407f114f4ed6d6a73a403 | 1558547a00b212419f0b1fdd3f78ac2c0f84b7a5 | |||
v1.0 | complete | Data_Structure | Data_Structure_3672_C | from typing import List, Union
def invert_matrix(m: List[List[Union[int, float]]]) -> List[List[Union[int, float]]]:
"""
Invert a given n x n matrix.
The function `invert_matrix` takes a square matrix as input, computes its inverse by following a set of
computational steps, and returns the inverted m... | from typing import List, Union
def get_cofactor(matrix, i, j):
return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]
def determinant_recursive(matrix):
if len(matrix) == 1:
return matrix[0][0]
if len(matrix) == 2:
return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]
... | from solution import invert_matrix
def test_2x2_matrix():
matrix = [
[4, 7],
[2, 6]
]
expected_output = [
[0.6, -0.7],
[-0.2, 0.4]
]
assert invert_matrix(matrix) == expected_output
def test_singular_matrix():
matrix = [
[1, 2],
[2, 4]
]
a... | [
{
"docstring": null,
"function_declaration": "def get_cofactor(matrix, i, j):",
"function_name": "get_cofactor",
"parameter_list": "(matrix, i, j)"
},
{
"docstring": null,
"function_declaration": "def determinant_recursive(matrix):",
"function_name": "determinant_recursive",
"par... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Union\n\ndef get_matrix_minor(matrix, i, j):\n return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]\n\ndef get_matr... | trial_gpt4o_1 | {
"original_instruction": "### Matrix Inversion Algorithm\n\n#### Problem Statement\nYou have been provided with a Python function `invert_matrix(m)` that inverts an \\( n \\times n \\) matrix. The function follows a four-step process to compute the inverse:\n1. Computation of the matrix of minors with an alternate s... | 0.543305 | Data_Structure_3672 | C | [
"get_cofactor",
"determinant_recursive",
"adjugate_matrix",
"transpose_matrix",
"invert_matrix"
] | 5 | [
[
"adjugate_matrix",
"determinant_recursive"
],
[
"adjugate_matrix",
"get_cofactor"
],
[
"adjugate_matrix",
"transpose_matrix"
],
[
"determinant_recursive",
"get_cofactor"
],
[
"invert_matrix",
"adjugate_matrix"
],
[
"invert_matrix",
"determinant_r... | 6 | [] | false | [] | false | pytest | true | [] | true | 2f1704c8ea98b0426eac1d36a9adc5a9d62ced98 | 3d1b564b51e3b10a3dde75762540abc6beb1fbce | |||
v1.0 | complete | Data_Structure | Data_Structure_5577_C | class SeparateChainingHashTable:
""" Separate Chaining Hash Table with dynamic resizing and contains method.
>>> table = SeparateChainingHashTable()
>>> table.put('a', 1)
>>> table.put('b', 2)
>>> table.contains('a')
True
>>> table.contains('z')
False
>>> for i in range(20): tab... | import itertools
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
ret... | from solution import SeparateChainingHashTable
def test_put_and_get():
table = SeparateChainingHashTable()
table.put('key1', 'value1')
assert table.get('key1') == 'value1'
table.put('key1', 'value2')
assert table.get('key1') == 'value2'
def test_remove():
table = SeparateChainingHashTable(... | [] | [
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 itertools\n\ndef is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n... | trial_gpt4o_0 | {
"original_instruction": "### Question: Enhanced Separate Chaining Hash Table\n\n#### Scenario\nYou have been provided with an implementation of a separate chaining hash table. While it works, it lacks some important features, such as dynamic resizing and more robust error handling.\n\n#### Task\nEnhance the provide... | 0.452358 | Data_Structure_5577 | C | [
"is_prime",
"next_prime"
] | 2 | [
[
"next_prime",
"is_prime"
]
] | 1 | [] | false | [
"SeparateChainingHashTable"
] | true | pytest | true | [] | true | 917df50ae636796eae88bdb7a40f87c499e35b24 | 2979b2ef0b748c171360ffa292333e871f4c07fb | |||
v1.0 | complete | Data_Structure | Data_Structure_5590_C | class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def kth_smallest(root: Node, k: int) -> int:
""" Find the k-th smallest element in a Binary Search Tree.
>>> n1 = Node(100)
>>> n2 = Node(50)
>>> n3 = Node(150)
... | class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_traversal(node, result):
if node:
inorder_traversal(node.left, result)
result.append(node.val)
inorder_traversal(node.right, resul... | import pytest
from solution import Node, kth_smallest
def test_kth_smallest():
n1 = Node(100)
n2 = Node(50)
n3 = Node(150)
n4 = Node(25)
n5 = Node(75)
n6 = Node(125)
n7 = Node(175)
n1.left, n1.right = n2, n3
n2.left, n2.right = n4, n5
n3.left, n3.right = n6, n7
assert kth_s... | [] | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.ri... | trial_gpt4o_2 | {
"original_instruction": "Given the implementation of inorder traversal of a binary tree in both iterative and recursive styles, your task is to write a function that performs \"K-th smallest element in a Binary Search Tree\".\n\n### Problem Statement\n\nYou are provided with a binary search tree (BST) and an intege... | 0.540155 | Data_Structure_5590 | C | [
"inorder_traversal",
"kth_smallest"
] | 2 | [
[
"kth_smallest",
"inorder_traversal"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 2cbe06b16ec110cbe5a2459926cbdecb8c938477 | ea2ae7a9a851d6869144f95d83d77d84c8818ad4 | |||
v1.0 | complete | Data_Structure | Data_Structure_5714_C | def find_eureka_numbers(start: int, end: int) -> List[int]:
"""
Returns a list of "Eureka" numbers within the range [start, end] inclusive.
A Eureka number is a number that can be represented as the sum of its digits raised
to their respective positions.
"""
def is_eureka_number(num: int) -> bool:... | def find_eureka_numbers(start, end):
"""
Returns a list of "Eureka" numbers within the range [start, end] inclusive.
A Eureka number is a number that can be represented as the sum of its digits raised
to their respective positions.
"""
eureka_numbers = []
for num in range(start, end + 1):
... | from solution import find_eureka_numbers, is_eureka_number
def test_find_eureka_numbers_basic():
assert find_eureka_numbers(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_find_eureka_numbers_up_to_100():
assert find_eureka_numbers(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
def test_find_eureka_numbers_large_... | [
{
"docstring": "Returns a list of \"Eureka\" numbers within the range [start, end] inclusive.\nA Eureka number is a number that can be represented as the sum of its digits raised \nto their respective positions.",
"function_declaration": "def find_eureka_numbers(start, end):",
"function_name": "find_eur... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_eureka_numbers(start, end):\n def is_eureka_number(n):\n digits = list(map(int, str(n)))\n return n == sum(d ** (idx + 1) for idx, d... | trial_gpt4o_1 | {
"original_instruction": "### Scenario\nYou are working on a problem that requires identifying numbers within a specific range where each digit raised to the power of its position and summed equals the number itself. These numbers are often referred to as digit power sum numbers or \"Eureka\" numbers.\n\n### Problem... | 0.612311 | Data_Structure_5714 | C | [
"find_eureka_numbers",
"is_eureka_number"
] | 2 | [
[
"find_eureka_numbers",
"is_eureka_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 39401e881bcbce9319c88d0bc4147b788965c94a | 0a0b17e6aafe91a91b0b3b4773bb123e37aa4c9b | |||
v1.0 | complete | Data_Structure | Data_Structure_4273_C | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def bogo_simulation_sort(arr: list, max_iterations: int) -> list:
"""
Bogo-Simulation Sort that shuffles the array until it's sorted or reaches t... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def bogo_simulation_sort(arr, max_iterations):
"""
Bogo-Simulation Sort that shuffles the array until it's sorted or reaches the maximum number o... | from solution import bogo_simulation_sort
def test_bogo_simulation_sort_sorted_array():
arr = [1, 2, 3, 4, 5]
max_iterations = 1000
sorted_arr = bogo_simulation_sort(arr, max_iterations)
assert sorted_arr == [1, 2, 3, 4, 5]
def test_bogo_simulation_sort_reverse_array():
arr = [5, 4, 3, 2, 1]
m... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Bogo-Simulation Sort that shuffles the array until it's sorted or reaches the maximum number of iterati... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef bogo_simulation_sort(arr, max_iterations):\n def is_sorted(arr):\n return all(arr[i] <= arr[i+1] for i in range(len(arr) - 1))\... | trial_gpt4o_2 | {
"original_instruction": "**Task**: Write a Python function that sorts an array using the Bogo Sort algorithm. However, given the impracticality of Bogo Sort, your task is to modernize this algorithm slightly by implementing a \"Bogo-Simulation Sort\" that:\n- Continues shuffling if the array is unsorted.\n- Stops i... | 0.565517 | Data_Structure_4273 | C | [
"is_sorted",
"bogo_simulation_sort"
] | 2 | [
[
"bogo_simulation_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 695a6ae4a23b325365224904eb9ba996a41c1844 | 8ab77a359be8cdc6330983ba17227438d2e8eba6 | |||
v1.0 | complete | Data_Structure | Data_Structure_5313_C | from typing import List, Dict
from enum import Enum
class TraversalState(Enum):
WHITE = 0
GRAY = 1
BLACK = 2
def is_in_cycle(graph: Dict[str, List[str]], traversal_states: Dict[str, TraversalState], vertex: str) -> bool:
"""Helper function to detect cycle from the given vertex."""
# Implement cycl... | from enum import Enum
from typing import List, Dict
class TraversalState(Enum):
WHITE = 0 # Vertex has not been visited yet
GRAY = 1 # Vertex is being visited (in the current path)
BLACK = 2 # Vertex and all its descendants have been completely visited
def is_in_cycle(graph, traversal_states, vertex):... | from solution import contains_cycle
def test_no_cycle():
graph = {'A': ['B', 'C'],
'B': ['D'],
'C': ['F'],
'D': ['E', 'F'],
'E': [],
'F': []}
assert not contains_cycle(graph)
def test_with_cycle():
graph = {'A': ['B', 'C'],
'B':... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from enum import Enum\nfrom typing import Dict, List\n\nclass TraversalState(Enum):\n WHITE = 0 # Vertex has not been visited\n GRAY = 1 # Vertex is ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Cycle Detection in a Directed Graph Using DFS\n\nYou are given a directed graph represented as an adjacency list. Your task is to write a function `contains_cycle(graph)` that determines whether the graph contains a cycle.\n\n#### Function Signature\n```python\ndef contains_cy... | 0.520105 | Data_Structure_5313 | C | [
"is_in_cycle",
"contains_cycle"
] | 2 | [
[
"contains_cycle",
"is_in_cycle"
]
] | 1 | [] | false | [
"TraversalState"
] | true | pytest | true | [] | true | a12bafade052c81b729016f6ad7ac9e0a006fb11 | 2a4ff4a77b5af6501a3f7acba6d7b9d498cc83dc | |||
v1.0 | complete | Data_Structure | Data_Structure_3778_C | def heap_sort(arr):
"""
This function should sort an array using both max heap and min heap logic.
Parameters:
arr (list): The list of integers to be sorted.
Returns:
list: The sorted list.
"""
pass
def max_heapify(arr, n, i):
"""
This helper function builds a max heap... | def heap_sort(arr):
"""
This function sorts an array using both max heap and min heap logic.
For the purpose of this task, we will implement the max heap logic.
Parameters:
arr (list): The list of integers to be sorted.
Returns:
list: The sorted list.
"""
n = len(arr)
... | from solution import heap_sort
def test_heap_sort_simple_case():
assert heap_sort([4, 7, 3, 9, 1]) == [1, 3, 4, 7, 9]
def test_heap_sort_already_sorted():
assert heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
assert heap_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_heap_sort_all_equal_elements():
... | [
{
"docstring": "This function sorts an array using both max heap and min heap logic.\nFor the purpose of this task, we will implement the max heap logic.\n\nParameters:\narr (list): The list of integers to be sorted.\n\nReturns:\nlist: The sorted list.",
"function_declaration": "def heap_sort(arr):",
"f... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_heapify(arr, n, i):\n \"\"\"\n This helper function ensures max heap property for a given node.\n \n Parameters:\n arr (list): The list... | trial_gpt4o_1 | {
"original_instruction": "### **Heap Sort Implementation and Analysis Task**\n\n**Objective**: Implement Heap Sort algorithm using both a max heap and a min heap to sort an array in ascending order. Then, analyze the performance and properties of your implementation.\n\n---\n\n**Context**:\n\nYou are provided with t... | 0.612168 | Data_Structure_3778 | C | [
"heap_sort",
"max_heapify",
"min_heapify"
] | 3 | [
[
"heap_sort",
"max_heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f191095e5766a5bf1b01a7f0a9412a6e7e6107cd | bd5d52d98a4193ea3f0507df79d0d85c59a40455 | |||
v1.0 | complete | Data_Structure | Data_Structure_3057_C | def dinic(capacity, source, sink):
""" Find the maximum flow from the source to the sink using Dinic's Algorithm.
Args:
capacity (List[List[int]]): Capacity matrix of the directed graph.
source (int): The source node.
sink (int): The sink node.
Returns:
int: The maximum flow from t... | from collections import deque
def bfs_capacity_level(capacity, source, sink, level):
"""
Build a level graph using BFS.
"""
V = len(capacity)
level[:] = [-1] * V
level[source] = 0
queue = deque([source])
while queue:
u = queue.popleft()
for v in range(V):
i... | def test_dinic():
capacity = [
[0, 10, 10, 0, 0, 0],
[0, 0, 2, 4, 8, 0],
[0, 0, 0, 0, 9, 0],
[0, 0, 0, 0, 0, 10],
[0, 0, 0, 6, 0, 10],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert dinic(capacity, source, sink) == 19
def test_dinic_all_edges_same_ca... | [
{
"docstring": "Build a level graph using BFS.",
"function_declaration": "def bfs_capacity_level(capacity, source, sink, level):",
"function_name": "bfs_capacity_level",
"parameter_list": "(capacity, source, sink, level)"
},
{
"docstring": "Use DFS to find an augmenting path and send flow.",... | [
0,
0,
0,
0,
1,
0,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(level, capacity, flow, source, sink):\n level[source] = 0\n queue = deque([source])\n while queue:\n ... | trial_gpt4o_8 | {
"original_instruction": "## Problem Statement\n\nYou are given the capacity matrix of a directed graph, along with a source and sink node. The objective is to find the maximum flow from the source to the sink using Dinic's Algorithm. Your task is to implement the Dinic's algorithm as described below to find the max... | 0.526161 | Data_Structure_3057 | C | [
"bfs_capacity_level",
"dfs_capacity_flow",
"dinic"
] | 3 | [
[
"dinic",
"bfs_capacity_level"
],
[
"dinic",
"dfs_capacity_flow"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | c896117799a764a18b95658733147ebfd056bad2 | fcbbaffaac3c0cd2cb9230ef6f2c10a77c6d0c04 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.