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_20489_C | def pancake_sort(arr):
""" Perform Pancake Sort on the input list `arr`.
>>> pancake_sort([3, 6, 2, 7, 4])
[2, 3, 4, 6, 7]
>>> pancake_sort([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> pancake_sort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>> pancake_sort([])
[]
>>> pancake_sort([7])
[7]
... | def flip(arr, end):
"""
Helper function to flip the subarray from start to end (inclusive).
"""
start = 0
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
def pancake_sort(arr):
"""
Perform Pancake Sort on the input list `arr`.
"... | from solution import pancake_sort
def test_pancake_sort_basic():
assert pancake_sort([3, 6, 2, 7, 4]) == [2, 3, 4, 6, 7]
def test_pancake_sort_sorted_array():
assert pancake_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_pancake_sort_reverse_sorted_array():
assert pancake_sort([5, 4, 3, 2, 1]) == [1, ... | [
{
"docstring": "Helper function to flip the subarray from start to end (inclusive).",
"function_declaration": "def flip(arr, end):",
"function_name": "flip",
"parameter_list": "(arr, end)"
},
{
"docstring": "Perform Pancake Sort on the input list `arr`.",
"function_declaration": "def pan... | [
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 flip(arr, k):\n \"\"\"\n Helper function to reverse the order of the first k elements in the array.\n \"\"\"\n return arr[:k][::-1] + arr[k:]\... | trial_gpt4o_2 | {
"original_instruction": "You are given a function that implements Pancake Sort, an inefficient but interesting sorting algorithm. Pancake Sort works by flipping subarrays (like flipping segments of a stack of pancakes) to move the maximum unsorted element to its correct position iteratively.\n\n#### Task\nWrite a f... | 0.776209 | Data_Structure_20489 | C | [
"flip",
"pancake_sort"
] | 2 | [
[
"pancake_sort",
"flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 03f1f1ba0aed2930eae4079690b4862a0664fd6a | c8f1401ca7a29a2f3d6418ad6bf140a42681ff66 | |||
v1.0 | complete | Data_Structure | Data_Structure_20793_C | from typing import List
def compute_totients(arr: List[int]) -> List[int]:
""" Compute Euler's Totient Function for each integer in the list.
Args:
arr (List[int]): A list of positive integers.
Returns:
List[int]: A list of totient results corresponding to each integer in `arr`.
... | from typing import List
def compute_totient(n: int) -> int:
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1
if n > 1:
result -= result // n
return result
def compute_totients(ar... | from solution import compute_totients
def test_compute_totients_basic():
assert compute_totients([1, 2, 3, 4, 5]) == [1, 1, 2, 2, 4]
assert compute_totients([6, 25, 100]) == [2, 20, 40]
def test_compute_totients_single_element():
assert compute_totients([10]) == [4]
assert compute_totients([7]) == [6]... | [
{
"docstring": null,
"function_declaration": "def compute_totient(n):",
"function_name": "compute_totient",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def compute_totients(arr):",
"function_name": "compute_totients",
"parameter_list": "(arr)"
}
] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef compute_totients(arr: List[int]) -> List[int]:\n \"\"\"\n Computes Euler's Totient Function for each integer in the given... | trial_gpt4o_2 | {
"original_instruction": "### Problem: Compute Euler's Totient Function for an Array of Integers\n\nYour task is to write a function that computes the totient function (ϕ(n)) for each integer in a list. You will be given an array of integers and must return an array of totient function results corresponding to each ... | 0.605211 | Data_Structure_20793 | C | [
"compute_totient",
"compute_totients"
] | 2 | [
[
"compute_totients",
"compute_totient"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 61956fa8865dbfad7135185fa4ce2ef1064cc434 | e9299b5de0e83d89e7140415efbb8ba41bdb5a4f | |||
v1.0 | complete | Data_Structure | Data_Structure_20643_C | import random
from typing import List
def quick_sort_optimized(arr: List[int]) -> List[int]:
"""Sort an array using an optimized Quick Sort algorithm.
This function uses a randomized pivot to minimize the risk of hitting the
worst-case time complexity and switches to Insertion Sort for small
parti... | import random
def insertion_sort(arr, low, high):
for i in range(low + 1, high + 1):
key = arr[i]
j = i - 1
while j >= low and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def partition(arr, low, high):
pivot_index = random.randint(low, high... | from solution import quick_sort_optimized
def test_sorted_array():
assert quick_sort_optimized([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert quick_sort_optimized([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_random_array():
arr = [3, 6, 8, 10, 1, 2, 1]
assert quick_sort_o... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, low, high):",
"function_name": "insertion_sort",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter_l... | [
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 quick_sort_optimized(arr):\n if len(arr) <= 1:\n return arr\n else:\n _quick_sort(arr, 0, len(arr) - 1)\n return a... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with implementing an improved version of the Quick Sort algorithm to handle some of its common drawbacks. In particular, you need to implement the following enhancements:\n\n1. Implement the Quick Sort algorithm using a randomized pivot to minimize the risk of hitting the wor... | 0.65277 | Data_Structure_20643 | C | [
"insertion_sort",
"partition",
"quick_sort",
"quick_sort_optimized"
] | 4 | [
[
"quick_sort",
"insertion_sort"
],
[
"quick_sort",
"partition"
],
[
"quick_sort_optimized",
"quick_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 0715a208752e96f5b960d837a966305c0af43d3f | f9eee0689eda2a89239c19e2ba0bdc10a3f505d9 | |||
v1.0 | complete | Data_Structure | Data_Structure_20635_C | from typing import List
def find_primitive_root(n: int) -> List[int]:
""" Returns a list of all primitive roots of n.
>>> find_primitive_root(13) == [2, 6, 7, 11]
>>> find_primitive_root(10) == []
>>> find_primitive_root(1) == [0]
""" | from typing import List
import math
def gcd(a: int, b: int) -> int:
while b:
a, b = b, a % b
return a
def find_primitive_root(n: int) -> List[int]:
def is_primitive_root(root: int, n: int, totient: int) -> bool:
required = set(range(1, n))
seen = set()
current = root
... | from solution import find_primitive_root
def test_find_primitive_root_prime():
assert find_primitive_root(13) == [2, 6, 7, 11]
def test_find_primitive_root_non_prime():
assert find_primitive_root(10) == []
def test_find_primitive_root_minimal():
assert find_primitive_root(1) == [0]
def test_find_primiti... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def find_primitive_root(n):",
"function_name": "find_primitive_root",
"parameter_list": "(n)"
},
{
"docstring... | [
0,
0,
0,
1,
0,
0,
0,
1,
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 math import gcd\nfrom typing import List\n\ndef compute_totient(n: int) -> int:\n result = n\n p = 2\n while p * p <= n:\n if n % p == 0:... | trial_gpt4o_7 | {
"original_instruction": "Find Primitive Roots\n\nGiven a positive integer n, your task is to write a function that finds all primitive roots of n. If no primitive roots exist, return an empty list.\n\n### Function Signature\n\n```python\ndef find_primitive_root(n: int) -> List[int]:\n \"\"\" Returns a list of al... | 0.515331 | Data_Structure_20635 | C | [
"gcd",
"find_primitive_root"
] | 2 | [
[
"find_primitive_root",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e4a5fc98f292fc90e582b0355dd0dbe956cb98f6 | 3b909a4df1faeb18b74d99be11c110020aa8fa5a | |||
v1.0 | complete | Data_Structure | Data_Structure_20316_C | def optimized_quick_sort(arr):
"""
Sorts the array `arr` using an optimized quick sort algorithm with median-of-three pivot selection.
Parameters:
arr (list): A list of comparable elements.
Returns:
list: A sorted version of `arr`.
"""
from solution import optimized_quick_sort
de... | def median_of_three(arr, low, high):
mid = (low + high) // 2
if arr[low] > arr[mid]:
arr[low], arr[mid] = arr[mid], arr[low]
if arr[low] > arr[high]:
arr[low], arr[high] = arr[high], arr[low]
if arr[mid] > arr[high]:
arr[mid], arr[high] = arr[high], arr[mid]
return mid
def p... | from solution import optimized_quick_sort
def test_sorted():
assert optimized_quick_sort([1, 2, 3, 4]) == [1, 2, 3, 4]
def test_reverse_sorted():
assert optimized_quick_sort([4, 3, 2, 1]) == [1, 2, 3, 4]
def test_unsorted():
assert optimized_quick_sort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10... | [
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_quick_sort(arr):\n \"\"\"\n Sorts the array `arr` using an optimized quick sort algorithm with median-of-three pivot selection.\n \n ... | trial_gpt4o_2 | {
"original_instruction": "### Quick Sort Implementation with Median-of-Three Pivot Selection\n\n**Scenario**:\nThe company you are working for has data analysis software that needs to efficiently sort large datasets. Your manager has noted that the conventional Quick Sort algorithm sometimes performs poorly on nearl... | 0.641191 | Data_Structure_20316 | C | [
"median_of_three",
"partition",
"quick_sort_recursive",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"quick_sort_recursive"
],
[
"partition",
"median_of_three"
],
[
"quick_sort_recursive",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 240b7eb164ac6ee94b808abb9a6bd5cc9e77c4b8 | 38570231d901144725df20ae717ba617302cf242 | |||
v1.0 | complete | Data_Structure | Data_Structure_21024_C | def fib_matrix(n: int) -> int:
""" Compute the nth Fibonacci number using matrix exponentiation.
>>> fib_matrix(0) == 0
>>> fib_matrix(1) == 1
>>> fib_matrix(10) == 55
>>> fib_matrix(100) == 354224848179261915075
""" | def matrix_mult(A, B):
"""
Multiplies two 2x2 matrices.
"""
return [
[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]
]
def matrix_pow(M, power):
"""
Exponentiates m... | from solution import fib_matrix
def test_fib_matrix_base_cases():
assert fib_matrix(0) == 0
assert fib_matrix(1) == 1
def test_fib_matrix_small_cases():
assert fib_matrix(2) == 1
assert fib_matrix(3) == 2
assert fib_matrix(4) == 3
assert fib_matrix(5) == 5
def test_fib_matrix_larger_cases():
... | [
{
"docstring": "Multiplies two 2x2 matrices.",
"function_declaration": "def matrix_mult(A, B):",
"function_name": "matrix_mult",
"parameter_list": "(A, B)"
},
{
"docstring": "Exponentiates matrix M to the given power using exponentiation by squaring.",
"function_declaration": "def matrix... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fib_matrix(n: int) -> int:\n \"\"\"\n Compute the nth Fibonacci number using matrix exponentiation method.\n \"\"\"\n if n == 0:\n retu... | trial_gpt4o_2 | {
"original_instruction": "### Fibonacci Focus\n\nYou are tasked with writing an optimized function to compute the nth Fibonacci number using matrix exponentiation. This method should maintain a polynomial time complexity.\n\nThe Fibonacci numbers are defined as:\n- F0 = 0, F1 = 1\n- Fn = Fn-1 + Fn-2 for n > 1\n\nMat... | 0.848973 | Data_Structure_21024 | C | [
"matrix_mult",
"matrix_pow",
"fib_matrix"
] | 3 | [
[
"fib_matrix",
"matrix_pow"
],
[
"matrix_pow",
"matrix_mult"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 98f759b74d42aef5c9cb0c8b6322a20714f91918 | c5befbfbc0776a44d792dc2f7ddd1a3f0aae8a71 | |||
v1.0 | complete | Data_Structure | Data_Structure_20598_C | def enhanced_pancake_sort(arr: List[int]) -> List[int]:
""" Sorts an array using the enhanced Pancake Sort algorithm to minimize the number of flips.
>>> enhanced_pancake_sort([3, 2, 4, 1])
[1, 2, 3, 4]
>>> enhanced_pancake_sort([1])
[1]
>>> enhanced_pancake_sort([1, 2, 3, 4, 5])
[1, 2, 3, 4... | from typing import List
def flip(arr: List[int], k: int):
"""Helper function to reverse the array from start up to index k."""
arr[:k+1] = arr[:k+1][::-1]
def enhanced_pancake_sort(arr: List[int]) -> List[int]:
"""Sorts an array using the enhanced Pancake Sort algorithm."""
n = len(arr)
for size i... | from solution import enhanced_pancake_sort
def test_enhanced_pancake_sort_example_case():
assert enhanced_pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
def test_enhanced_pancake_sort_single_element():
assert enhanced_pancake_sort([1]) == [1]
def test_enhanced_pancake_sort_already_sorted():
assert enhanced_p... | [
{
"docstring": "Helper function to reverse the array from start up to index k.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Sorts an array using the enhanced Pancake Sort algorithm.",
"function_declaration": "def ... | [
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": "from typing import List\n\ndef flip(arr: List[int], k: int) -> None:\n \"\"\"\n Flips the first k elements of the array arr in ... | trial_gpt4o_2 | {
"original_instruction": "Pancake Sort Optimization and Enhancement\n\nYou are given an array of integers that you need to sort using the Pancake Sort algorithm. Write a function `enhanced_pancake_sort` that sorts the array in ascending order. Your task is to first improve the basic pancake sort by minimizing the nu... | 0.743653 | Data_Structure_20598 | C | [
"flip",
"enhanced_pancake_sort"
] | 2 | [
[
"enhanced_pancake_sort",
"flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 490475338da4386e9e2c72af113f958ca1bc430b | c298fa8caa9a6ca1258bbbff23f34c8241b0a88c | |||
v1.0 | complete | Data_Structure | Data_Structure_20423_C | [Completion Task in Python]
def find_mod_inverse(a, m) -> int:
'''
Find and return the modular inverse of a modulo m.
'''
# your code here
def is_prime(num) -> bool:
'''
Determine if the number num is prime.
'''
# your code here
def generate_prime(bits: int, seed=None) -> int:
'''... | import random
def find_mod_inverse(a, m):
"""
Find and return the modular inverse of a modulo m.
"""
def egcd(a, b):
if a == 0:
return b, 0, 1
else:
g, x, y = egcd(b % a, a)
return g, y - (b // a) * x, x
g, x, y = egcd(a, m)
if g != 1:
... | import pytest
from solution import find_mod_inverse, is_prime, generate_prime
def test_find_mod_inverse():
assert find_mod_inverse(3, 11) == 4
assert find_mod_inverse(10, 17) == 12
assert find_mod_inverse(2, 5) == 3
with pytest.raises(ValueError):
find_mod_inverse(3, 6) # 3 and 6 are not co-p... | [
{
"docstring": "Find and return the modular inverse of a modulo m.",
"function_declaration": "def find_mod_inverse(a, m):",
"function_name": "find_mod_inverse",
"parameter_list": "(a, m)"
},
{
"docstring": "Determine if the number num is prime.",
"function_declaration": "def is_prime(num... | [
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 find_mod_inverse(a, m):\n \"\"\"\n Find and return the modular inverse of a modulo m.\n \"\"\"\n def egcd(a, b):\n if ... | trial_gpt4o_0 | {
"original_instruction": "### RSA Key Generation, Encryption, and Decryption\n\nAs part of your assessments, you need to implement components of the RSA encryption algorithm to measure the understanding of your students. Your task is to complete the implementation of the RSA cryptographic algorithm for secure data t... | 0.60798 | Data_Structure_20423 | C | [
"find_mod_inverse",
"is_prime",
"generate_prime"
] | 3 | [
[
"generate_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 57f7521e733d9b356a53b2e142dc42c6b5589096 | 26acb6c443f7ffdf6e3c1291bb96cd3f53521649 | |||
v1.0 | complete | Data_Structure | Data_Structure_20593_C | def generate_key_pair(bit_length):
"""
Generate RSA public and private keys.
:param bit_length: Bit length of the modulus n.
:return: A tuple (n, e, d).
"""
pass
def encrypt(data, e, n):
"""
Encrypt data using RSA public key.
:param data: The plaintext data (an integer) to be encr... | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(length):
"""
Generate an odd integer randomly
"""
p = random.getrandbits(length)
# apply a mask to set MSB and LSB to 1
p |= (1 << length - 1) | 1
return p
def generate_prime_number(length):
"""
Gener... | from solution import generate_key_pair, encrypt, decrypt
def test_generate_key_pair():
n, e, d = generate_key_pair(16)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_encrypt_decrypt():
n, e, d = generate_key_pair(32)
data = 42
encrypted = encrypt(dat... | [
{
"docstring": "Generate an odd integer randomly",
"function_declaration": "def generate_prime_candidate(length):",
"function_name": "generate_prime_candidate",
"parameter_list": "(length)"
},
{
"docstring": "Generate a prime",
"function_declaration": "def generate_prime_number(length):"... | [
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 sympy import isprime, mod_inverse\nimport math\n\ndef generate_prime_candidate(length):\n \"\"\" Generate an odd integer randomly \"\"\... | trial_gpt4o_1 | {
"original_instruction": "### RSA Encryption/Decryption Implementations\n\n#### Background\nRSA is one of the first public-key cryptosystems and is widely used for secure data transmission. Unlike symmetric key cryptosystems, RSA relies on a pair of keys:\n- A public key (n, e) for encryption.\n- A private key (n, d... | 0.700388 | Data_Structure_20593 | C | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key_pair",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key_pair",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 6b09c7e2e5d9114d74005f95df1b5858ccff6d40 | 9824531d4500c826c8886bdb6f19e6c9d402cf72 | |||
v1.0 | complete | Data_Structure | Data_Structure_19891_C | from typing import List
def enhanced_radix_sort(array: List[int], simulation: bool = False) -> List[int]:
""" Enhanced Radix Sort that handles negative numbers along with non-negative numbers.
Args:
array (List[int]): A list of integers which can include both negative and non-negative integers.
si... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool):
n = len(arr)
output = [0] * n
count = [0] * 10
# Count occurrences of digits
for i in range(n):
index = arr[i] // exp
count[(index % 10)] += 1
# Update count to have position info
for i ... | from solution import enhanced_radix_sort
def test_empty_array():
assert enhanced_radix_sort([]) == []
def test_all_positives():
assert enhanced_radix_sort([3, 1, 4, 1, 5, 9]) == [1, 1, 3, 4, 5, 9]
def test_all_negatives():
assert enhanced_radix_sort([-3, -1, -4, -1, -5, -9]) == [-9, -5, -4, -3, -1, -1]
... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation):",
"function_name": "radix_sort",
... | [
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 counting_sort(arr: List[int], exp: int, simulation: bool):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n ... | trial_gpt4o_0 | {
"original_instruction": "### Question: Implement and Enhance Radix Sort to Handle Negative Numbers\n\nYou are tasked with implementing an enhanced version of the Radix Sort algorithm provided. The provided Radix Sort implementation sorts lists of non-negative integers. Extend this functionality to handle lists that... | 0.707527 | Data_Structure_19891 | C | [
"counting_sort",
"radix_sort",
"enhanced_radix_sort"
] | 3 | [
[
"enhanced_radix_sort",
"radix_sort"
],
[
"radix_sort",
"counting_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8dab96355494e595ae593dfe66a0d8920d6ffd71 | 91460e9312cb51d98e4881d9f2c0845e98faf390 | |||
v1.0 | complete | Data_Structure | Data_Structure_20957_C | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Checks if the given list is sorted in ascending order.
>>> is_sorted([1, 2, 3, 4, 5]) True
>>> is_sorted([1, 3, 2, 4, 5]) False
"""
pass
def bogo_sort_with_check(arr: List[int]) -> List[int]:
"""
Sorts the... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Checks if the given list is sorted in ascending order.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort_with_check(arr: List[int]) -> List[int]:
... | from solution import is_sorted, bogo_sort_with_check
def test_is_sorted_empty_list():
assert is_sorted([]) is True
def test_is_sorted_single_element():
assert is_sorted([1]) is True
def test_is_sorted_sorted_list():
assert is_sorted([1, 2, 3, 4, 5]) is True
def test_is_sorted_unsorted_list():
assert... | [
{
"docstring": "Checks if the given list is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the list using an improved Bogo Sort algorithm that stops early if the list becomes sorted.... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Check if the given list is sorted in ascending order.\n \... | trial_gpt4o_2 | {
"original_instruction": "---\n### Problem: Sorting Checker\n\nYou have been provided with a highly inefficient sorting algorithm called Bogo Sort. Your task is to develop a more efficient checker function to verify if the list is sorted in ascending order. Alongside, implement a new function that uses this sorting ... | 0.645042 | Data_Structure_20957 | C | [
"is_sorted",
"bogo_sort_with_check"
] | 2 | [
[
"bogo_sort_with_check",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c7ed444fe1495c465f69e90f928bcb43cbc48704 | 9ab4cb7ba6b321df2924cdb84eb58d4889fd3fa4 | |||
v1.0 | complete | Data_Structure | Data_Structure_21006_C | from typing import List
def hybrid_merge_sort(arr: List[int], threshold: int = 10) -> List[int]:
"""
Implement an optimized version of the Merge Sort algorithm for sorting a list of integers.
This implementation uses a hybrid approach where Merge Sort is used for large subarrays,
and Insertion S... | from typing import List
def insertion_sort(arr: List[int], left: int, right: int):
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def merge(arr: List[int], left: int, ... | from solution import hybrid_merge_sort
def test_hybrid_merge_sort_empty():
assert hybrid_merge_sort([]) == []
def test_hybrid_merge_sort_single_element():
assert hybrid_merge_sort([1]) == [1]
def test_hybrid_merge_sort_two_elements():
assert hybrid_merge_sort([2, 1]) == [1, 2]
def test_hybrid_merge_sort... | [
{
"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, mid, right):",
"function_name": "merge",
"paramete... | [
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) -> None:\n \"\"\"\n Sorts the subarray arr[left:right+1] using inse... | trial_gpt4o_2 | {
"original_instruction": "### Problem Description\n\nYou are asked to implement an optimized version of the Merge Sort algorithm for sorting a list of integers. Your implementation should focus on efficiency and correctness while demonstrating a sound understanding of the merge sort process. Instead of using subarra... | 0.608277 | Data_Structure_21006 | C | [
"insertion_sort",
"merge",
"hybrid_merge_sort"
] | 3 | [
[
"hybrid_merge_sort",
"insertion_sort"
],
[
"hybrid_merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 08ff3dfc21ccd0bdff3874be683a400b45bfcec8 | f9def354d42bc9fb0b68731470122e776b5d7733 | |||
v1.0 | complete | Data_Structure | Data_Structure_20483_C | import math
from typing import Tuple, Dict
def euclidean_distance(v1: Tuple[int, ...], v2: Tuple[int, ...]) -> float:
"""
Computes the Euclidean distance between two vectors.
:param v1: Tuple of integers
:param v2: Tuple of integers
:return: Euclidean distance as a float
"""
return math.sqr... | import math
def euclidean_distance(v1, v2):
"""
Computes the Euclidean distance between two vectors
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def nearest_neighbor(x, tSet):
"""
Finds and returns the class label of the nearest neighbor of vector x in the training set tSet.... | from solution import nearest_neighbor
def test_nn_exact_match():
x = (1, 2)
tSet = {
(2, 3): "A",
(4, 5): "B",
(1, 2): "C"
}
assert nearest_neighbor(x, tSet) == "C"
def test_nn_closest_point():
x = (1, 2)
tSet = {
(2, 3): "A",
(4, 5): "B",
(1, 3)... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(x, y):\n \"\"\"\n Computes the Euclidean distance between two vectors x and y.\n \"\"\"\n return math.sqrt(s... | trial_gpt4o_2 | {
"original_instruction": "### Nearest Neighbor Classification\n\nIn this assessment, you will implement and extend the Nearest Neighbor algorithm based on the provided code snippets. The goal is to classify a given test point by finding its nearest neighbor in a training set of labeled vectors.\n\n### Problem Statem... | 0.671468 | Data_Structure_20483 | C | [
"euclidean_distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4bb9a6fd3576d766d719a21d1bec14f9a806ac5f | 62908954fb563a9e32ae5ae27ef3f6453d9efc1e | |||
v1.0 | complete | Data_Structure | Data_Structure_21051_C | def generate_rsa_keys(p: int, q: int) -> (int, int, int):
"""
Generate RSA keys given two prime numbers p and q.
Args:
p (int): A prime number.
q (int): A prime number.
Returns:
(public_key, private_key, n): A tuple containing the public key, private key, and n.
>>> generate_rsa_k... | def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def extended_gcd(a, b):
if a == 0:
return b, 0, 1
gcd, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y
def modular_inverse(a, m):
gcd, x, _ = extended_gcd(a, m)
if gcd != 1:
... | from solution import generate_rsa_keys
def test_generate_rsa_keys_small_primes():
p, q = 17, 23
public_key, private_key, n = generate_rsa_keys(p, q)
assert public_key == 65537
assert n == 391
assert (public_key * private_key) % ((p - 1) * (q - 1)) == 1
def test_generate_rsa_keys_larger_primes():
... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n while b != 0:\n a, b = b, a % b\n return a\n\ndef extended_gcd(a, b):\n if a == 0:\n return b, 0, 1\n gcd, x1, y1 =... | trial_gpt4o_0 | {
"original_instruction": "RSA Public Key Cryptosystem\n\n#### Context\nThe RSA public key cryptosystem heavily relies on number theory and concepts such as the Extended Euclidean Algorithm and Modular Inverse. Given two large prime numbers p and q, the RSA algorithm involves calculating the public and private keys f... | 0.599281 | Data_Structure_21051 | C | [
"gcd",
"extended_gcd",
"modular_inverse",
"generate_rsa_keys"
] | 4 | [
[
"generate_rsa_keys",
"gcd"
],
[
"generate_rsa_keys",
"modular_inverse"
],
[
"modular_inverse",
"extended_gcd"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | fba88d7ed60aafdcb020bb981723eac2dab1c473 | 1e3d24dbaac4bfbed6fa9e618e9b2dea4a5ef4b4 | |||
v1.0 | complete | Data_Structure | Data_Structure_20743_C | from typing import List
def binary_search_iterative(array: List[int], target: int) -> int:
"""
Perform binary search to find the first occurrence of the target using an iterative approach.
:param array: List of integers sorted in ascending order.
:param target: The integer to search for.
:return: ... | from typing import List
def binary_search_iterative(array: List[int], target: int) -> int:
"""
Perform binary search to find the first occurrence of the target using iterative approach.
"""
left, right = 0, len(array) - 1
result = -1
while left <= right:
mid = (left + right) // 2
... | from solution import binary_search_iterative, binary_search_recursive
def test_binary_search_iterative():
array1 = [1, 2, 4, 4, 5, 6, 8]
target1 = 4
assert binary_search_iterative(array1, target1) == 2
array2 = [1, 3, 5, 7, 9]
target2 = 2
assert binary_search_iterative(array2, target2) == -1
... | [
{
"docstring": "Perform binary search to find the first occurrence of the target using iterative approach.",
"function_declaration": "def binary_search_iterative(array, target):",
"function_name": "binary_search_iterative",
"parameter_list": "(array, target)"
},
{
"docstring": "Helper functi... | [
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_iterative(array: List[int], target: int) -> int:\n left, right = 0, len(array) - 1\n result = -1\n \n ... | trial_gpt4o_2 | {
"original_instruction": "### Binary Search Enhancement\n\n#### Problem Statement\n\nYou are given an array of integers sorted in ascending order and a target integer. Your task is to write a function that returns the index of the first occurrence of the target in the array using binary search. If the target is not ... | 0.655225 | Data_Structure_20743 | C | [
"binary_search_iterative",
"binary_search_recursive_helper",
"binary_search_recursive"
] | 3 | [
[
"binary_search_recursive",
"binary_search_recursive_helper"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d6617fc5e1fa092dd8d363624bf8e97fb02672a0 | e5d3bfa1cbeab6f48217d90625180e561e62d497 | |||
v1.0 | complete | Data_Structure | Data_Structure_21098_C | def extended_gcd(a: int, b: int) -> (int, int, int):
""" Implements the Extended Euclidean Algorithm.
Calculates integers x and y such that ax + by = gcd(a, b).
Args:
a (int): First number.
b (int): Second number.
Returns:
tuple: (x, y, gcd(a, b))
Example:
>>> extended... | def extended_gcd(a, b):
"""
Implements the Extended Euclidean Algorithm.
Calculates integers x and y such that ax + by = gcd(a, b).
Args:
a (int): First number.
b (int): Second number.
Returns:
tuple: (x, y, gcd(a, b))
"""
if b == 0:
return (1, 0, a)
else:
... | from solution import extended_gcd, modular_inverse
def test_extended_gcd():
assert extended_gcd(30, 12) == (1, -2, 6)
assert extended_gcd(12, 30) == (-2, 1, 6) # Different sequence yields the same GCD
assert extended_gcd(101, 10) == (1, -10, 1)
assert extended_gcd(0, 5) == (0, 1, 5)
assert extende... | [
{
"docstring": "Implements the Extended Euclidean Algorithm.\nCalculates integers x and y such that ax + by = gcd(a, b).\n\nArgs:\na (int): First number.\nb (int): Second number.\n\nReturns:\ntuple: (x, y, gcd(a, b))",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
... | [
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 extended_gcd(a, b):\n \"\"\"\n Computes the extended GCD of a and b.\n \n Args:\n a (int): first integer\n b (int): second integ... | trial_gpt4o_2 | {
"original_instruction": "**Extended Euclidean Algorithm & Modular Inverse Implementation**\n\nYou have been given the task of implementing two functions that utilize the Extended Euclidean Algorithm to compute:\n1. The GCD of two integers, and their corresponding coefficients.\n2. The modular inverse of an integer ... | 0.619457 | Data_Structure_21098 | C | [
"extended_gcd",
"modular_inverse"
] | 2 | [
[
"modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4b2f73466abdfa7b4fcbc7f37b354b8140a105b9 | aba5e017c6ed73490008113ec8ef1e18457bae8e | |||
v1.0 | complete | Data_Structure | Data_Structure_21101_C | import math
from typing import Callable
def is_prime(num: int) -> bool:
"""
Helper function to check if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if nu... | import math
def is_prime(num):
"""
Helper function to check if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
... | from solution import next_prime
def test_next_prime_positive():
assert next_prime(10) == 11
assert next_prime(17) == 19
assert next_prime(20) == 23
assert next_prime(1000) == 1009
def test_next_prime_negative_and_zero():
assert next_prime(-5) == 2
assert next_prime(0) == 2
assert next_prim... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the smallest prime number greater than n.",
"function_declaration": "def next_prime(n):",
"... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_prime(num):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if ... | trial_gpt4o_0 | {
"original_instruction": "Write a function called `next_prime` that takes an integer `n` and returns the smallest prime number larger than `n`. The function should efficiently utilize the given `prime_check` function as part of its solution. \n\n### Input\n* An integer `n` (−10^6 ≤ n ≤ 10^6)\n\n### Output\n* Returns... | 0.833646 | Data_Structure_21101 | C | [
"is_prime",
"next_prime"
] | 2 | [
[
"next_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7ea123cd8569b4117888b22d8b9a13ebb4808b14 | d394b9f744cac8836e974b592fe63f7a1fcfaef8 | |||
v1.0 | complete | Data_Structure | Data_Structure_20877_C | from typing import List
def find_pattern_occurrences(text: str, pattern: str) -> List[int]:
"""
Find all starting indices where the pattern appears as a substring in the text using the KMP algorithm.
Args:
- text (str): The document in which to search the word. It can be empty.
- pattern (str): Th... | from typing import List
def compute_lps(pattern: str) -> List[int]:
"""
Helper function to compute the Longest Prefix Suffix (LPS) array used in KMP algorithm.
"""
lps = [0] * len(pattern)
length = 0 # length of the previous longest prefix suffix
i = 1
while i < len(pattern):
... | from solution import find_pattern_occurrences
def test_find_pattern_occurrences_basic():
assert find_pattern_occurrences('hello there hero!', 'he') == [0, 7, 12]
def test_find_pattern_occurrences_multiple_matches():
assert find_pattern_occurrences('abcabcabc', 'abc') == [0, 3, 6]
def test_find_pattern_occurr... | [
{
"docstring": "Helper function to compute the Longest Prefix Suffix (LPS) array used in KMP algorithm.",
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": null,
"function_declaration": "def find_pattern_o... | [
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 compute_lps(pattern: str) -> List[int]:\n \"\"\"\n Helper function to compute the Longest Prefix Suffix (LPS) array used ... | trial_gpt4o_0 | {
"original_instruction": "**Problem Statement**:\n\nYou are given a large document (text) and a specific word (pattern) that you need to search within the text. Use the Knuth-Morris-Pratt (KMP) algorithm to efficiently find all the starting indices where the word appears as a substring in the document.\n\n**Function... | 0.625157 | Data_Structure_20877 | C | [
"compute_lps",
"find_pattern_occurrences"
] | 2 | [
[
"find_pattern_occurrences",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7c00148483779166f59ac1b11bc7e5c9d5c7dacc | e290d4683e83d0b8558ea7d85e8e62999abfa4c1 | |||
v1.0 | complete | Data_Structure | Data_Structure_21404_C | import random
def is_probably_prime(n: int, k: int) -> bool:
"""
Uses the Miller-Rabin primality test to determine whether n is a probable prime.
>>> is_probably_prime(17, 5)
True
>>> is_probably_prime(18, 5)
False
>>> is_probably_prime(2, 3)
True
>>> is_probably_prime(7919, 4)... | import random
def miller_rabin_pass(a, s, d, n):
"""
Helper function for performing a single Miller-Rabin test.
"""
a_to_power = pow(a, d, n)
if a_to_power == 1:
return True
for _ in range(s - 1):
if a_to_power == n - 1:
return True
a_to_power = pow(a_to_powe... | from solution import is_probably_prime
def test_prime_small_prime_numbers():
assert is_probably_prime(2, 5) == True
assert is_probably_prime(3, 5) == True
assert is_probably_prime(5, 5) == True
assert is_probably_prime(7, 5) == True
assert is_probably_prime(13, 5) == True
assert is_probably_pri... | [
{
"docstring": "Helper function for performing a single Miller-Rabin test.",
"function_declaration": "def miller_rabin_pass(a, s, d, n):",
"function_name": "miller_rabin_pass",
"parameter_list": "(a, s, d, n)"
},
{
"docstring": "Uses the Miller-Rabin primality test to determine whether n is ... | [
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_probably_prime(n: int, k: int) -> bool:\n \"\"\"\n Determines if a number n is probably prime using the Rabin-Miller primality t... | trial_gpt4o_2 | {
"original_instruction": "### Rabin-Miller Primality Test Implementation\n\n#### Problem\nYou are tasked with implementing the Rabin-Miller primality test. Your function should determine whether a given number is prime with high probability. The number tested might be very large, so efficiency is important.\n\n#### ... | 0.814785 | Data_Structure_21404 | C | [
"miller_rabin_pass",
"is_probably_prime"
] | 2 | [
[
"is_probably_prime",
"miller_rabin_pass"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2767179a7ecac9c85786d4e25a0dea28ba4dfa6c | 5376d9682ce03f1e8152f849221f9631c1213d9a | |||
v1.0 | complete | Data_Structure | Data_Structure_20985_C | from typing import List, Dict
def multi_pattern_kmp(text: str, patterns: List[str]) -> Dict[str, List[int]]:
"""
Search for multiple patterns in a given text using KMP algorithm.
Returns a dictionary with pattern as the key and list of start indexes as the value.
>>> multi_pattern_kmp('hello ther... | from typing import List, Dict
def compute_kmp_table(pattern: str) -> List[int]:
"""
Compute the KMP table (also known as the "partial match" table or "failure function")
for a given pattern.
"""
table = [0] * len(pattern)
j = 0 # length of the previous longest prefix suffix
i = 1
while... | def test_compute_kmp_table():
assert compute_kmp_table("ABCDABD") == [0, 0, 0, 0, 1, 2, 0]
assert compute_kmp_table("AAAA") == [0, 1, 2, 3]
assert compute_kmp_table("AABAACAABAA") == [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5]
def test_knuth_morris_pratt():
assert knuth_morris_pratt("ABABDABACDABABCABAB", "ABABC... | [
{
"docstring": "Compute the KMP table (also known as the \"partial match\" table or \"failure function\")\nfor a given pattern.",
"function_declaration": "def compute_kmp_table(pattern):",
"function_name": "compute_kmp_table",
"parameter_list": "(pattern)"
},
{
"docstring": "KMP algorithm fo... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict\n\ndef compute_lps(pattern: str) -> List[int]:\n lps = [0] * len(pattern)\n length = 0 # length of the previous longest p... | trial_gpt4o_1 | {
"original_instruction": "### Knuth-Morris-Pratt String Matching Enhancement\n\nGiven the implementation of the Knuth-Morris-Pratt (KMP) algorithm for string matching, enhance it to handle multiple patterns simultaneously. Specifically, you will implement a function `multi_pattern_kmp` which searches for multiple pa... | 0.602055 | Data_Structure_20985 | C | [
"compute_kmp_table",
"knuth_morris_pratt",
"multi_pattern_kmp"
] | 3 | [
[
"knuth_morris_pratt",
"compute_kmp_table"
],
[
"multi_pattern_kmp",
"knuth_morris_pratt"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 06dbc6464adbea994815c89f8bab48404c34d4f7 | 74846d9de80e33fb49563fd6100d259f099b47e7 | |||
v1.0 | complete | Data_Structure | Data_Structure_21022_C | def reverse_string(s: str, method: str) -> str:
"""
Reverses a string based on the specified method.
Parameters:
s (str): The string to be reversed.
method (str): The method to use for reversal. One of 'recursive', 'iterative', 'pythonic', 'ultra_pythonic'.
Returns:
str: The reversed strin... | def reverse_string(s: str, method: str) -> str:
"""
Reverses a string based on the specified method.
Parameters:
s (str): The string to be reversed.
method (str): The method to use for reversal. One of 'recursive', 'iterative', 'pythonic', 'ultra_pythonic'.
Returns:
str: The revers... | from solution import reverse_string
def test_reverse_string_recursive():
assert reverse_string("hello", "recursive") == "olleh"
assert reverse_string("world", "recursive") == "dlrow"
assert reverse_string("a", "recursive") == "a"
assert reverse_string("", "recursive") == ""
def test_reverse_string... | [
{
"docstring": "Reverses a string based on the specified method.\n\nParameters:\ns (str): The string to be reversed.\nmethod (str): The method to use for reversal. One of 'recursive', 'iterative', 'pythonic', 'ultra_pythonic'.\n\nReturns:\nstr: The reversed string.",
"function_declaration": "def reverse_str... | [
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 reverse_string(s: str, method: str) -> str:\n \"\"\"\n Reverses the given string `s` using the specified method.\n \n :param s: The string to ... | trial_gpt4o_2 | {
"original_instruction": "### Question\n\n**String Reversal Algorithm Implementation**\n\nYou are tasked with implementing a function to reverse a given string using a specified method. The method should be chosen based on the application needs and constraints provided.\n\n**Function Signature**:\n```python\ndef rev... | 0.717616 | Data_Structure_21022 | C | [
"reverse_string",
"_reverse_recursive",
"_reverse_iterative",
"_reverse_pythonic",
"_reverse_ultra_pythonic"
] | 5 | [
[
"reverse_string",
"_reverse_iterative"
],
[
"reverse_string",
"_reverse_pythonic"
],
[
"reverse_string",
"_reverse_recursive"
],
[
"reverse_string",
"_reverse_ultra_pythonic"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 7306b477e276d154befa5c73e2d165d5f959df7b | a756c5a9127e6653efff8b46621147392c83c928 | |||
v1.0 | complete | Data_Structure | Data_Structure_21248_C | def build_tree_inorder(pre: list, post: list) -> list:
"""Construct the full binary tree from pre-order and post-order traversals and return its in-order traversal sequence.
>>> build_tree_inorder([1, 2, 4, 5, 3, 6, 7], [4, 5, 2, 6, 7, 3, 1])
[4, 2, 5, 1, 6, 3, 7]
>>> build_tree_inorder([1], [1])
[1... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def construct_tree(pre, pre_start, pre_end, post, post_start, post_end):
if pre_start > pre_end or post_start > post_end:
return None
root = TreeNode(pre... | from solution import build_tree_inorder
def test_build_tree_inorder_simple():
pre = [1, 2, 4, 5, 3, 6, 7]
post = [4, 5, 2, 6, 7, 3, 1]
expected_inorder = [4, 2, 5, 1, 6, 3, 7]
assert build_tree_inorder(pre, post) == expected_inorder
def test_build_tree_inorder_single_node():
pre = [1]
post = [... | [] | [
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 build_tree_inorder(pre, post):\n # Helper function to construct tree and get inorder traversal\n def construct(pre_index, post_start, post_end):\n ... | trial_gpt4o_2 | {
"original_instruction": "### Binary Tree Construction from Traversal Data\n\nYou are given the pre-order and post-order traversal sequences of a full binary tree. A full binary tree is a binary tree in which every node has either 0 or 2 children. Your task is to reconstruct this full binary tree and return its in-o... | 0.485988 | Data_Structure_21248 | C | [
"construct_tree",
"inorder_traversal",
"build_tree_inorder"
] | 3 | [
[
"build_tree_inorder",
"construct_tree"
],
[
"build_tree_inorder",
"inorder_traversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 912de4c6d2e688a4877fec69a1bca52ab6dd23d9 | da403609cb4dfd177ef0cbf2f1cdde82a9ae7ae9 | |||
v1.0 | complete | Data_Structure | Data_Structure_20134_C | from typing import List, Tuple
def range_query(array: List[int], lower: int, upper: int) -> Tuple[int, int]:
"""
Interpolation Search-Based Range Query.
You are provided with a sorted array of integers and two integers representing a search range [lower, upper].
Design a function that uses the pr... | from typing import List, Tuple
def interpolation_search(array: List[int], target: int) -> int:
low = 0
high = len(array) - 1
while low <= high and target >= array[low] and target <= array[high]:
if low == high:
if array[low] == target:
return low
return -1
... | from solution import range_query
def test_range_query_within_bounds():
assert range_query([1, 3, 5, 7, 9, 11, 13, 15], 5, 13) == (2, 6)
def test_range_query_straddle_bounds():
assert range_query([1, 3, 5, 7, 9, 11, 13, 15], 6, 12) == (3, 5)
def test_range_query_no_match():
assert range_query([1, 3, 5, 7,... | [
{
"docstring": null,
"function_declaration": "def interpolation_search(array, target):",
"function_name": "interpolation_search",
"parameter_list": "(array, target)"
},
{
"docstring": null,
"function_declaration": "def find_start_index(array, lower):",
"function_name": "find_start_in... | [
0,
0,
0,
0,
0,
0,
1,
1,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def interpolation_search(array, x):\n low = 0\n high = len(array) - 1\n\n while low <= high and x >= array[low] and x <= array[high]:\n if low... | trial_gpt4o_6 | {
"original_instruction": "### Interpolation Search-Based Range Query\n\nIn many applications, such as database indexing, quick range queries over sorted data are often needed. Designing a solution to efficiently determine the range of indices where array elements fall within a specified range can significantly enhan... | 0.607506 | Data_Structure_20134 | C | [
"interpolation_search",
"find_start_index",
"find_end_index",
"range_query"
] | 4 | [
[
"find_end_index",
"interpolation_search"
],
[
"find_start_index",
"interpolation_search"
],
[
"range_query",
"find_end_index"
],
[
"range_query",
"find_start_index"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 3bf0894cdd5a237e154011a9f4a841db015fd260 | 9ad123c25e07eebbcf1bc8aea86d7a979b3eb15a | |||
v1.0 | complete | Data_Structure | Data_Structure_20922_C | from enum import Enum
class TraversalState(Enum):
WHITE = 0
GRAY = 1
BLACK = 2
def is_in_cycle(graph, traversal_states, vertex):
"""
Determines if the given vertex is in a cycle.
:param graph: Dictionary representation of the graph.
:param traversal_states: Dictionary representing the stat... | from enum import Enum
class TraversalState(Enum):
WHITE = 0
GRAY = 1
BLACK = 2
def is_in_cycle(graph, traversal_states, vertex):
"""
Determines if the given vertex is in a cycle.
:param graph: Dictionary representation of the graph.
:param traversal_states: Dictionary representing the stat... | def test_empty_graph():
graph = {}
assert contains_cycle(graph) == False
def test_single_vertex_no_edges():
graph = {'A': []}
assert contains_cycle(graph) == False
def test_single_cycle():
graph = {
'A': ['B'],
'B': ['C'],
'C': ['A']
}
assert contains_cycle(graph) =... | [] | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from enum import Enum\n\nclass TraversalState(Enum):\n WHITE = 0\n GRAY = 1\n BLACK = 2\n\ndef is_in_cycle(graph, traversal_states, vertex):\n \"\... | trial_gpt4o_0 | {
"original_instruction": "### Cycle Detection in a Directed Graph\n\n#### Objective:\nWrite Python functions to determine if a directed graph has a cycle. This is crucial in applications like detecting deadlocks in operating systems, where processes and resources can be modeled as a directed graph.\n\n#### Details:\... | 0.567264 | Data_Structure_20922 | C | [
"is_in_cycle",
"contains_cycle"
] | 2 | [
[
"contains_cycle",
"is_in_cycle"
]
] | 1 | [] | false | [
"TraversalState"
] | true | pytest | false | [] | true | f92750db3aba5bebc32fb63a77c5cff474d9d7ba | 3909b772608cb90c6372bd3e85213ed7a4ac024a | |||
v1.0 | complete | Data_Structure | Data_Structure_21437_C | from typing import List
import cmath
import math
def iterative_fft(x: List[complex]) -> List[complex]:
""" Compute the DFT of an array of complex numbers using an iterative approach
>>> iterative_fft([2.0+2j, 1.0+3j, 3.0+1j, 2.0+2j])
[(8+8j), 2j, (2-2j), (-2+0j)]
>>> iterative_fft([1+0j, 1+0j, 1+0j, 1+... | from typing import List
import cmath
import math
def bit_reverse_copy(a):
n = len(a)
result = [0] * n
bits = int(math.log2(n))
for i in range(n):
reveresed_i = int(f'{i:0{bits}b}'[::-1], 2)
result[reveresed_i] = a[i]
return result
def iterative_fft(x: List[complex]) -> List[complex... | from solution import iterative_fft
def test_iterative_fft_simple():
input_signal = [2.0+2j, 1.0+3j, 3.0+1j, 2.0+2j]
expected_output = [8+8j, 2j, 2-2j, -2+0j]
result = iterative_fft(input_signal)
assert all(abs(r - e) < 1e-9 for r, e in zip(result, expected_output))
def test_iterative_fft_power_of_two(... | [
{
"docstring": null,
"function_declaration": "def bit_reverse_copy(a):",
"function_name": "bit_reverse_copy",
"parameter_list": "(a)"
},
{
"docstring": null,
"function_declaration": "def iterative_fft(x):",
"function_name": "iterative_fft",
"parameter_list": "(x)"
}
] | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport cmath\n\ndef iterative_fft(x: List[complex]) -> List[complex]:\n n = len(x)\n levels = n.bit_length() - 1\n y = [0] *... | trial_gpt4o_7 | {
"original_instruction": "### Question: Iterative FFT Implementation\n\nYou are tasked with implementing the Cooley-Tukey FFT algorithm iteratively. This way you can avoid potential recursion depth issues faced with the recursive implementation. Write a function `iterative_fft` that computes the DFT of an array of c... | 0.630475 | Data_Structure_21437 | C | [
"bit_reverse_copy",
"iterative_fft"
] | 2 | [
[
"iterative_fft",
"bit_reverse_copy"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8fcc5a28adcee891f765a07c7df73b2ee7d80d43 | 4625b0a04c8f99302dfe6249645c46909786d002 | |||
v1.0 | complete | Data_Structure | Data_Structure_21683_C | from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
""" Sorts a given list of integers using the Insertion Sort algorithm.
>>> insertion_sort([4, 3, 1, 2])
[1, 2, 3, 4]
>>> insertion_sort([10, -1, 3, 5])
[-1, 3, 5, 10]
"""
if len(arr) <= 1:
return arr
... | from typing import List
def search_insert(sorted_arr: List[int], value: int) -> int:
"""
Determines the position where an element should be inserted in a sorted array.
"""
for i, v in enumerate(sorted_arr):
if value < v:
return i
return len(sorted_arr)
def insertion_sort(arr: L... | from solution import insertion_sort
def test_insertion_sort_with_unsorted_list():
assert insertion_sort([4, 3, 1, 2]) == [1, 2, 3, 4]
assert insertion_sort([10, -1, 3, 5]) == [-1, 3, 5, 10]
def test_insertion_sort_with_sorted_list():
assert insertion_sort([1, 2, 3, 4]) == [1, 2, 3, 4]
assert insertion... | [
{
"docstring": "Determines the position where an element should be inserted in a sorted array.",
"function_declaration": "def search_insert(sorted_arr, value):",
"function_name": "search_insert",
"parameter_list": "(sorted_arr, value)"
},
{
"docstring": "Sorts a given list of integers using ... | [
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 search_insert(arr, x):\n \"\"\"\n Helper function to find the index where x should be inserted\n in the sorted portion of arr.\n \"\"\"\n f... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort Implementation\n\n**Background**:\nYou are given a partially implemented helper function `search_insert` which determines the position where an element should be inserted in a sorted array. Using this helper function to assist, your task is to implement the Insertion Sort... | 0.674153 | Data_Structure_21683 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 978d18b5489a84e3fd54777c621ccc21d12f3437 | 37de0c80d3774fdae608e3ca608c4393d0ec2365 | |||
v1.0 | complete | Data_Structure | Data_Structure_21244_C | def permutation_bogo_sort(arr):
"""
Sort the given list of elements using a variation of Bogo Sort by generating
all possible permutations and checking if they are sorted.
Input:
- arr: A list of integers.
Output:
- Returns the sorted list.
Constraints:
- Do not use built-in sorti... | from itertools import permutations
def is_sorted(arr):
"""
Check if the given list is sorted in ascending order.
"""
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def permutation_bogo_sort(arr):
"""
Sort the given list of elements using a variation of Bogo Sort by generating
al... | from solution import permutation_bogo_sort
def test_permutation_bogo_sort_sorted_list():
assert permutation_bogo_sort([1, 2, 3]) == [1, 2, 3]
def test_permutation_bogo_sort_reversed_list():
assert permutation_bogo_sort([3, 2, 1]) == [1, 2, 3]
def test_permutation_bogo_sort_mixed_list():
assert permutatio... | [
{
"docstring": "Check if the given list is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sort the given list of elements using a variation of Bogo Sort by generating\nall possible permuta... | [
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 itertools import permutations\n\ndef permutation_bogo_sort(arr):\n \"\"\"\n Sort the given list of elements using a variation of Bogo Sort.\n\n ... | trial_gpt4o_1 | {
"original_instruction": "**Context**:\nBogo Sort is an intentionally inefficient algorithm used for academic purposes to demonstrate the pitfalls of relying on randomness for sorting. Despite its impracticality, understanding Bogo Sort provides a clear understanding of why efficient algorithms are necessary. \n\nWr... | 0.589978 | Data_Structure_21244 | C | [
"is_sorted",
"permutation_bogo_sort"
] | 2 | [
[
"permutation_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7c8f4b6a96b6ed56379de9b1ff6608c1c066ccaa | cbc64c5345ca0656cbe9d59493c0ba55d1b49cd4 | |||
v1.0 | complete | Data_Structure | Data_Structure_20896_C | def stoogesort(arr, l, h, k=10):
""" Enhanced Stooge Sort algorithm with early termination check and threshold optimization.
>>> array = [5, 3, 2, 8, 6, 2]
>>> stoogesort(array, 0, len(array) - 1)
>>> array
[2, 2, 3, 5, 6, 8]
"""
pass
def insertion_sort(arr, l, h):
pass
# Example usage... | def insertion_sort(arr, l, h):
for i in range(l + 1, h + 1):
key = arr[i]
j = i - 1
while j >= l and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def stoogesort(arr, l, h, k=10):
# Early termination check
already_sorted = True
for i i... | from solution import stoogesort
def test_stoogesort_sorted_input():
array = [1, 2, 3, 4, 5]
stoogesort(array, 0, len(array) - 1)
assert array == [1, 2, 3, 4, 5]
def test_stoogesort_reverse_sorted_input():
array = [5, 4, 3, 2, 1]
stoogesort(array, 0, len(array) - 1)
assert array == [1, 2, 3, 4,... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, l, h):",
"function_name": "insertion_sort",
"parameter_list": "(arr, l, h)"
},
{
"docstring": null,
"function_declaration": "def stoogesort(arr, l, h, k=10):",
"function_name": "stoogesort",
"parameter_list": "... | [
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 stoogesort(arr, l, h, k=5):\n \"\"\"\n Performs Stooge Sort on the array with enhancements.\n \n Parameters:\n arr (list): The list to be s... | trial_gpt4o_2 | {
"original_instruction": "### Stooge Sort Analysis and Enhancement\n\nYou are given a recursive sorting algorithm known as Stooge Sort. It is known for its inefficiency due to its high time complexity but serves as a good educational example for understanding recursive sorting mechanisms.\n\n**Task**: Augment the St... | 0.610528 | Data_Structure_20896 | C | [
"insertion_sort",
"stoogesort"
] | 2 | [
[
"stoogesort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1d38aca0326ccc10c3382c4ab62be2c899a90468 | 0a66f295a29f23eab0b46c605ac2a72f64a594d2 | |||
v1.0 | complete | Data_Structure | Data_Structure_21030_C | from typing import List
def gnome_sort(arr: List[int]) -> List[int]:
""" Sorts a list of integers using the Gnome Sort algorithm.
>>> gnome_sort([34, 2, 78, 1, 58])
[1, 2, 34, 58, 78]
>>> gnome_sort([5, 3, 1, 4, 2])
[1, 2, 3, 4, 5]
"""
pass
def sorted_index_positions(arr: List[int]) -> Lis... | def gnome_sort(arr):
"""
Sorts a list of integers using the Gnome Sort algorithm.
"""
index = 0
while index < len(arr):
if index == 0 or arr[index] >= arr[index - 1]:
index += 1
else:
arr[index], arr[index - 1] = arr[index - 1], arr[index]
index -=... | from solution import gnome_sort, sorted_index_positions
def test_gnome_sort():
assert gnome_sort([34, 2, 78, 1, 58]) == [1, 2, 34, 58, 78]
assert gnome_sort([5, 3, 1, 4, 2]) == [1, 2, 3, 4, 5]
assert gnome_sort([]) == []
assert gnome_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
assert gnome_sort([3, 3,... | [
{
"docstring": "Sorts a list of integers using the Gnome Sort algorithm.",
"function_declaration": "def gnome_sort(arr):",
"function_name": "gnome_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Returns a list of indices showing the new positions of the elements in the sorted list.",
... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef gnome_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array of integers using the Gnome Sort algorithm.\n \"\"\... | trial_gpt4o_4 | {
"original_instruction": "### Gnome Sort in Practice\n\n#### Background\nGnome Sort is a simple, intuitive sorting algorithm that is not efficient for large datasets but can be useful for educational purposes or when sorting trivially small datasets. The algorithm employs a series of comparisons and swaps to ensure ... | 0.665819 | Data_Structure_21030 | C | [
"gnome_sort",
"sorted_index_positions"
] | 2 | [
[
"sorted_index_positions",
"gnome_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aa25edec390b7e1013cac04e9250dbf34555a4b0 | 3d68d303db010d52747ead1131c06a69336b276d | |||
v1.0 | complete | Data_Structure | Data_Structure_21529_C | class Node:
def __init__(self, x):
self.val = x
self.next = None
def intersection(head1: Node, head2: Node) -> Optional[Node]:
""" Determines the intersection node of two singly linked lists. The intersection is determined by reference, not by value.
>>> common = Node(7)
>>> common... | class Node:
def __init__(self, x):
self.val = x
self.next = None
def get_length(head):
length = 0
while head:
length += 1
head = head.next
return length
def intersection(head1: Node, head2: Node) -> Node:
if not head1 or not head2:
return None
len1 ... | from solution import Node, intersection
def test_intersection():
# Example 1
# List A: 1 -> 3 -> 5
# \
# 7 -> 9 -> 11
# /
# List B: 2 -> 4 -> 6
common = Node(7)
common.next = Node(9)
common.next.next = Node(11)
head1 = Node(1... | [] | [
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": "class Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\ndef intersection(head1: Node, head2: Node) -> Optional[No... | trial_gpt4o_1 | {
"original_instruction": "You are to implement the function `intersection` which determines the intersection node of two singly linked lists. The intersection is determined by reference, not by value. \n\n### Function Signature\n```python\ndef intersection(head1: Node, head2: Node) -> Optional[Node]:\n pass\n```\... | 0.547573 | Data_Structure_21529 | C | [
"get_length",
"intersection"
] | 2 | [
[
"intersection",
"get_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | b1dc497600f9a69b60ff165cfa8f00744025b076 | b218566c49d7fe90d18e42313f9297eb0218e4ba | |||
v1.0 | complete | Data_Structure | Data_Structure_21665_C | import heapq
from math import sqrt
def k_closest(points, k, origin=(0, 0)):
""" Find the k closest points to the origin from a given list of points.
Arguments:
points -- a list of tuples, where each tuple represents a point in 2D space (x, y)
k -- an integer representing the number of closest poin... | import heapq
from math import sqrt
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points in 2D space.
"""
return sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def k_closest(points, k, origin=(0, 0)):
"""
Find the k closest points to... | from solution import k_closest
def test_basic_case():
points = [(1, 5), (2, 3), (-2, 4), (3, -2), (0, 1)]
k = 3
origin = (0, 0)
expected = [(0, 1), (2, 3), (3, -2)]
assert set(k_closest(points, k, origin)) == set(expected)
def test_with_different_origin():
points = [(1, 2), (3, 4), (1, -1)]
... | [
{
"docstring": "Calculate the Euclidean distance between two points in 2D space.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Find the k closest points to the origin from a ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef k_closest(points, k, origin=(0, 0)):\n \"\"\"\n Returns the k closest points to the origin.\n \n Parameters:\n - points: Lis... | trial_gpt4o_1 | {
"original_instruction": "### Question\n\n**Scenario**:\nImagine you are developing features for a mapping application where users can search for the k closest landmarks to their current location. Your task is to implement a function that finds the k closest points (landmarks) to a given origin point.\n\n**Task**:\n... | 0.65378 | Data_Structure_21665 | C | [
"euclidean_distance",
"k_closest"
] | 2 | [
[
"k_closest",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | df76ccac53d63ca69f9909ecf1f735bd98f9f6aa | 14832547a7e316b41ed64239c9e3f6d927d531f3 | |||
v1.0 | complete | Data_Structure | Data_Structure_21251_C | from typing import List, Tuple, Dict
def maximum_flow(n: int, m: int, edges: List[Tuple[int, int, int]], source: int, sink: int) -> Dict[str, int]:
""" Compute the maximum flow from a given source to a given sink using
Ford-Fulkerson, Edmonds-Karp, and Dinic algorithms.
Examples:
>>> maxi... | from typing import List, Tuple, Dict
from collections import deque, defaultdict
def bfs_level_graph(C, source, sink, levels, n):
queue = deque([source])
levels[source] = 0
while queue:
u = queue.popleft()
for v in range(n):
if levels[v] < 0 and C[u][v] > 0: # unused capacity
... | from solution import maximum_flow
def test_case_1():
n = 4
m = 5
edges = [(0, 1, 1000), (0, 2, 1000), (1, 2, 1), (1, 3, 1000), (2, 3, 1000)]
source = 0
sink = 3
result = maximum_flow(n, m, edges, source, sink)
assert result == {
"Ford-Fulkerson": 2000,
"Edmonds-Karp": 2000,
... | [
{
"docstring": null,
"function_declaration": "def bfs_level_graph(C, source, sink, levels, n):",
"function_name": "bfs_level_graph",
"parameter_list": "(C, source, sink, levels, n)"
},
{
"docstring": null,
"function_declaration": "def dfs_flow(C, levels, u, sink, flow):",
"function_n... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple, Dict\nimport collections\n\ndef maximum_flow(n: int, m: int, edges: List[Tuple[int, int, int]], source: int, sink: int) -> Dic... | trial_gpt4o_1 | {
"original_instruction": "Maximum Flow Network Analysis\n\n#### Task\n\nYou are given a directed graph representing a flow network with `n` vertices and `m` edges. Each edge has a specific capacity representing the maximum possible flow that can pass through that edge. Your task is to implement the Ford-Fulkerson, E... | 0.56035 | Data_Structure_21251 | C | [
"bfs_level_graph",
"dfs_flow",
"dinic_algorithm",
"bfs",
"ford_fulkerson",
"edmonds_karp",
"maximum_flow"
] | 7 | [
[
"dinic_algorithm",
"bfs_level_graph"
],
[
"dinic_algorithm",
"dfs_flow"
],
[
"edmonds_karp",
"ford_fulkerson"
],
[
"ford_fulkerson",
"bfs"
],
[
"maximum_flow",
"dinic_algorithm"
],
[
"maximum_flow",
"edmonds_karp"
],
[
"maximum_flow",
... | 7 | [] | false | [] | false | pytest | true | [] | true | 3933d1854eddd42c9e12aa7b56d10cc38dc4dc7a | 1b0c6a983300b888ba0305ea664097870c5d309c | |||
v1.0 | complete | Data_Structure | Data_Structure_21379_C | import math
from functools import reduce
def gcd(a, b):
"""
Computes the greatest common divisor of a and b.
"""
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""
Computes the least common multiple of a and b.
"""
return abs(a*b) // gcd(a, b)
def generalized_gcd(arr):
... | import math
from functools import reduce
def gcd(a, b):
"""
Computes the greatest common divisor of a and b.
"""
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""
Computes the least common multiple of a and b.
"""
return abs(a*b) // gcd(a, b)
def generalized_gcd(arr):
... | import pytest
from solution import generalized_gcd, generalized_lcm
def test_generalized_gcd_positive_numbers():
assert generalized_gcd([2, 4, 6, 8]) == 2
assert generalized_gcd([10, 20, 40]) == 10
def test_generalized_gcd_mixed_numbers():
assert generalized_gcd([5, 7, 11]) == 1
assert generalized_gcd... | [
{
"docstring": "Computes the greatest common divisor of a and b.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the least common multiple of a and b.",
"function_declaration": "def lcm(a, b):",
"function_name... | [
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\nfrom functools import reduce\n\ndef generalized_gcd(arr):\n \"\"\"\n Computes the GCD of a list of integers.\n\n Args:\n arr: List[in... | trial_gpt4o_2 | {
"original_instruction": "Develop a function `generalized_gcd(arr)` which computes the greatest common divisor (GCD) of a list of integers. Then, use this function to develop another function `generalized_lcm(arr)` to compute the least common multiple (LCM) for the same list of integers.\n\n### Requirements\n1. Impl... | 0.693812 | Data_Structure_21379 | C | [
"gcd",
"lcm",
"generalized_gcd",
"generalized_lcm"
] | 4 | [
[
"generalized_gcd",
"gcd"
],
[
"generalized_lcm",
"lcm"
],
[
"lcm",
"gcd"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 6bd637c67c1fba46e1ddc840f94e00346a302654 | 5c3668e97ee76fbd3b307cfd10edfae6ff1e026f | |||
v1.0 | complete | Data_Structure | Data_Structure_21178_C | def optimized_quick_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers using the optimized Quick Sort algorithm.
Parameters:
- arr: List[int] : List of integers to be sorted
Returns:
- List[int] : Sorted list of integers
>>> optimized_quick_sort([3, 6, 8, 10, 1,... | import random
from typing import List
def insertion_sort(arr: List[int], low: int, high: int) -> None:
for i in range(low + 1, high + 1):
key = arr[i]
j = i - 1
while j >= low and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def _quick_sort(arr:... | from solution import optimized_quick_sort
def test_empty_array():
assert optimized_quick_sort([]) == []
def test_single_element():
assert optimized_quick_sort([1]) == [1]
def test_already_sorted():
assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted():
assert opti... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, low, high):",
"function_name": "insertion_sort",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def _quick_sort(arr, low, high):",
"function_name": "_quick_sort",
"paramet... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef insertion_sort(arr, low, high):\n for i in range(low + 1, high + 1):\n key = arr[i]\n j = i - 1... | trial_gpt4o_2 | {
"original_instruction": "## Question\n\n### Problem Statement\n\nYou are required to implement an optimized version of the Quick Sort algorithm. Your function should sort an array of integers efficiently, optimizing for both average and worst-case scenarios. Specifically, you should:\n\n1. Use a randomized pivot to... | 0.622841 | Data_Structure_21178 | C | [
"insertion_sort",
"_quick_sort",
"optimized_quick_sort"
] | 3 | [
[
"_quick_sort",
"insertion_sort"
],
[
"optimized_quick_sort",
"_quick_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3396bafd0b38d31cc9f8783a23488dd6896a9421 | 05e79a0aca52a0cfebe02bd85180e1c38a520e43 | |||
v1.0 | complete | Data_Structure | Data_Structure_20677_C | import random
import time
def insertion_sort(arr):
"""
Sorts an array in ascending order using the insertion sort algorithm.
Parameters:
arr (list): The list of elements to be sorted.
Returns:
list: The sorted list.
"""
# Your code here
def is_sorted(arr):
"""
Helper ... | import random
def insertion_sort(arr):
"""
Sorts an array in ascending order using the insertion sort algorithm.
Parameters:
arr (list): The list of elements to be sorted.
Returns:
list: The sorted list.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
... | from solution import insertion_sort, is_sorted, bogo_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, 5]) == [1, 2, 3, 4, 5]
def test_inse... | [
{
"docstring": "Sorts an array in ascending order using the insertion sort algorithm.\n\nParameters:\narr (list): The list of elements to be sorted.\n\nReturns:\nlist: The sorted list.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef insertion_sort(arr):\n \"\"\"\n Sorts an array in ascending order using the insertion sort algorithm.\n \n Parameters:\n a... | trial_gpt4o_0 | {
"original_instruction": "### Sorting Algorithm Analysis and Enhancement\n\nBogo Sort, also whimsically known as \"stupid sort,\" is a notoriously inefficient algorithm due to its reliance on random shuffling. Despite being impractical for real-world applications, it serves as an engaging example of algorithm comple... | 0.612956 | Data_Structure_20677 | C | [
"insertion_sort",
"is_sorted",
"bogo_sort",
"compare_performance"
] | 4 | [
[
"bogo_sort",
"is_sorted"
],
[
"compare_performance",
"bogo_sort"
],
[
"compare_performance",
"insertion_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 145ea3d1f70cb7679b83a3bba5656190fabe1767 | 1baf8e13a164361bbeb5548b290ec0c96649c64a | |||
v1.0 | complete | Data_Structure | Data_Structure_21759_C | import math
from typing import List
def is_prime(n: int) -> bool:
"""
Check if the number n is a prime number.
"""
pass # Provided implementation
def filter_primes(numbers: List[int]) -> List[int]:
"""
Filters and returns only the prime numbers from a list of integers.
>>> filter_primes(... | import math
from typing import List
def is_prime(n: int) -> bool:
"""
Check if the number n is a prime number.
"""
if n <= 1:
return False
if n == 2 or 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 ... | from solution import filter_primes, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(5) == True
assert is_prime(4) == False
assert is_prime(0) == False
assert is_prime(1) == False
assert is_prime(-1) == False
assert is_prime(13) == True... | [
{
"docstring": "Check if the number n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Filters and returns only the prime numbers from a list of integers.",
"function_declaration": "def filter_primes(... | [
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 math import isqrt\nfrom typing import List\n\ndef prime_check(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with enhancing an efficient algorithm for checking prime numbers to evaluate a given list of integers. The goal is to write a function `filter_primes(numbers: List[int]) -> List[int]` that filters and returns only the prime numbers from a list of integers.\n\n### Requirements... | 0.776629 | Data_Structure_21759 | C | [
"is_prime",
"filter_primes"
] | 2 | [
[
"filter_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c1242aeafd7740fc5d377f7bca52dc3472265157 | 84527cee8c596f5551da418d5d1c73d492e093c6 | |||
v1.0 | complete | Data_Structure | Data_Structure_21799_C | from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers using the insertion sort algorithm.
>>> insertion_sort([4, 2, 7, 1, 3])
[1, 2, 3, 4, 7]
>>> insertion_sort([10, -5, 7, 2, 0])
[-5, 0, 2, 7, 10]
>>> insertion_sort([1])
[1]
>>> in... | from typing import List
def search_insert(arr: List[int], val: int, start: int, end: int) -> int:
"""
Helper function to perform binary search to find the insertion position for val
"""
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
start = mid + 1
el... | from solution import insertion_sort
def test_sorted_list():
assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list():
assert insertion_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_unsorted_list_general():
assert insertion_sort([4, 2, 7, 1, 3]) == [1, 2, 3, 4, 7]
def ... | [
{
"docstring": "Helper function to perform binary search to find the insertion position for val",
"function_declaration": "def search_insert(arr, val, start, end):",
"function_name": "search_insert",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "Function to perform insertion ... | [
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 search_insert(arr, val, start, end):\n \"\"\"\n Binary search method to find the correct insertion position for val in arr between start and end.\n ... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with implementing a function `insertion_sort` that sorts an array of integers using the insertion sort algorithm. Given the core logic for binary search (`search_insert`) to find the correct insertion positions, your goal is to integrate this into a full sorting method.\n\n##... | 0.68611 | Data_Structure_21799 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9390abb32605d79f1964add03d8a758a089cbace | 1f20d8db57bcc131393258159d7cee457dded72a | |||
v1.0 | complete | Data_Structure | Data_Structure_21735_C | def infix_to_postfix(expression: str) -> str:
""" Convert an infix expression to postfix notation.
>>> infix_to_postfix("3+(2*5)")
'325*+'
>>> infix_to_postfix("((3+1)*4)")
'31+4*'
>>> infix_to_postfix("5+2*6-3/7")
'526*+37/-'
>>> infix_to_postfix("3+(4+5*6)/7")
'3456*+7/+'
... | def get_precedence(op):
"""
Returns the precedence of the given operator.
Higher number means higher precedence.
"""
if op in {'+', '-'}:
return 1
if op in {'*', '/'}:
return 2
return 0
def infix_to_postfix(expression: str) -> str:
"""
Converts the given infix expres... | from solution import infix_to_postfix
def test_simple_expression():
assert infix_to_postfix("3+(2*5)") == "325*+"
def test_expression_with_multiple_parentheses():
assert infix_to_postfix("((3+1)*4)") == "31+4*"
def test_expression_with_all_operators():
assert infix_to_postfix("5+2*6-3/7") == "526*+37/-"
... | [
{
"docstring": "Returns the precedence of the given operator.\nHigher number means higher precedence.",
"function_declaration": "def get_precedence(op):",
"function_name": "get_precedence",
"parameter_list": "(op)"
},
{
"docstring": "Converts the given infix expression to postfix notation.",... | [
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 infix_to_postfix(expression: str) -> str:\n precedence = {'+': 1, '-': 1, '*': 2, '/': 2}\n stack = []\n postfix = []\n \n for char in expr... | trial_gpt4o_1 | {
"original_instruction": "### Stack-Based Infix to Postfix Conversion\n\n#### Scenario\nIn a computer science class, you are asked to evaluate mathematical expressions written in infix notation. However, computers prefer postfix notation because it’s easier to parse and evaluate mechanically. To assist in converting... | 0.47358 | Data_Structure_21735 | C | [
"get_precedence",
"infix_to_postfix"
] | 2 | [
[
"infix_to_postfix",
"get_precedence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b435e54851656827c37ed98f13200f79053d1358 | b6c77a12bebb4fcce4c4a2482e10673acd34f1d6 | |||
v1.0 | complete | Data_Structure | Data_Structure_21657_C | def matrix_mult(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
""" Multiply two matrices A and B.
>>> matrix_mult([[2, 0], [0, 2]], [[1, 0], [0, 1]]) [[2, 0], [0, 2]]
>>> matrix_mult([[1, 1], [1, 0]], [[1, 1], [1, 0]]) [[2, 1], [1, 1]]
"""
pass
def matrix_power(mat: List[List[int]], po... | def matrix_mult(A, B):
n = len(A)
C = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
return C
def matrix_power(mat, power):
n = len(mat)
result = [[1 if i == j else 0 for j in range(n)] for i ... | from solution import matrix_power, state_transition
def test_matrix_power_identity():
mat = [[2, 0], [0, 2]]
power = 0
expected = [[1, 0], [0, 1]]
assert matrix_power(mat, power) == expected
def test_matrix_power_example():
mat = [[1, 1], [1, 0]]
power = 2
expected = [[2, 1], [1, 1]]
a... | [
{
"docstring": null,
"function_declaration": "def matrix_mult(A, B):",
"function_name": "matrix_mult",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def matrix_power(mat, power):",
"function_name": "matrix_power",
"parameter_list": "(mat, power)"
}... | [
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_mult(A, B):\n n = len(A)\n C = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n for k in range(n)... | trial_gpt4o_0 | {
"original_instruction": "### Matrix Operations and Optimization in Dynamic Systems\n\nThe following tasks involve matrix operations fundamental to many scientific and engineering applications. You will implement two main functionalities to work with square matrices: power calculation and matrix operations for dynam... | 0.431695 | Data_Structure_21657 | C | [
"matrix_mult",
"matrix_power",
"state_transition"
] | 3 | [
[
"matrix_power",
"matrix_mult"
],
[
"state_transition",
"matrix_power"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f805daba068b56c9423f2644e5d290bcf6c65b60 | 6deee1bb8af1986d4f0da5ccc2975b37503c7567 | |||
v1.0 | complete | Data_Structure | Data_Structure_21788_C | from typing import List
def multiply_matrices(matA: List[List[int]], matB: List[List[int]]) -> List[List[int]]:
""" Multiplies two square matrices of size n x n.
>>> multiply_matrices([[1, 2], [3, 4]], [[5, 6], [7, 8]])
[[19, 22], [43, 50]]
"""
def matrix_pow(mat: List[List[int]], power: int) -> List[... | from typing import List
def multiply_matrices(matA: List[List[int]], matB: List[List[int]]) -> List[List[int]]:
"""
Multiplies two square matrices of size n x n.
"""
size = len(matA)
result = [[0 for _ in range(size)] for _ in range(size)]
for i in range(size):
for j in range(size)... | from solution import multiply_matrices, matrix_pow
def test_multiply_matrices():
matA = [[1, 2], [3, 4]]
matB = [[5, 6], [7, 8]]
expected = [[19, 22], [43, 50]]
assert multiply_matrices(matA, matB) == expected
def test_matrix_pow_exponent_0():
mat = [[1, 2], [3, 4]]
power = 0
expected = [[... | [
{
"docstring": "Multiplies two square matrices of size n x n.",
"function_declaration": "def multiply_matrices(matA, matB):",
"function_name": "multiply_matrices",
"parameter_list": "(matA, matB)"
},
{
"docstring": "Raises a square matrix to a given power using exponentiation by squaring.",
... | [
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 multiply_matrices(matA: List[List[int]], matB: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Multiplies two square matr... | trial_gpt4o_1 | {
"original_instruction": "You are given two problems to solve involving matrix operations. You need to implement functions to perform matrix multiplication and matrix exponentiation. These operations are fundamental in various computational applications, including graphics, dynamic programming, and scientific comput... | 0.551541 | Data_Structure_21788 | C | [
"multiply_matrices",
"matrix_pow"
] | 2 | [
[
"matrix_pow",
"multiply_matrices"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 06673fe7defeccd298be58a7d76747121edcba6c | 18d1b01b3af73ee442a6256b579b76f8292e6a6b | |||
v1.0 | complete | Data_Structure | Data_Structure_21796_C | def max_heap_sort(arr, debug=False):
"""
Heap Sort using a max heap to sort an array in ascending order.
Args:
arr (List[int]): The array to be sorted.
debug (bool): If True, print the array at each significant step.
Returns:
List[int]: The sorted array in ascending order.
"""
... | def max_heapify(arr, n, i, debug):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[largest] < arr[left]:
largest = left
if right < n and arr[largest] < arr[right]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr... | from solution import max_heap_sort, min_heap_sort
def test_max_heap_sort():
assert max_heap_sort([3, 1, 4, 1, 5, 9, 2], debug=False) == [1, 1, 2, 3, 4, 5, 9]
assert max_heap_sort([-5, 3, -1, 0, 2], debug=False) == [-5, -1, 0, 2, 3]
assert max_heap_sort([1, 1, 1, 1, 1], debug=False) == [1, 1, 1, 1, 1]
a... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, debug):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, debug)"
},
{
"docstring": null,
"function_declaration": "def max_heap_sort(arr, debug=False):",
"function_name": "max_heap_sort",
"par... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_heap_sort(arr, debug=False):\n def heapify(arr, n, i):\n largest = i \n left = 2 * i + 1 \n right = 2 * i + 2 \n \n ... | trial_gpt4o_1 | {
"original_instruction": "### Scenario\n\nYou have been hired by a company that needs to efficiently sort large datasets constantly. They use both min heaps and max heaps in different parts of their system depending on the type of data they are dealing with.\n\nYour task is to complete the implementation of the heap... | 0.637977 | Data_Structure_21796 | C | [
"max_heapify",
"max_heap_sort",
"min_heapify",
"min_heap_sort"
] | 4 | [
[
"max_heap_sort",
"max_heapify"
],
[
"min_heap_sort",
"min_heapify"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e9d1dc6ece7ff6e20466a1656e9f82c7c8278926 | aba161b51e0a9f719877bd6df64cdaab0d0ea79f | |||
v1.0 | complete | Data_Structure | Data_Structure_21932_C | def generate_all_palindromic_partitions(s: str) -> List[List[str]]:
""" Generates all possible subdivisions of the string s where each subdivision consists of palindromic substrings.
>>> generate_all_palindromic_partitions("aab")
[["a", "a", "b"], ["aa", "b"]]
>>> generate_all_palindromic_partitions("ra... | def is_palindrome(s):
"""
Check if the given string s is a palindrome.
"""
return s == s[::-1]
def generate_all_palindromic_partitions(s):
"""
Generates all possible subdivisions of the string s where each subdivision consists of palindromic substrings.
"""
def backtrack(start, path):
... | from solution import generate_all_palindromic_partitions
def test_single_character():
assert generate_all_palindromic_partitions("a") == [["a"]]
def test_two_same_characters():
assert generate_all_palindromic_partitions("aa") == [["a", "a"], ["aa"]]
def test_non_palindromic_characters():
assert generate_... | [
{
"docstring": "Check if the given string s is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Generates all possible subdivisions of the string s where each subdivision consists of palindromic subs... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(string):\n \"\"\"\n Helper function to check if a given string is a palindrome.\n \"\"\"\n return string == string[::-1]\n\ndef ... | trial_gpt4o_7 | {
"original_instruction": "**Context**: Imagine you are assisting in the development of a software tool aimed at providing insights into the structural properties of strings for various applications like bioinformatics and text analysis. One task is to generate all possible subdivisions of a given string where each s... | 0.714844 | Data_Structure_21932 | C | [
"is_palindrome",
"generate_all_palindromic_partitions"
] | 2 | [
[
"generate_all_palindromic_partitions",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 885b4187404b9fe4dce600f0fa56f87ea7023014 | 5de651f893545c12fdbe6435f7e8be14ff293300 | |||
v1.0 | complete | Data_Structure | Data_Structure_21861_C | from typing import List
def search_insert(sorted_portion: List[int], value: int) -> int:
"""
Helper method to perform a binary search and find the correct index
to insert the given value into the sorted portion of the list.
"""
pass
def insertion_sort(arr: List[int]) -> List[int]:
"""
Perf... | from typing import List
def search_insert(sorted_portion: List[int], value: int) -> int:
"""
Helper method to perform a binary search and find the correct index
to insert the given value into the sorted portion of the list.
"""
low, high = 0, len(sorted_portion)
while low < high:
mid = ... | from solution import insertion_sort
def test_insertion_sort_empty():
assert insertion_sort([]) == []
def test_insertion_sort_single_element():
assert insertion_sort([5]) == [5]
def test_insertion_sort_two_elements():
assert insertion_sort([3, 1]) == [1, 3]
assert insertion_sort([1, 3]) == [1, 3]
def... | [
{
"docstring": "Helper method to perform a binary search and find the correct index\nto insert the given value into the sorted portion of the list.",
"function_declaration": "def search_insert(sorted_portion, value):",
"function_name": "search_insert",
"parameter_list": "(sorted_portion, value)"
}... | [
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 search_insert(arr, target):\n \"\"\"\n Helper function to determine the position to insert a target in a sorted array.\n It performs a binary sea... | trial_gpt4o_2 | {
"original_instruction": "Given the helper method `search_insert` which performs a binary search to find the insertion position in a sorted array, implement the **insertion sort** algorithm using this method. Your task is to write a function `insertion_sort` that sorts an array of integers using the insertion sort t... | 0.65043 | Data_Structure_21861 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b9605e0a2591442bce9a9aa1c0e9932c456a08d1 | b2042d50e8b985b36b9f56f27b33659cf0b850e5 | |||
v1.0 | complete | Data_Structure | Data_Structure_21228_C | import typing
from typing import List
def radix_sort(arr: List[int], simulation: bool=False) -> List[int]:
""" Sort a list of transaction IDs represented as integers using Radix Sort.
Args:
arr: List of transaction IDs (integers) to be sorted.
simulation (default is False): A boolean flag ... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool=False) -> None:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n ... | from solution import radix_sort
def test_empty_list():
assert radix_sort([]) == []
def test_single_element():
assert radix_sort([1]) == [1]
def test_sorted_list():
assert radix_sort([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def test_reverse_sorted_list():
assert radix_sort(... | [
{
"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 radix_sort(arr, simulation=False):",
"function_name":... | [
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 counting_sort(arr: List[int], exp: int, simulation: bool) -> None:\n n = len(arr)\n output = [0] * n\n count = [0] * 1... | trial_gpt4o_2 | {
"original_instruction": "### Radix Sort Application to Transaction IDs\n\nConsider a scenario where you are working with a large dataset of transaction IDs represented as integers. These transaction IDs need to be sorted in ascending order for efficient lookup and subsequent processing. Implement the `radix_sort` f... | 0.575576 | Data_Structure_21228 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0657a036f061ae697e294094d54102ef8ba1e0c3 | 4c063dff868135c6ab9b95e149b9303a3b9a7080 | |||
v1.0 | complete | Data_Structure | Data_Structure_22064_C | def rsa_secure_communication(k: int, message: int) -> (int, int):
"""
Secure RSA communication function that generates keys, encrypts a message, and then decrypts it.
Parameters:
k (int): Bit length for the key generation
message (int): The message to encrypt and decrypt (must be positive and less ... | import random
from sympy import isprime, primerange, mod_inverse
def generate_large_prime(bits):
"""
Generate a prime number of given bit length.
"""
lower_bound = 2 ** (bits - 1)
upper_bound = 2 ** bits - 1
while True:
candidate = random.randint(lower_bound, upper_bound)
i... | from solution import rsa_secure_communication
def test_rsa_secure_communication_16bit():
k = 16
message = 123
encrypted_message, decrypted_message = rsa_secure_communication(k, message)
assert decrypted_message == message
def test_rsa_secure_communication_32bit():
k = 32
message = 45678
en... | [
{
"docstring": "Generate a prime number of given bit length.",
"function_declaration": "def generate_large_prime(bits):",
"function_name": "generate_large_prime",
"parameter_list": "(bits)"
},
{
"docstring": "Generate RSA public and private keys of bit length k.",
"function_declaration":... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime(bit_length):\n while True:\n p = random.getrandbits(bit_length)\n ... | trial_gpt4o_4 | {
"original_instruction": "### RSA Encryption Algorithm: Secure Communication\n\nYou are working on implementing a secure communication system using cryptography. In this challenge, you need to generate RSA keys and use them for encryption and decryption of messages.\n\n#### Task\nComplete the function `rsa_secure_co... | 0.618564 | Data_Structure_22064 | C | [
"generate_large_prime",
"rsa_key_generation",
"rsa_encrypt",
"rsa_decrypt",
"rsa_secure_communication"
] | 5 | [
[
"rsa_key_generation",
"generate_large_prime"
],
[
"rsa_secure_communication",
"rsa_decrypt"
],
[
"rsa_secure_communication",
"rsa_encrypt"
],
[
"rsa_secure_communication",
"rsa_key_generation"
]
] | 4 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | b598ed5b4e4b1e0132a1ef7c10b4c42a4d124508 | d48d88923a305913dd1bc04b126404c16365dae8 | |||
v1.0 | complete | Data_Structure | Data_Structure_21941_C | from typing import List
def optimized_radix_sort(arr: List[int]) -> List[int]:
""" Implement and optimize Radix Sort to sort a list of non-negative integers.
Aim to optimize space complexity where possible.
>>> optimized_radix_sort([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66, 75, 90, 170, 802]
... | from typing import List
def optimized_radix_sort(arr: List[int]) -> List[int]:
if len(arr) == 0:
return arr
max_num = max(arr)
place = 1
while max_num // place > 0:
counting_sort(arr, place)
place *= 10
return arr
def counting_sort(arr: List[int], place: int):
... | from solution import optimized_radix_sort
def test_radix_sort_example_case():
arr = [170, 45, 75, 90, 802, 24, 2, 66]
expected = [2, 24, 45, 66, 75, 90, 170, 802]
assert optimized_radix_sort(arr) == expected
def test_radix_sort_empty_list():
arr = []
expected = []
assert optimized_radix_sort(a... | [
{
"docstring": null,
"function_declaration": "def optimized_radix_sort(arr):",
"function_name": "optimized_radix_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def counting_sort(arr, place):",
"function_name": "counting_sort",
"parameter_list": ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int) -> None:\n n = len(arr)\n output = [0] * n # Output array that will have sorted ... | trial_gpt4o_2 | {
"original_instruction": "**Question: Implement and Optimize Radix Sort**\n\n### Problem Statement\nGiven a list of non-negative integers, implement the Radix Sort algorithm to sort the list. Your implementation should follow the outlined principles and aim to optimize space complexity where possible.\n\n### Functio... | 0.638209 | Data_Structure_21941 | C | [
"optimized_radix_sort",
"counting_sort"
] | 2 | [
[
"optimized_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 223c38a36bc4ae389f1d1d7554c6329537872915 | c1414ecb527be33d1500c5156bb84aaf35c058db | |||
v1.0 | complete | Data_Structure | Data_Structure_21607_C | def find_path(graph: Dict[Any, List[Any]], start: Any, end: Any) -> Optional[List[Any]]:
""" Returns a list representing one possible path from the start node to the end node.
If no path exists, return None.
>>> find_path({'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']}... | def find_path(graph, start, end, path=None):
"""
Returns one path from start to end or None if no path exists.
"""
if path is None:
path = []
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if... | from solution import find_path, find_all_paths, find_shortest_path
def test_find_path():
graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']}
assert find_path(graph, 'A', 'D') in [['A', 'B', 'D'], ['A', 'C', 'D'], ['A', 'B', 'C', 'D']]
def test_find_path_no_path():
gr... | [
{
"docstring": "Returns one path from start to end or None if no path exists.",
"function_declaration": "def find_path(graph, start, end, path=None):",
"function_name": "find_path",
"parameter_list": "(graph, start, end, path=None)"
},
{
"docstring": "Returns all paths from start to end as a... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_path(graph, start, end, path=[]):\n \"\"\"\n Find one path from start node to end node\n \"\"\"\n path = path + [start]\n if start == ... | trial_gpt4o_2 | {
"original_instruction": "### Graph Path-Finding Challenge\n\n#### Context\nYou are tasked with implementing graph traversal functions. Your goal is to write efficient code that finds paths between two nodes in a given directed graph. Your solution should incorporate advanced understanding of algorithm optimization ... | 0.559913 | Data_Structure_21607 | C | [
"find_path",
"find_all_paths",
"find_shortest_path"
] | 3 | [
[
"find_shortest_path",
"find_all_paths"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d99bfa18b741e0e7e84f977fe37754c341089303 | 49e275f2c92dbb35a94d06054a4681ea74f1e105 | |||
v1.0 | complete | Data_Structure | Data_Structure_21395_C | def is_primitive_root(a: int, n: int) -> bool:
"""
Check if a given integer 'a' is a primitive root of 'n'.
Parameters:
a (int): The integer to check.
n (int): The modulo integer.
Returns:
bool: True if 'a' is a primitive root of 'n', else False.
>>> is_primitive_root(2, 5)
... | from math import gcd
def euler_totient(n):
"""Calculate Euler's Totient function ϕ(n)"""
result = n
p = 2
while (p * p <= n):
if (n % p == 0):
while (n % p == 0):
n //= p
result -= result // p
p += 1
if (n > 1):
result -= result // n
... | from solution import is_primitive_root, euler_totient, find_order
def test_is_primitive_root_example_1():
assert is_primitive_root(2, 5) == True
def test_is_primitive_root_example_2():
assert is_primitive_root(4, 6) == False
def test_is_primitive_root_small_primes():
assert is_primitive_root(3, 7) == Tru... | [
{
"docstring": "Calculate Euler's Totient function ϕ(n)",
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": "Find the order of a modulo n",
"function_declaration": "def find_order(a, n):",
"function_name": "fi... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef euler_totient(n):\n result = n\n p = 2\n while p * p <= n:\n if n %... | trial_gpt4o_1 | {
"original_instruction": "### Scenario\nYou are building a cryptographic system that relies heavily on modular arithmetic and primitive roots. One of the critical operations is identifying these roots for given integers, which is necessary for secure key generation.\n\n### Task\nImplement a function `is_primitive_ro... | 0.593186 | Data_Structure_21395 | C | [
"euler_totient",
"find_order",
"is_primitive_root"
] | 3 | [
[
"is_primitive_root",
"euler_totient"
],
[
"is_primitive_root",
"find_order"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c91a2bd0427de47e54241dfbdb9c6b6ea1a3ac0c | 4a3776f237402c9d71c92d48ec6e00545a48a206 | |||
v1.0 | complete | Data_Structure | Data_Structure_22170_C | def sum_digit_powers(low: int, high: int) -> list:
"""
Given a range defined by two integers `low` and `high`, return a list of integers
within this range (inclusive) which can be expressed as the sum of their digits
raised to their respective positions.
>>> sum_digit_powers(1, 10)
[1, 2, ... | def digit_power_sum(n):
"""
Function to calculate the sum of digits raised to their respective positions.
"""
return sum(int(digit)**(index + 1) for index, digit in enumerate(str(n)))
def sum_digit_powers(low: int, high: int) -> list:
"""
Function to find all numbers between low and high (inclu... | from solution import sum_digit_powers
def test_sum_digit_powers_single_digit_numbers():
assert sum_digit_powers(1, 9) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_sum_digit_powers_small_range():
assert sum_digit_powers(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
def test_sum_digit_powers_large_range():
assert ... | [
{
"docstring": "Function to calculate the sum of digits raised to their respective positions.",
"function_declaration": "def digit_power_sum(n):",
"function_name": "digit_power_sum",
"parameter_list": "(n)"
},
{
"docstring": "Function to find all numbers between low and high (inclusive)\ntha... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sum_digit_powers(low: int, high: int) -> list:\n \"\"\"\n This function returns a list of integers within the given range [low, high]\n that sati... | trial_gpt4o_9 | {
"original_instruction": "#### Context:\nIn mathematics, certain numbers display unique properties based on operations performed on their individual digits. One such property involves digit powers. For example, the number 89 satisfies the condition:\n\\[ 8^1 + 9^2 = 89 \\]\nSimilarly, 135 satisfies:\n\\[ 1^1 + 3^2 +... | 0.677889 | Data_Structure_22170 | C | [
"digit_power_sum",
"sum_digit_powers"
] | 2 | [
[
"sum_digit_powers",
"digit_power_sum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 26cfe56ac12045a83e24fa4557016bb4c7c2a741 | abe5a70ef4fd12ff74ec2edfc4dd6d50b45d6ec5 | |||
v1.0 | complete | Data_Structure | Data_Structure_21821_C | def max_heap_sort(arr: list, simulation: bool = False) -> list:
""" Perform a max heap sort on the given list of integers.
Args:
arr (list): A list of integers to sort.
simulation (bool): If True, prints the array at each iteration of the heapification process.
Returns:
list: Sorted... | def max_heapify(arr, n, i, simulation=False, iter_count=[0]):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr... | from solution import max_heap_sort, min_heap_sort
def test_max_heap_sort():
assert max_heap_sort([4, 6, 3, 2, 8, 1, 5]) == [1, 2, 3, 4, 5, 6, 8]
assert max_heap_sort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
assert max_heap_sort([1]) == [1]
assert max_heap_sort([]) == []
a... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, simulation=False, iter_count=[0]):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, simulation=False, iter_count=[0])"
},
{
"docstring": null,
"function_declaration": "def min_heapify(arr, n, i, simu... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_heapify(arr, n, i, simulation=False, iter_count=[0]):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n and arr[left] >... | trial_gpt4o_0 | {
"original_instruction": "#### Scenario\nYou currently work at a tech company that processes large datasets daily. To improve the efficiency of managing tasks, your company wants to sort various datasets using the Heap Sort algorithm. Your task is to implement both the max heap sort and the min heap sort functions. ... | 0.675274 | Data_Structure_21821 | C | [
"max_heapify",
"min_heapify",
"max_heap_sort",
"min_heap_sort"
] | 4 | [
[
"max_heap_sort",
"max_heapify"
],
[
"min_heap_sort",
"min_heapify"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 110e51a4cbdea7c115517f6f095c4d6bd36c51bc | b343122c8acf332ee3ce44ccea2492ecb469ef8e | |||
v1.0 | complete | Data_Structure | Data_Structure_21420_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def delete_node_in_bst(root, key):
""" Delete a node with a given key from a Binary Search Tree and return the new root of the tree.
>>> tree_to_list(delete_node_in_b... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def delete_node_in_bst(root, key):
if not root:
return root
if key < root.val:
root.left = delete_node_in_bst(root.left, key)
elif key > root.val... | from solution import TreeNode, delete_node_in_bst
def tree_to_list(root):
""" Helper function to convert tree to list for easy comparison """
if not root:
return []
result = []
queue = [root]
while queue:
node = queue.pop(0)
if node:
result.append(node.val)
... | [] | [
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 de... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nYou work as a software engineer for a company that maintains a large database system. The database needs to efficiently remove specific entries while maintaining an ordered structure, which is implemented using a Binary Search Tree (BST). Your task is to implement a function t... | 0.562825 | Data_Structure_21420 | C | [
"delete_node_in_bst",
"find_min"
] | 2 | [
[
"delete_node_in_bst",
"find_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | a4872e386344ed45e77531ed6dbc9a1c704efb6d | 30c0ae689c61dceb4794efd5de7607115c95d636 | |||
v1.0 | complete | Data_Structure | Data_Structure_22250_C | def prime_check(n):
"""Return True if n is a prime number
Else return False.
"""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
j = 5
while j * j <= n:
if n % j == 0 or n % (j + 2) == 0:
retu... | def prime_check(n):
"""Return True if n is a prime number, else return False."""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
j = 5
while j * j <= n:
if n % j == 0 or n % (j + 2) == 0:
return False... | from solution import next_prime
def test_next_prime_after_small_numbers():
assert next_prime(0) == 2
assert next_prime(1) == 2
def test_next_prime_after_prime_numbers():
assert next_prime(2) == 3
assert next_prime(3) == 5
assert next_prime(5) == 7
def test_next_prime_after_composite_numbers():
... | [
{
"docstring": "Return True if n is a prime number, else return False.",
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": "Returns the smallest prime number greater than n.",
"function_declaration": "def next_prime(n... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def prime_check(n):\n \"\"\"Return True if n is a prime number, else return False.\"\"\"\n\n if n <= 1:\n return False\n if n == 2 or n == 3:\... | trial_gpt4o_0 | {
"original_instruction": "#### Scenario\n\nYou work for a software security consulting firm that frequently needs to analyze encryption key strengths. One common task is to check if certain integers are prime, which is fundamental to determining the hardness of factorizing encryption keys.\n\n#### Task\n\nImplement ... | 0.787922 | Data_Structure_22250 | C | [
"prime_check",
"next_prime"
] | 2 | [
[
"next_prime",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 436d9dbb3ec3e7a4327b50d4e50e516954429623 | 56e133d01d2701ddb338e9d0d2e80f7119a601f6 | |||
v1.0 | complete | Data_Structure | Data_Structure_22667_C | def multiply_bitwise_operator(x: int, y: int) -> int:
"""
Multiplies two non-negative integers using bitwise operations.
>>> multiply_bitwise_operator(3, 4) 12
>>> multiply_bitwise_operator(0, 5) 0
>>> multiply_bitwise_operator(2, 10) 20
""" | def multiply_bitwise_operator(x: int, y: int) -> int:
"""
Multiplies two non-negative integers using bitwise operations.
"""
result = 0
while y > 0:
# If the rightmost bit of y is set, add x to the result
if y & 1:
result = add_bitwise(result, x)
# Shift x left by... | import pytest
from solution import multiply_bitwise_operator
def test_multiply_bitwise_operator():
assert multiply_bitwise_operator(3, 4) == 12
assert multiply_bitwise_operator(0, 5) == 0
assert multiply_bitwise_operator(2, 10) == 20
assert multiply_bitwise_operator(1, 1) == 1
assert multiply_bitwi... | [
{
"docstring": "Multiplies two non-negative integers using bitwise operations.",
"function_declaration": "def multiply_bitwise_operator(x, y):",
"function_name": "multiply_bitwise_operator",
"parameter_list": "(x, y)"
},
{
"docstring": "Adds two non-negative integers using bitwise operations... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply_bitwise_operator(x: int, y: int) -> int:\n \"\"\"\n Multiplies two non-negative integers using bitwise operations.\n \"\"\"\n result ... | trial_gpt4o_1 | {
"original_instruction": "### Question: Bitwise Multiplier\n\nImagine working in a low-level systems environment where standard arithmetic operations are restricted or require optimized procedures. Inspired by the concept of bitwise addition, you are tasked with implementing a function to multiply two non-negative i... | 0.661948 | Data_Structure_22667 | C | [
"multiply_bitwise_operator",
"add_bitwise"
] | 2 | [
[
"multiply_bitwise_operator",
"add_bitwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8a33d4160aeaa877ba5f79cc7210bb08fe753f95 | beceeca943c175449058187b6bd0fe3d7660e532 | |||
v1.0 | complete | Data_Structure | Data_Structure_22251_C | from typing import List
def iterative_merge_sort(arr: List[int]) -> List[int]:
"""
Perform an in-place iterative merge sort on the given array.
>>> iterative_merge_sort([]) == []
>>> iterative_merge_sort([1]) == [1]
>>> iterative_merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
>>> iterative... | def iterative_merge_sort(arr):
"""
Perform an in-place iterative merge sort on the given array.
"""
width = 1
n = len(arr)
while width < n:
for i in range(0, n, 2 * width):
left = i
mid = min(i + width, n)
right = min(i + 2 * width, n)
merg... | from solution import iterative_merge_sort
def test_iterative_merge_sort_empty():
assert iterative_merge_sort([]) == []
def test_iterative_merge_sort_single_element():
assert iterative_merge_sort([1]) == [1]
def test_iterative_merge_sort_sorted_array():
assert iterative_merge_sort([1, 2, 3, 4, 5]) == [1, ... | [
{
"docstring": "Perform an in-place iterative merge sort on the given array.",
"function_declaration": "def iterative_merge_sort(arr):",
"function_name": "iterative_merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "In-place merge function that merges two halves of an array.",
"fu... | [
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(arr, l, m, r):\n # Helper function to merge two halves in place.\n n1 = m - l + 1\n n2 = r - m\n \n # Create temporary arrays \n L... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort - Enhanced Implementation\n\n#### Problem Statement:\nYou have been hired as a software developer to improve the performance of an existing in-house sorting library. Currently, it uses a basic recursive implementation of the merge sort algorithm, which works well but consumes... | 0.609079 | Data_Structure_22251 | C | [
"iterative_merge_sort",
"merge"
] | 2 | [
[
"iterative_merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 89971794365a522e6077a2b8fa76a80fcc309640 | d314a9261ee876b5eabda1924189bb7b2e19b16d | |||
v1.0 | complete | Data_Structure | Data_Structure_22336_C | def is_pattern_in_text(text: str, pattern: str) -> bool:
"""
Implement a Python function to check if a given keyword pattern is present in a given text document,
leveraging the Knuth-Morris-Pratt (KMP) algorithm for optimal performance.
Args:
text: str : The main text in which to search the pat... | def compute_lps(pattern):
length = 0
lps = [0] * len(pattern)
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
els... | from solution import is_pattern_in_text
def test_pattern_exists():
assert is_pattern_in_text('hello there hero!', 'hero') == True
def test_pattern_does_not_exist():
assert is_pattern_in_text('a quick brown fox', 'lazy') == False
def test_pattern_exists_with_repeated_substring():
assert is_pattern_in_text... | [
{
"docstring": null,
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": null,
"function_declaration": "def is_pattern_in_text(text, pattern):",
"function_name": "is_pattern_in_text",
"parameter_list... | [
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_pattern_in_text(text: str, pattern: str) -> bool:\n \"\"\"\n This function leverages the Knuth-Morris-Pratt (KMP) algorithm to check if the patte... | trial_gpt4o_2 | {
"original_instruction": "#### Scenario\nYou are developing a sophisticated filtering system for a library's digital archiving tool. Given the massive collection of digitized books, your tool needs an efficient way to search for specific keyword patterns in text documents. \n\n#### Task\nImplement a Python function ... | 0.577694 | Data_Structure_22336 | C | [
"compute_lps",
"is_pattern_in_text"
] | 2 | [
[
"is_pattern_in_text",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5b7bb4b5ecad1185e11e0853d08e0edc7b578d10 | 35e38db8582a52c4bd1a80f6b2f8d6abba40ea5f | |||
v1.0 | complete | Data_Structure | Data_Structure_22218_C | from typing import List
def enhanced_insertion_sort(arr: List[int]) -> List[int]:
""" Implement an enhanced version of the Insertion Sort algorithm that uses binary search to find the position
where an element should be inserted.
Args:
arr (List[int]): A list of integers to be sorted.
Re... | from typing import List
def binary_search(arr: List[int], val: int, start: int, end: int) -> int:
"""
This function performs binary search on subarray arr[start:end] to find the position where val fits.
"""
if start == end:
if arr[start] > val:
return start
else:
... | from solution import enhanced_insertion_sort
def test_enhanced_insertion_sort_example1():
assert enhanced_insertion_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90]
def test_enhanced_insertion_sort_example2():
assert enhanced_insertion_sort([-10, -50, 0, 20, 30, 10, -40]) == [-50, -40, -10, ... | [
{
"docstring": "This function performs binary search on subarray arr[start:end] to find the position where val fits.",
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": null,
... | [
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 binary_search(arr, val, start, end):\n \"\"\"\n Helper function to perform binary search and find the index\n where val should be inserted in the... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement and Enhance Insertion Sort with Binary Search\n\nThe Insertion Sort algorithm provided is a simple and intuitive way to sort small arrays. However, it has a performance bottleneck due to its O(n^2) time complexity. One way to optimize this algorithm is by using binar... | 0.634061 | Data_Structure_22218 | C | [
"binary_search",
"enhanced_insertion_sort"
] | 2 | [
[
"enhanced_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2415e8ea6a1369b28d9404c6a65978f3335e1bf6 | 59c597fdf674e81da1845370d11a0da83e48c3c4 | |||
v1.0 | complete | Data_Structure | Data_Structure_21681_C | from typing import List
def invert_matrix(m: List[List[float]]) -> List[List[float]]:
"""Invert a given n x n matrix represented as a list of lists.
Given an invertible n x n matrix represented as a list of lists, compute
its inverse. The input matrix is guaranteed to be non-empty, the rows will
... | from typing import List
def invert_matrix(m: List[List[float]]) -> List[List[float]]:
# Helper function to compute the determinant of a matrix
def get_determinant(matrix: List[List[float]]) -> float:
size = len(matrix)
if size == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] ... | from solution import invert_matrix
def test_invert_2x2_matrix():
m = [
[4, 3],
[3, 2]
]
expected = [
[-2.0, 3.0],
[3.0, -4.0]
]
assert invert_matrix(m) == expected
def test_invert_3x3_matrix():
m = [
[1, 2, 3],
[0, 1, 4],
[5, 6, 0]
]
... | [
{
"docstring": null,
"function_declaration": "def invert_matrix(m):",
"function_name": "invert_matrix",
"parameter_list": "(m)"
},
{
"docstring": null,
"function_declaration": "def transpose(matrix):",
"function_name": "transpose",
"parameter_list": "(matrix)"
},
{
"docst... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef get_matrix_determinant(m: List[List[float]]) -> float:\n \"\"\"\n Helper function to calculate the determinant of a given... | trial_gpt4o_2 | {
"original_instruction": "Invert a Matrix\n\nGiven an invertible \\(n \\times n\\) matrix represented as a list of lists, implement a function `invert_matrix(m)` to compute the inverse of the matrix.\n\n### Function Signature\n```python\ndef invert_matrix(m: List[List[float]]) -> List[List[float]]:\n pass\n```\n\... | 0.547644 | Data_Structure_21681 | C | [
"invert_matrix",
"transpose"
] | 2 | [
[
"invert_matrix",
"transpose"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c020bcf6324c13b0c72ec8bc1053cba6deb04705 | 126cdbf58af400dfffc55bdbf3640c83c15bee22 | |||
v1.0 | complete | Data_Structure | Data_Structure_21912_C | def generate_key(k, seed=None) -> (int, int, int):
"""Generate RSA key pair. Return (n, e, d).
>>> n, e, d = generate_key(16)
>>> isinstance(n, int)
True
>>> isinstance(e, int)
True
>>> isinstance(d, int)
True
"""
pass
def encrypt(data, e, n) -> int:
"""Encrypt the give... | import random
from sympy import isprime, mod_inverse
def generate_large_prime(bits, rng):
"""Generate a prime number with specified bits using a RNG."""
while True:
number = rng.getrandbits(bits)
if isprime(number):
return number
def generate_key(k, seed=None):
"""Generate RSA ... | from solution import generate_key, encrypt, decrypt
def test_key_generation():
n, e, d = generate_key(512)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert e == 65537 # Checking if public exponent is correctly set
def test_encryption_decryption():
n, e, d =... | [
{
"docstring": "Generate a prime number with specified bits using a RNG.",
"function_declaration": "def generate_large_prime(bits, rng):",
"function_name": "generate_large_prime",
"parameter_list": "(bits, rng)"
},
{
"docstring": "Generate RSA key pair. Return (n, e, d).",
"function_decl... | [
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_large_prime(bits, rng):\n \"\"\"Generate a prime number with specified bits using a R... | trial_gpt4o_0 | {
"original_instruction": "### RSA Encryption Key Generation and Message Encryption/Decryption\n\nYou have been provided with an RSA key generation algorithm and basic encryption/decryption functions. Your task is to improve the reliability and efficiency of the RSA key generation process. Furthermore, you will imple... | 0.726496 | Data_Structure_21912 | C | [
"generate_large_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_large_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 915ad8056b35f541c7ec0b663de4d86585b18802 | 94a21bd7ba9041fea034ef1a25f959c2a257cf66 | |||
v1.0 | complete | Data_Structure | Data_Structure_21964_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers in non-decreasing order using the Merge Sort algorithm.
Parameters:
arr (List[int]): An unsorted list of integers.
Returns:
List[int]: A list of integers sorted in non-decre... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers in non-decreasing order using the Merge Sort algorithm.
Parameters:
arr (List[int]): An unsorted list of integers.
Returns:
List[int]: A list of integers sorted in non-decre... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_list():
assert merg... | [
{
"docstring": "Sorts an array of integers in non-decreasing order using the Merge Sort algorithm.\n\nParameters:\n arr (List[int]): An unsorted list of integers.\n \nReturns:\n List[int]: A list of integers sorted in non-decreasing order.",
"function_declaration": "def merge_sort(arr):",
"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": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half =... | trial_gpt4o_2 | {
"original_instruction": "You are required to implement the `merge_sort` function given below. This function should sort an array of integers in non-decreasing order using the Merge Sort algorithm. \n\nMerge Sort works on the principle of Divide and Conquer. The array is divided into two halves, each of which is rec... | 0.614191 | Data_Structure_21964 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6ad37eea515ec17f7a60ccd38aa7399d06a46bdf | f7a3bb4ca487b2f42590df591333bdf8d1d17f6e | |||
v1.0 | complete | Data_Structure | Data_Structure_22043_C | from typing import List
def optimized_bucket_sort(arr: List[float]) -> List[float]:
""" Implement and Optimize Bucket Sort
This function sorts a list of floating-point numbers uniformly distributed between 0 and 1 using an optimized bucket sort algorithm.
>>> optimized_bucket_sort([0.12, 0.25, 0.9, 0.5, 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 optimized_bucket_sort(arr: List[flo... | from solution import optimized_bucket_sort
def test_optimized_bucket_sort_basic():
assert optimized_bucket_sort([0.12, 0.25, 0.9, 0.5, 0.8]) == [0.12, 0.25, 0.5, 0.8, 0.9]
def test_optimized_bucket_sort_empty():
assert optimized_bucket_sort([]) == []
def test_optimized_bucket_sort_single_element():
asser... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def optimized_bucket_sort(arr):",
"function_name": "optimized_bucket_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 optimized_bucket_sort(arr: List[float]) -> List[float]:\n if not arr:\n return []\n \n # Determine the number o... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement and Optimize Bucket Sort\n\n#### Context\nImagine you are tasked with sorting a large list of floating-point numbers representing sensor readings collected within a specific range. The numbers are uniformly distributed between 0 and 1.\n\n#### Problem Statement\nImpl... | 0.583042 | Data_Structure_22043 | C | [
"insertion_sort",
"optimized_bucket_sort"
] | 2 | [
[
"optimized_bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 691ec788c581fa3662e997d5873905f20ef58230 | 088c2630b8a8b31a8b91a14921d2acfb633ba669 | |||
v1.0 | complete | Data_Structure | Data_Structure_22026_C | def insertion_sort(bucket: List[float]) -> List[float]:
"""
Sort a list of floating-point numbers using insertion sort.
"""
pass
def improved_bucket_sort(arr: List[float]) -> List[float]:
""" Sort a list of floating-point numbers in the range [0, 1) using the bucket sort algorithm.
Args:
... | def insertion_sort(bucket):
for i in range(1, len(bucket)):
key = bucket[i]
j = i - 1
while j >= 0 and key < bucket[j]:
bucket[j + 1] = bucket[j]
j -= 1
bucket[j + 1] = key
return bucket
def improved_bucket_sort(arr):
if not arr:
return []
... | from solution import improved_bucket_sort
def test_improved_bucket_sort_standard_case():
arr = [0.897, 0.565, 0.656, 0.123, 0.665, 0.343]
assert improved_bucket_sort(arr) == [0.123, 0.343, 0.565, 0.656, 0.665, 0.897]
def test_improved_bucket_sort_already_sorted():
arr = [0.1, 0.2, 0.3, 0.4, 0.5]
asser... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(bucket):",
"function_name": "insertion_sort",
"parameter_list": "(bucket)"
},
{
"docstring": null,
"function_declaration": "def improved_bucket_sort(arr):",
"function_name": "improved_bucket_sort",
"parameter_list":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insertion_sort(bucket):\n for i in range(1, len(bucket)):\n key = bucket[i]\n j = i - 1\n while j >= 0 and bucket[j] > key:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nYou have been hired by a software company to write a function that sorts a list of floating-point numbers, taking advantage of the fact that before rounding, these numbers are uniformly distributed between 0.0 and 1.0. To achieve this, you decide to implement the bucket sort a... | 0.593333 | Data_Structure_22026 | C | [
"insertion_sort",
"improved_bucket_sort"
] | 2 | [
[
"improved_bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3847ca90f8e69e2c200385f77d2128e9a406ab93 | 5f463e82e966c5d26cceb96b2a4ad30936d058c5 | |||
v1.0 | complete | Data_Structure | Data_Structure_21557_C | def binary_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.
[1,3,5,6], 5 -> 2
[1,3,5,6], 2 -> 1
[1,3,5,6], 7 -> 4
[1,3,5,6], 0 -> 0
"""
pass
... | def binary_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, high = 0, len(array)
while low < high:
mid = (low + high) // 2
if array[mi... | from solution import binary_search_insert, binary_insertion_sort
# Tests for binary_search_insert
def test_binary_search_insert_found():
assert binary_search_insert([1, 3, 5, 6], 5) == 2
def test_binary_search_insert_not_found():
assert binary_search_insert([1, 3, 5, 6], 2) == 1
assert binary_search_inser... | [
{
"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 binary_search_insert(array, val):",
"function_name": "binary_search_insert",
"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 binary_search_insert(array, val):\n \"\"\"\n Given a sorted array and a target value, return the index if the target is\n found. If not, return t... | trial_gpt4o_2 | {
"original_instruction": "### Question: Insertion Sort with Binary Search Optimization\n\nYou are tasked with implementing an insertion sort algorithm, but with a twist. You will use binary search to find the correct insertion position in the sorted portion of the array. \n\n#### Instructions:\n1. Implement the `bin... | 0.581685 | Data_Structure_21557 | C | [
"binary_search_insert",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"binary_search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 657fab45bc24038660fc7a7ed9ee21ccc44f4d54 | 22d99becd35ce6848d47a14a8ccb3aae0257b4ca | |||
v1.0 | complete | Data_Structure | Data_Structure_21694_C | import math
def nearest_neighbor_classifier(query, training_set):
"""
Classifies the given query vector by nearest neighbor algorithm.
Arguments:
query: A tuple representing the feature vector to classify.
training_set: A dictionary where keys are tuples representing training vectors and values ar... | import math
def euclidean_distance(v1, v2):
"""
Compute the Euclidean distance between two vectors.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def nearest_neighbor_classifier(query, training_set):
"""
Classifies the given query vector by nearest neighbor algorithm.
Ar... | from solution import nearest_neighbor_classifier
def test_nearest_neighbor_classifier_basic():
query_vector = (4.0, 3.5, 2.2)
training_vectors = {
(4.1, 3.4, 2.2): 'apple',
(3.1, 2.9, 3.5): 'banana',
(4.0, 3.5, 2.1): 'cherry'
}
assert nearest_neighbor_classifier(query_vector, tr... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef nearest_neighbor_classifier(query, training_set):\n \"\"\"\n Classifies the given query vector by the nearest neighbor algorithm.\n\n... | trial_gpt4o_2 | {
"original_instruction": "### Nearest Neighbor Algorithm Implementation\n\nYou are tasked with implementing a function that uses the nearest neighbor algorithm to classify data points. Your function will take a query vector and a training set, compute the nearest neighbor, and return the associated label.\n\n#### Fu... | 0.569478 | Data_Structure_21694 | C | [
"euclidean_distance",
"nearest_neighbor_classifier"
] | 2 | [
[
"nearest_neighbor_classifier",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f3549ab14bb819eab9d6c541dbf24ea9b3ead59c | 9c4a389d4226e7db21034ce2b73baa30e5c99c28 | |||
v1.0 | complete | Data_Structure | Data_Structure_21808_C | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
This function utilizes binary search to find the index at which
`val` should be inserted to keep `array` sorted.
"""
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if... | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
This function utilizes binary search to find the index at which
`val` should be inserted to keep `array` sorted.
"""
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if... | 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]) == [1, 2, 3]
def test_insertion_sort_reverse_sorted():
a... | [
{
"docstring": "This function utilizes binary search to find the index at which \n`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 an array ... | [
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 low = 0\n high = len(array) - 1\n while low <= high:\n mid ... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort with Binary Search\n\n**Context**: \nAs a programming challenge, you need to implement an efficient sorting algorithm. You've been provided with a helper function `search_insert` that uses binary search to find the correct position to insert an element in a sorted array.... | 0.640255 | Data_Structure_21808 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 767f38953c63861dcc203d63282024c4ec0c3a3f | 634fd7ac9e00d13a285d4ae0f5d5358d61d1341f | |||
v1.0 | complete | Data_Structure | Data_Structure_22665_C | from typing import List
def partition(arr: List[int], first: int, last: int) -> int:
""" Rearranges the elements such that elements less than the pivot are to its left
and elements greater than the pivot are to its right. Returns the final position of the pivot.
"""
pass # implement the partition log... | from typing import List
def partition(arr: List[int], first: int, last: int) -> int:
pivot = arr[last]
i = first - 1
for j in range(first, last):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[last] = arr[last], arr[i+1]
return i+1
def quic... | from solution import quick_sort, partition
def test_quick_sort_example_1():
assert quick_sort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10]
def test_quick_sort_example_2():
assert quick_sort([1, -1, 0]) == [-1, 0, 1]
def test_quick_sort_empty():
assert quick_sort([]) == []
def test_quick_sort_single... | [
{
"docstring": null,
"function_declaration": "def partition(arr, first, last):",
"function_name": "partition",
"parameter_list": "(arr, first, last)"
},
{
"docstring": null,
"function_declaration": "def quick_sort(arr):",
"function_name": "quick_sort",
"parameter_list": "(arr)"
... | [
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 partition(arr: List[int], first: int, last: int) -> int:\n pivot = arr[last]\n i = first - 1\n for j in range(first, l... | trial_gpt4o_1 | {
"original_instruction": "### Quick Sort Algorithm Implementation\n\nYou are required to implement a recursive Quick Sort function. The function should take an array of integers as input and sort it in ascending order. A secondary function for partitioning the array around a pivot element is also to be implemented.\... | 0.626492 | Data_Structure_22665 | C | [
"partition",
"quick_sort"
] | 2 | [
[
"quick_sort",
"partition"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0659cc884271518920e06bc7f4adbedc22bc48ce | 1f4823f175e9a55f73f1107338054e719e41f45b | |||
v1.0 | complete | Data_Structure | Data_Structure_22447_C | def trailing_zero(x: int) -> int:
count = 0
while x and (x & 1) == 0:
count += 1
x >>= 1
return count
def gcd_bitwise(a: int, b: int) -> int:
"""Compute the Greatest Common Divisor (GCD) of two non-negative integers using bitwise operations efficiently.
>>> gcd_bitwise(12, 15)
... | def trailing_zero(x):
count = 0
while x and (x & 1) == 0:
count += 1
x >>= 1
return count
def gcd_bitwise(a: int, b: int) -> int:
if a == 0: return b
if b == 0: return a
# Finding the number of trailing zero bits in both numbers
shift = min(trailing_zero(a), trailing_zero(b... | from solution import gcd_bitwise
def test_gcd_bitwise_basic():
assert gcd_bitwise(12, 15) == 3
def test_gcd_bitwise_large_numbers():
assert gcd_bitwise(1000000000, 500000000) == 500000000
def test_gcd_bitwise_one_zero():
assert gcd_bitwise(0, 10) == 10
assert gcd_bitwise(10, 0) == 10
def test_gcd_bi... | [
{
"docstring": null,
"function_declaration": "def trailing_zero(x):",
"function_name": "trailing_zero",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def gcd_bitwise(a, b):",
"function_name": "gcd_bitwise",
"parameter_list": "(a, b)"
}
] | [
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 trailing_zero(x):\n count = 0\n while x and not x & 1:\n count += 1\n x >>= 1\n return count\n\ndef gcd_bitwise(a: int, b: int) -> ... | trial_gpt4o_1 | {
"original_instruction": "#### **Title**: Advanced GCD Computation using Bitwise Operations\n\n#### **Objective**:\nWrite a Python function to compute the Greatest Common Divisor (GCD) of two non-negative integers using bitwise operations efficiently. This function should handle large input values robustly.\n\n#### ... | 0.721622 | Data_Structure_22447 | C | [
"trailing_zero",
"gcd_bitwise"
] | 2 | [
[
"gcd_bitwise",
"trailing_zero"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7482fb0bd7304aec0da1b447f79f77fd4329e053 | af4dc09cecdefb782c507458a13b23e3359dfd65 | |||
v1.0 | complete | Data_Structure | Data_Structure_21490_C | [Completion Task in Python]
from typing import List, Dict, Any
def compare_heap_sorts(arr: List[int]) -> Dict[str, Any]:
"""
Implement heap sort using both max heap and min heap, and compare their performances.
Args:
arr: A list of integers to be sorted.
Returns:
A dictionary... | from typing import List, Dict, Any
def max_heapify(arr: List[int], n: int, i: int, count: int) -> int:
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[l] > arr[largest]:
largest = l
if r < n and arr[r] > arr[largest]:
largest = r
if largest != i:
arr[i], arr[... | from solution import compare_heap_sorts
def test_compare_heap_sorts_example():
input_arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
result = compare_heap_sorts(input_arr)
expected_sorted_arr = sorted(input_arr)
assert result['sorted_max_heap'] == expected_sorted_arr
assert result['sorted_min_heap'] =... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, count):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, count)"
},
{
"docstring": null,
"function_declaration": "def heap_sort_max(arr):",
"function_name": "heap_sort_max",
"parameter_list":... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict, Any\n\ndef heapify(arr: List[int], n: int, i: int, max_heap: bool, iterations: List[int]) -> None:\n \"\"\"\n To heapify ... | trial_gpt4o_1 | {
"original_instruction": "### Heap Sort with Variations in Performance Analytics.\n\n**Objective**:\nYou need to assess the students' understanding of heap sort implementations using both max heap and min heap and additionally evaluate their ability to analyze the performance of sorting algorithms.\n\n**Context**:\n... | 0.622525 | Data_Structure_21490 | C | [
"max_heapify",
"heap_sort_max",
"min_heapify",
"heap_sort_min",
"compare_heap_sorts"
] | 5 | [
[
"compare_heap_sorts",
"heap_sort_max"
],
[
"compare_heap_sorts",
"heap_sort_min"
],
[
"heap_sort_max",
"max_heapify"
],
[
"heap_sort_min",
"min_heapify"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | b778ba98c757b4f41820958067cb2c07beb5f492 | 3d66d397409882b1ae0e855dfac0e688ce9b5226 | |||
v1.0 | complete | Data_Structure | Data_Structure_22167_C | import random
from typing import List
def is_prime(n: int, k: int) -> bool:
"""Check if a number is prime using the Rabin-Miller primality test."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
d = n - 1
r = 0
while d % 2 =... | import random
from typing import List
def is_prime(n: int, k: int) -> bool:
"""Check if a number is prime using the Rabin-Miller primality test."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
d = n - 1
r = 0
while d % 2 =... | from solution import generate_primes
def test_generate_primes_small_range():
assert generate_primes(10, 5) == [2, 3, 5, 7]
def test_generate_primes_medium_range():
assert generate_primes(50, 5) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
def test_generate_primes_large_range():
assert gene... | [
{
"docstring": "Check if a number is prime using the Rabin-Miller primality test.",
"function_declaration": "def is_prime(n, k):",
"function_name": "is_prime",
"parameter_list": "(n, k)"
},
{
"docstring": "Generate list of prime numbers up to n using Rabin-Miller primality test.",
"funct... | [
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 typing import List\n\ndef is_prime(n: int, k: int) -> bool:\n \"\"\"Check if a number is prime using the Rabin-Miller primality test.\"... | trial_gpt4o_0 | {
"original_instruction": "In advanced cryptographic systems, it is crucial to quickly determine if large numbers are prime. Using the Rabin-Miller primality test, you can efficiently check for primality with a high degree of certainty.\n\n**Scenario**:\nYou are working for a tech company that needs to generate a lis... | 0.726325 | Data_Structure_22167 | C | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5aacbdf198f8b789ea44e9bd47244c68751360f4 | ff000aef279a5719234a17fa37b783b73e05d8dc | |||
v1.0 | complete | Data_Structure | Data_Structure_22562_C | from typing import List
def invert_matrix(matrix: List[List[float]]) -> List[List[float]]:
""" Inverts a given n x n matrix. Returns a suitable error code matrix if the input is invalid.
>>> invert_matrix([
... [4, 7],
... [2, 6]
... ])
[[0.6, -0.7],
[-0.2, 0.4]]
>>> in... | from typing import List
def get_matrix_minor(matrix, i, j):
return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]
def get_matrix_determinant(matrix):
# Special case for 2x2 matrix
if len(matrix) == 2:
return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]
determinant = 0
... | from solution import invert_matrix
def test_valid_2x2_matrix():
matrix = [
[4, 7],
[2, 6]
]
expected = [
[0.6, -0.7],
[-0.2, 0.4]
]
result = invert_matrix(matrix)
for r in range(len(expected)):
for c in range(len(expected[r])):
assert round(re... | [
{
"docstring": null,
"function_declaration": "def get_matrix_minor(matrix, i, j):",
"function_name": "get_matrix_minor",
"parameter_list": "(matrix, i, j)"
},
{
"docstring": null,
"function_declaration": "def get_matrix_determinant(matrix):",
"function_name": "get_matrix_determinant"... | [
0,
0,
0,
1,
0,
0,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef invert_matrix(matrix: List[List[float]]) -> List[List[float]]:\n def is_square(m):\n return all(len(row) == len(m) fo... | trial_gpt4o_8 | {
"original_instruction": "Matrix Inversion Implementation\n\n**Problem Statement:**\n\nGiven an n x n matrix, write a function `invert_matrix(matrix)` that returns its inverse. If the matrix is not invertible or does not satisfy the required conditions, return a suitable error code within a matrix format as describe... | 0.585752 | Data_Structure_22562 | C | [
"get_matrix_minor",
"get_matrix_determinant",
"get_matrix_inverse",
"invert_matrix"
] | 4 | [
[
"get_matrix_determinant",
"get_matrix_minor"
],
[
"get_matrix_inverse",
"get_matrix_determinant"
],
[
"get_matrix_inverse",
"get_matrix_minor"
],
[
"invert_matrix",
"get_matrix_inverse"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | e3c15d09905f1d1f267d38b3d748078f7045dea1 | f7a41aff0a8fdf481fce5010b7915fc6de9edece | |||
v1.0 | complete | Data_Structure | Data_Structure_22295_C | def improved_sort(arr: list) -> list:
"""
Given an array of integers, sort the array in ascending order using a
more efficient sorting algorithm.
Parameters:
arr (list): List of integers to be sorted
Returns:
list: Sorted list of integers
Example:
>>> improved_sort([3, 2, 5, 1... | def improved_sort(arr):
"""
This function sorts an array of integers in ascending order using
merge sort algorithm which has O(n log n) time complexity.
Parameters:
arr (list): List of integers to be sorted
Returns:
list: Sorted list of integers
"""
if len(arr) <= 1:
... | from solution import improved_sort
def test_improved_sort_sorted_array():
assert improved_sort([1, 2, 3]) == [1, 2, 3]
def test_improved_sort_reverse_sorted_array():
assert improved_sort([3, 2, 1]) == [1, 2, 3]
def test_improved_sort_unsorted_array():
assert improved_sort([3, 2, 5, 1, 4]) == [1, 2, 3... | [
{
"docstring": "This function sorts an array of integers in ascending order using\nmerge sort algorithm which has O(n log n) time complexity.\n\nParameters:\narr (list): List of integers to be sorted\n\nReturns:\nlist: Sorted list of integers",
"function_declaration": "def improved_sort(arr):",
"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": "def improved_sort(arr: list) -> list:\n \"\"\"\n Sorts the array in ascending order using Timsort, which is an optimized\n sorting algorithm derived ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement an Enhanced Sorting Solution\n\nYou are tasked with improving upon the Stooge Sort algorithm to create a more efficient sorting method. Use your understanding from the analysis of Stooge Sort and principles from other efficient algorithms to design and implement a ne... | 0.654226 | Data_Structure_22295 | C | [
"improved_sort",
"merge"
] | 2 | [
[
"improved_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 22e0c101f0c3f7cc922943e757369de083c0aaa1 | b8fe1a8f879cbc615505ffaf438688928102d995 | |||
v1.0 | complete | Data_Structure | Data_Structure_22825_C | from typing import Tuple
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
"""
Extended Euclidean Algorithm to find the coefficients (x, y) such that
a * x + b * y = gcd(a, b).
"""
pass
def find_coprime_solution(a: int, b: int) -> Tuple[int, int, int]:
"""
Find integers x and y suc... | from typing import Tuple
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
"""
Extended Euclidean Algorithm to find the coefficients (x, y) such that
a * x + b * y = gcd(a, b).
"""
if b == 0:
return (1, 0, a)
else:
x1, y1, gcd = extended_gcd(b, a % b)
x = y1
... | from solution import find_coprime_solution
def test_find_coprime_solution_example1():
x, y, gcd = find_coprime_solution(30, 50)
assert 30 * x + 50 * y == gcd
assert gcd == 10
def test_find_coprime_solution_example2():
x, y, gcd = find_coprime_solution(101, 10)
assert 101 * x + 10 * y == gcd
as... | [
{
"docstring": "Extended Euclidean Algorithm to find the coefficients (x, y) such that\na * x + b * y = gcd(a, b).",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Find integers x and y such that a * x + b * y... | [
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 Tuple\n\ndef extended_gcd(a: int, b: int) -> Tuple[int, int, int]:\n \"\"\"\n Extended Euclidean Algorithm to find the coefficients (... | trial_gpt4o_0 | {
"original_instruction": "## Problem Statement\n\nYou have been provided with the implementation of the Extended Euclidean Algorithm. Your task is to use this algorithm to solve a real-world problem.\n\n### Task\n\nGiven two positive integers `a` and `b`, write a function `find_coprime_solution(a: int, b: int) -> Tu... | 0.735284 | Data_Structure_22825 | C | [
"extended_gcd",
"find_coprime_solution"
] | 2 | [
[
"find_coprime_solution",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 207190d0798a579b71dee2f2f7c10afaf576d4f6 | 32f7573c7eb44c087e9d34b086e5e94d6f5a86fb | |||
v1.0 | complete | Data_Structure | Data_Structure_22841_C | from typing import List
import math
def is_prime(n: int) -> bool:
"""
Checks if a number is prime.
Parameters:
- n (int): The number to check.
Returns:
- bool: True if the number is prime, False otherwise.
"""
pass # Your implementation here
def find_prime_numbers(numbers: L... | from typing import List
import math
def is_prime(n: int) -> bool:
"""
Checks if a number is prime.
Parameters:
- n (int): The number to check.
Returns:
- bool: True if the number is prime, False otherwise.
"""
if n <= 1:
return False
if n == 2 or n == 3:
re... | from solution import find_prime_numbers
def test_basic_cases():
assert find_prime_numbers([10, 11, 12, 13, 14, 15]) == [11, 13]
assert find_prime_numbers([1, 2, 3, 4, 5]) == [2, 3, 5]
def test_empty_list():
assert find_prime_numbers([]) == []
def test_one_element_list():
assert find_prime_numbers([1]... | [
{
"docstring": "Checks if a number is prime.\n\nParameters:\n- n (int): The number to check.\n\nReturns:\n- bool: True if the number is prime, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Finds and retu... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Returns True if n is a prime number otherwise False.\n \"\"\"\n if n <= 1:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nYou are designing a system that performs prime number checks as a critical part of its operation, which is commonly used in cryptography and number theory applications. A highly efficient and correctly implemented prime-checking function is necessary to ensure the performance ... | 0.785128 | Data_Structure_22841 | C | [
"is_prime",
"find_prime_numbers"
] | 2 | [
[
"find_prime_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 29d678c721cdc8b0750d26a7ac77914ccf427c45 | 47c67f4b4af53e6cac16d34a0a2b1215685e5948 | |||
v1.0 | complete | Data_Structure | Data_Structure_22496_C | class Node:
def __init__(self, val=None):
self.val = val
self.next = None
def find_intersection(head1, head2):
""" This function returns the first common node in both linked lists if an intersection exists, otherwise it returns None.
>>> a1 = Node(1)
>>> b1 = Node(3)
>>> c1 = Node(5... | class Node:
def __init__(self, val=None):
self.val = val
self.next = None
def get_length(head):
length = 0
current = head
while current:
length += 1
current = current.next
return length
def find_intersection(head1, head2):
# Get lengths of both lists
len1 = ... | from solution import Node, find_intersection
def test_find_intersection_with_intersection():
a1 = Node(1)
b1 = Node(3)
c1 = Node(5)
d = Node(7)
a2 = Node(2)
b2 = Node(4)
c2 = Node(6)
e = Node(9)
f = Node(11)
a1.next = b1
b1.next = c1
c1.next = d
a2.next = b2
b2.... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, val=None):\n self.val = val\n self.next = None\n\ndef get_length_and_tail(node):\n length = 0\n while ... | trial_gpt4o_2 | {
"original_instruction": "### Linked List Intersection Finder\n\n#### Problem Statement\nYou are given two singly linked lists that may or may not intersect at some point. Write a function `find_intersection(head1, head2)` that returns the first common node in both lists. If no intersection exists, return `None`.\n\... | 0.559731 | Data_Structure_22496 | C | [
"get_length",
"find_intersection"
] | 2 | [
[
"find_intersection",
"get_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 92b6bdfd263a25d27ffa000d9feac8add067e3ab | 87163ea5f9a94fb3233382e08441ce3fa91c3159 | |||
v1.0 | complete | Data_Structure | Data_Structure_22534_C | def search_insert(array, val):
""" Helper method to find the correct position to insert a value into a sorted part of the array.
>>> search_insert([1, 2, 4, 5], 3)
2
>>> search_insert([1, 2, 4, 5], 0)
0
>>> search_insert([1, 2, 4, 5], 6)
4
>>> search_insert([1, 2, 4, 5], 4)
2
"""... | def search_insert(array, val):
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def insertion_sort(arr):
for i in range(1, len(arr)):
val = arr[i]... | def test_search_insert():
assert search_insert([1, 2, 4, 5], 3) == 2
assert search_insert([1, 2, 4, 5], 0) == 0
assert search_insert([1, 2, 4, 5], 6) == 4
assert search_insert([1, 2, 4, 5], 4) == 2
def test_insertion_sort():
assert insertion_sort([3, 1, 4, 5, 2]) == [1, 2, 3, 4, 5]
assert inser... | [
{
"docstring": null,
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_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 search_insert(array, val):\n low = 0\n high = len(array) - 1\n while low <= high:\n mid = low + (high - low) // 2\n if val > array[... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort Implementation with Search Insert Helper\n\n#### Objective:\nImplement the insertion sort algorithm using the provided `search_insert` helper method to correctly insert elements into a sorted part of the array.\n\n#### Input:\n- A list of integers `arr` representing the u... | 0.675756 | Data_Structure_22534 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | cc089325e86f32f9a38a55a3626d1770d16e379f | 6b9514ff498834c5fa91383146b5b10756879fed | |||
v1.0 | complete | Data_Structure | Data_Structure_22105_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([5, 3, 1, 2, 4])
[1, 2, 3, 4, 5]
>>> merge_sort([])
[]
>>> merge_sort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
... | 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(le... | from solution import merge_sort
def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merge_sort_sorted_array():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_array():
assert merge_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_merge_sort_r... | [
{
"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 if len(arr) <= 1:\n return arr\n \n def merge(left: List[int], right... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Implementation Challenge\n\n#### Context:\nMerge Sort is a powerful and efficient sorting algorithm suitable for sorting large datasets, especially when the data to be sorted can be large and not fit into memory. You are required to implement the Merge Sort algorithm from scr... | 0.609806 | Data_Structure_22105 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 234776b8f625a3da32e11c7547d987fd48fce4ff | 067a5884705e8f3e20eb3e09630b4a2aaf9cec75 | |||
v1.0 | complete | Data_Structure | Data_Structure_22367_C | class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root: TreeNode, key: int) -> TreeNode:
"""
Insert a key into the BST and return the root of the modified BST.
>>> root = TreeNode(4)
>>> root = insert(root, 2)
>>> ... | class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
"""
Insert a key into the BST. If the tree is empty, return a new node.
Otherwise, recur down the tree and insert the key.
Returned root should point to the new ... | from solution import TreeNode, insert, search, delete
def test_insert():
root = TreeNode(4)
root = insert(root, 2)
root = insert(root, 6)
root = insert(root, 1)
root = insert(root, 3)
root = insert(root, 5)
root = insert(root, 7)
# Test structure
assert root.val == 4
assert... | [] | [
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": "class TreeNode:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n\ndef insert(root, key):\n \"\"... | trial_gpt4o_0 | {
"original_instruction": "### Binary Search Tree Operations\n\nAs a programming exercise, you will implement insertion, searching, and deletion operations for a Binary Search Tree (BST). The purpose of each operation is to maintain the fundamental properties of a BST.\n\n### Task:\n\n1. **Insert a value into the BST... | 0.56448 | Data_Structure_22367 | C | [
"insert",
"search",
"delete",
"minValueNode"
] | 4 | [
[
"delete",
"minValueNode"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 80e4e8562609f658e89aa4f6d65f1ab676c73612 | c1bcd05d88750561b6a44a3d61f1848fcab3e7ab | |||
v1.0 | complete | Data_Structure | Data_Structure_21991_C | def heap_sort(arr, order='asc', simulation=False):
"""
Sort an array of integers using heap sort either in ascending or descending order.
Args:
arr (list): A list of integers to be sorted.
order (str): 'asc' for ascending order (default), 'desc' for descending order.
simulation (bool): If ... | def heapify(arr, n, i, order='asc', simulation=False):
if order == 'asc':
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[i] < arr[left]:
largest = left
if right < n and arr[largest] < arr[right]:
largest = right
if larges... | from solution import heap_sort
def test_heap_sort_ascending():
arr = [4, 10, 3, 5, 1]
assert heap_sort(arr, 'asc', False) == [1, 3, 4, 5, 10]
def test_heap_sort_descending():
arr = [4, 10, 3, 5, 1]
assert heap_sort(arr, 'desc', False) == [10, 5, 4, 3, 1]
def test_heap_sort_empty():
arr = []
a... | [
{
"docstring": null,
"function_declaration": "def heapify(arr, n, i, order='asc', simulation=False):",
"function_name": "heapify",
"parameter_list": "(arr, n, i, order='asc', simulation=False)"
},
{
"docstring": null,
"function_declaration": "def heap_sort(arr, order='asc', simulation=Fa... | [
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 heap_sort(arr, order='asc', simulation=False):\n def heapify(arr, n, i, desc):\n largest = i\n left = 2 * i + 1\n right = 2 * i + ... | trial_gpt4o_2 | {
"original_instruction": "#### Context:\nA research institution needs to process a large amount of sensor data collected in an unsorted format. They seek to sort this data as efficiently as possible to perform further analysis. Implement a function that sorts an array of integers using heap sort. You can choose betw... | 0.633628 | Data_Structure_21991 | C | [
"heapify",
"heap_sort"
] | 2 | [
[
"heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1372f00a3675944b4e1cbf0a4d2de020f210228d | 0d55d25deda2552a52421a7d5394339c607f0747 | |||
v1.0 | complete | Data_Structure | Data_Structure_22776_C | from typing import List
def radix_sort_prices(prices: List[int]) -> List[int]:
""" Sorts a given list of non-negative integers using Radix Sort.
Prices are sorted in ascending order.
>>> radix_sort_prices([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66, 75, 90, 170, 802]
>>> radix_sort_prices([... | from typing import List
def counting_sort(arr: List[int], exp: int) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10 # Since we're dealing with base 10 numbers
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i] +=... | from solution import radix_sort_prices
def test_radix_sort_empty_list():
assert radix_sort_prices([]) == []
def test_radix_sort_single_element_list():
assert radix_sort_prices([1]) == [1]
def test_radix_sort_multiple_elements():
assert radix_sort_prices([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 6... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort_prices(prices):",
"function_name": "radix_sort_prices",
"parameter_list": ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n for ... | trial_gpt4o_2 | {
"original_instruction": "### Context\nYou work for an e-commerce company, and your task is to enhance the sorting mechanism used for listing item prices. Your company deals exclusively with non-negative integer prices. Efficient sorting helps in multiple operations, including searching for price ranges, filtering c... | 0.602769 | Data_Structure_22776 | C | [
"counting_sort",
"radix_sort_prices"
] | 2 | [
[
"radix_sort_prices",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4e6832bc46daa10fa86d973248ce327a4f336e55 | b0517b04b1c5fb85ac821ea72ae4331a71ca00bc | |||
v1.0 | complete | Data_Structure | Data_Structure_23074_C | def k_largest_elements(arr: List[int], k: int) -> List[int]:
""" Find and return the k-largest elements of a given list using Heap Sort.
>>> k_largest_elements([3, 2, 1, 5, 6, 4], 2)
[6, 5]
>>> k_largest_elements([1, 2, 3, 4, 5, 6], 1)
[6]
""" | def heapify(arr, n, i):
"""
Helper function to maintain the max heap property.
"""
largest = i # Initialize largest as root
left = 2 * i + 1 # left child
right = 2 * i + 2 # right child
# If left child is larger than root
if left < n and arr[left] > arr[largest]:
larges... | from solution import k_largest_elements
def test_k_largest_elements_basic():
assert k_largest_elements([3, 2, 1, 5, 6, 4], 2) == [6, 5]
assert k_largest_elements([1, 2, 3, 4, 5, 6], 1) == [6]
def test_k_largest_elements_large_k():
assert k_largest_elements([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) == [6, 5, 5, 4]
... | [
{
"docstring": "Helper function to maintain the max heap property.",
"function_declaration": "def heapify(arr, n, i):",
"function_name": "heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Main function to perform heap sort.",
"function_declaration": "def heap_sort(arr):",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef find_k_largest_elements(arr, k):\n \"\"\"\n Returns the k-largest elements in arr in descending order using a max heap.\n \n P... | trial_gpt4o_2 | {
"original_instruction": "**Task**: Implement a k-largest element finder using the max heap implementation of Heap Sort.\n\n**Objective**: Use Heap Sort with a max heap to find and return the k-largest elements of a given list.\n\n**Input/Output Formats**:\n* **Input**: \n * An array of integers `arr`.\n * An inte... | 0.77933 | Data_Structure_23074 | C | [
"heapify",
"heap_sort",
"k_largest_elements"
] | 3 | [
[
"heap_sort",
"heapify"
],
[
"k_largest_elements",
"heap_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8fb149b03ecd24ad3ec0e6ee8b9dbe105c9f8efa | 478abc62ac75871a3f04943eb016c24289eb9e0c | |||
v1.0 | complete | Data_Structure | Data_Structure_22799_C | def optimized_sort(arr):
""" Sorts a list of integers in ascending order using a more efficient sorting algorithm.
>>> optimized_sort([64, 34, 25, 12, 22, 11, 90])
[11, 12, 22, 25, 34, 64, 90]
>>> optimized_sort([3, -1, 2, -4, 0])
[-4, -1, 0, 2, 3]
>>> optimized_sort([])
[]
>>> optimized... | def merge_sort(arr):
"""
Sorts an array of integers in ascending order using Merge Sort.
"""
if len(arr) <= 1:
return arr
# Split the array into two halves
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
# Merge the sorted ha... | from solution import merge_sort
def test_merge_sort_sorted():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted():
assert merge_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_merge_sort_unsorted():
assert merge_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 2... | [
{
"docstring": "Sorts an array of integers in ascending order using Merge Sort.",
"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... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_sort(arr):\n \"\"\"\n Sorts a list of integers using Merge Sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n\n d... | trial_gpt4o_2 | {
"original_instruction": "Implement Optimized Exchange Sort\n\nYou are provided with an inefficient Exchange Sort algorithm. Your task is to implement a more efficient sorting algorithm to sort a given list of integers in ascending order. You can choose any of the following more efficient sorting algorithms:\n\n1. Q... | 0.621656 | Data_Structure_22799 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 086d899ef80d3df92ee48c5418ff4fc47e1f2202 | c34350248d1958b05a5b505a734457ce6d2f522b | |||
v1.0 | complete | Data_Structure | Data_Structure_22979_C | from typing import List
def heap_sort(arr: List[int], ascending: bool = True) -> List[int]:
""" Sort an array of integers in ascending or descending order using heap sort.
Args:
arr (List[int]): The array of integers to be sorted.
ascending (bool): Determines if the array should be sorted in ascen... | from typing import List
def heapify(arr: List[int], n: int, i: int, ascending: bool) -> None:
if ascending:
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if... | def test_heap_sort_ascending():
arr = [3, 1, 4, 1, 5, 9, 2, 6]
assert heap_sort(arr, ascending=True) == [1, 1, 2, 3, 4, 5, 6, 9]
def test_heap_sort_descending():
arr = [3, 1, 4, 1, 5, 9, 2, 6]
assert heap_sort(arr, ascending=False) == [9, 6, 5, 4, 3, 2, 1, 1]
def test_heap_sort_empty():
assert hea... | [
{
"docstring": null,
"function_declaration": "def heapify(arr, n, i, ascending):",
"function_name": "heapify",
"parameter_list": "(arr, n, i, ascending)"
},
{
"docstring": null,
"function_declaration": "def heap_sort(arr, ascending=True):",
"function_name": "heap_sort",
"paramete... | [
0,
0,
0,
1,
1,
1,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef heap_sort(arr: List[int], ascending: bool = True) -> List[int]:\n \"\"\"\n Sorts the array using heap sort algorithm in e... | trial_gpt4o_9 | {
"original_instruction": "**Heap Sort Analysis and Implementation**\n\n### Context:\nYou have been given functions `max_heap_sort` and `min_heap_sort` to sort an array in ascending order using max-heap and min-heap methodologies, respectively. Now, as an experienced programmer, you are required to analyze these impl... | 0.722217 | Data_Structure_22979 | C | [
"heapify",
"heap_sort"
] | 2 | [
[
"heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 70a2870e36e3e1bbc754eef59c1b8815280d201d | 040c8df0427a6cbc6d321e91079e8d618f996b14 | |||
v1.0 | complete | Data_Structure | Data_Structure_22511_C | from typing import List, Dict
def dfs_component(graph: Dict[str, List[str]], start: str) -> List[str]:
""" Perform a Depth First Search (DFS) to identify all nodes in the component connected to `start`.
>>> graph = {
... 'A': ['B'], 'B': ['A', 'C'], 'C': ['B'],
... 'D': ['E'], 'E': ['D']
... }
... | def dfs_component(graph, start):
"""
Perform a Depth First Search (DFS) to identify all nodes in the component connected to `start`.
"""
visited = set()
stack = [start]
result = []
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
... | from solution import dfs_component, bfs_component, find_all_components
def test_dfs_component():
graph = {
'A': ['B'], 'B': ['A', 'C'], 'C': ['B'],
'D': ['E'], 'E': ['D']
}
result = dfs_component(graph, 'A')
assert set(result) == {'A', 'B', 'C'}
def test_bfs_component():
graph = {
... | [
{
"docstring": "Perform a Depth First Search (DFS) to identify all nodes in the component connected to `start`.",
"function_declaration": "def dfs_component(graph, start):",
"function_name": "dfs_component",
"parameter_list": "(graph, start)"
},
{
"docstring": "Perform a Breadth First Search... | [
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 dfs_component(graph, start):\n \"\"\"\n Perform a Depth First Search (DFS) to find all nodes in the component connected to the start node.\n \"\"... | trial_gpt4o_2 | {
"original_instruction": "**Graph Traversal Challenge**\n\nYou are given an undirected graph represented as an adjacency list. Your task is to implement two different graph traversal algorithms: Depth First Search (DFS) and Breadth First Search (BFS). Additionally, you need to identify and return all the disconnecte... | 0.502939 | Data_Structure_22511 | C | [
"dfs_component",
"bfs_component",
"find_all_components"
] | 3 | [
[
"find_all_components",
"bfs_component"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3e48352909f650ecd819a4dddff58150e400e546 | 20d0e9849ce1b94398b1b222daeafeb3689548c2 | |||
v1.0 | complete | Data_Structure | Data_Structure_23180_C | def batch_prime_check(numbers):
"""
Check primality of multiple numbers.
Parameters:
numbers (list): A list of integers to check for primality.
Returns:
list: A list of boolean values where True represents a prime number, and False represents a non-prime number.
>>> batch_prime_ch... | def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def batch_prime_check(numbers):
"""
Ch... | from solution import batch_prime_check
def test_basic_primes():
assert batch_prime_check([2, 3, 5, 7, 11, 13, 17, 19]) == [True, True, True, True, True, True, True, True]
def test_non_primes():
assert batch_prime_check([1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20]) == [False, False, False, False, False, False, ... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Check primality of multiple numbers.\n\nParameters:\nnumbers (list): A list of integers to check for primality.\n\nReturns:\nlist: A list of boolean values... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n... | trial_gpt4o_2 | {
"original_instruction": "### Prime Check Algorithm Assessment\n\n**Objective**:\n\nYou are tasked with verifying the primality of a sequence of numbers efficiently using an optimized prime-check algorithm. \n\n**Task**:\n\nWrite a function `batch_prime_check` that takes a list of integers and returns a list of True... | 0.713656 | Data_Structure_23180 | C | [
"is_prime",
"batch_prime_check"
] | 2 | [
[
"batch_prime_check",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 16920921ef98b73a9c497b65e799f90a2030a25d | e755f61693cdad567657d5d35492843ab26150cf | |||
v1.0 | complete | Data_Structure | Data_Structure_22377_C | from typing import List, Tuple
def find_all_maximal_cliques(n: int, edges: List[Tuple[int, int]]) -> List[List[int]]:
""" Find all maximal cliques in an undirected graph.
Args:
n (int): Number of vertices in the graph.
edges (List[Tuple[int, int]]): List of edges where each edge is a tuple (u, v).
... | from typing import List, Tuple, Set
def bron_kerbosch_pivot(R: Set[int], P: Set[int], X: Set[int], adj_list: List[Set[int]], cliques: List[List[int]]):
if not P and not X:
cliques.append(list(R))
return
u = next(iter(P.union(X)))
for v in P - adj_list[u]:
bron_kerbosch_pivot(R.union... | from solution import find_all_maximal_cliques, find_largest_clique
def test_find_all_maximal_cliques_single_clique():
n = 5
edges = [(1, 2), (2, 3), (3, 1), (1, 4), (4, 5)]
expected_cliques = [[1, 2, 3], [1, 4], [4, 5]]
actual_cliques = find_all_maximal_cliques(n, edges)
assert len(actual_cliques) ... | [
{
"docstring": null,
"function_declaration": "def bron_kerbosch_pivot(R, P, X, adj_list, cliques):",
"function_name": "bron_kerbosch_pivot",
"parameter_list": "(R, P, X, adj_list, cliques)"
},
{
"docstring": null,
"function_declaration": "def find_all_maximal_cliques(n, edges):",
"fu... | [
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 find_all_maximal_cliques(n, edges):\n def bron_kerbosch(R, P, X, adj_list):\n if not P and not X:\n yield R\n else:\n ... | trial_gpt4o_2 | {
"original_instruction": "You are given an undirected graph represented by an adjacency list. Your task is to implement algorithms to find all maximal cliques in the graph. However, to demonstrate advanced understanding, you need to make the following enhancements:\n\n1. Optimize the Bron-Kerbosch algorithm using pi... | 0.543647 | Data_Structure_22377 | C | [
"bron_kerbosch_pivot",
"find_all_maximal_cliques",
"find_largest_clique"
] | 3 | [
[
"find_all_maximal_cliques",
"bron_kerbosch_pivot"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8e9f6fb360f993b88c3664293e1abff76b6462cf | c8e02f9d78a0aac064dfe97d5f32181cdce633f4 | |||
v1.0 | complete | Data_Structure | Data_Structure_23027_C | def validate_inputs(a, p):
""" Validate the inputs `a` and `p` for the Diffie-Hellman key exchange.
>>> validate_inputs(2, 23) # Should not raise an error
>>> validate_inputs(5, 101) # Should not raise an error
>>> validate_inputs(-1, 23) # Raises ValueError
>>> validate_inputs("5", 23) # Raises Val... | import random
from sympy import isprime, primerange
def validate_inputs(a, p):
"""
Validate the inputs `a` and `p` for the Diffie-Hellman key exchange.
"""
if not (isinstance(a, int) and a > 0):
raise ValueError("Primitive root 'a' must be a positive integer.")
if not (isinstance(p, int) an... | from solution import validate_inputs, generate_large_prime, diffie_hellman_key_exchange
import pytest
def test_validate_inputs_valid():
validate_inputs(2, 23)
validate_inputs(5, 101)
def test_validate_inputs_invalid_primitive_root():
with pytest.raises(ValueError, match="Primitive root 'a' must be a posit... | [
{
"docstring": "Validate the inputs `a` and `p` for the Diffie-Hellman key exchange.",
"function_declaration": "def validate_inputs(a, p):",
"function_name": "validate_inputs",
"parameter_list": "(a, p)"
},
{
"docstring": "Generate a large prime number of the specified bit length.",
"fun... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sympy import isprime, primerange, primitive_root, randprime\nimport random\n\ndef validate_inputs(a, p):\n \"\"\"\n Validates that `a` is a primiti... | trial_gpt4o_1 | {
"original_instruction": "Diffie-Hellman Key Exchange Enhancements\n\n**Context**: The Diffie-Hellman key exchange algorithm enables two parties to securely exchange cryptographic keys over a public channel. Your task is to enhance the current implementation by adding input validation, error handling, and key length... | 0.521402 | Data_Structure_23027 | C | [
"validate_inputs",
"generate_large_prime",
"diffie_hellman_key_exchange"
] | 3 | [
[
"diffie_hellman_key_exchange",
"generate_large_prime"
],
[
"diffie_hellman_key_exchange",
"validate_inputs"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 55fe44798784bb8f3c8e9cde5464fa5a9b87181d | 8e1133b9edc1a288827185ac600b62b0cea244ba | |||
v1.0 | complete | Data_Structure | Data_Structure_22993_C | from typing import List
def ford_fulkerson(n: int, capacity: List[List[int]]) -> int:
"""
Find the maximum possible flow from the source (vertex 0) to the sink (vertex n-1) in the given flow network.
Parameters:
n (int): The number of vertices in the network.
capacity (List[List[int]]): A 2D l... | from collections import deque
def bfs(source, sink, parent, n, residual_capacity):
# Perform BFS from source to sink and store the path in the parent array
visited = [False] * n
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v in ra... | from solution import ford_fulkerson
def test_max_flow_example1():
n = 4
capacity = [
[0, 1000, 1000, 0],
[0, 0, 1, 1000],
[0, 0, 0, 1000],
[0, 0, 0, 0]
]
assert ford_fulkerson(n, capacity) == 2000
def test_max_flow_zero_capacity():
n = 3
capacity = [
[0,... | [
{
"docstring": null,
"function_declaration": "def bfs(source, sink, parent, n, residual_capacity):",
"function_name": "bfs",
"parameter_list": "(source, sink, parent, n, residual_capacity)"
},
{
"docstring": null,
"function_declaration": "def ford_fulkerson(n, capacity):",
"function_... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(capacity, source, sink, parent):\n visited = [False] * len(capacity)\n queue = deque([source])\n visited[sou... | trial_gpt4o_1 | {
"original_instruction": "### Maximum Flow Optimization Challenge\n\nYou are provided with a flow network consisting of `n` vertices. Each vertex is represented as an integer from `0` to `n-1`, where vertex `0` is the source and vertex `n-1` is the sink. The network can be described by an adjacency matrix `capacity`... | 0.513013 | Data_Structure_22993 | C | [
"bfs",
"ford_fulkerson"
] | 2 | [
[
"ford_fulkerson",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 777042a6f8fcf2c54f9a23ffad056bc3a4eecfd0 | fe435793014af327bd4917748e547ea158212485 | |||
v1.0 | complete | Data_Structure | Data_Structure_22231_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def delete_node(root, key):
""" Delete a node from a Binary Search Tree (BST) and return the root of the modified tree.
:param root: TreeNode, the root of the BS... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def delete_node(root, key):
if not root:
return root
if key < root.val:
root.left = delete_node(root.left, key)
elif key > root.val:
... | from solution import delete_node, build_tree, tree_to_list
def test_delete_node_middle_node():
root = build_tree([5,3,6,2,4,None,7])
key = 3
expected_result = [5, 4, 6, 2, None, None, 7]
new_root = delete_node(root, key)
assert tree_to_list(new_root) == expected_result
def test_delete_node_with_no... | [] | [
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": "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 de... | trial_gpt4o_1 | {
"original_instruction": "### BinarySearchTree Deletion:\n\nYou are required to implement the `delete_node` function in a given Binary Search Tree (BST). Specifically, you need to delete a node from the BST that matches a given key, ensuring that the tree remains a valid BST afterward.\n\n**Function Signature:**\n``... | 0.641588 | Data_Structure_22231 | C | [
"delete_node",
"get_min",
"build_tree",
"tree_to_list"
] | 4 | [
[
"delete_node",
"get_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 8629d478fe0f27eed4c41a27062e619128f78582 | 2d7ddf622019b6155ef6cf9ecd54ee58e73bb271 | |||
v1.0 | complete | Data_Structure | Data_Structure_22848_C | import random
def generate_sequence(chain: dict, initial_state: str, length: int) -> list:
"""
Generates a sequence of states based on the given Markov chain.
Parameters:
chain (dict): The Markov chain where keys are states and values are dictionaries of state transition probabilities.
... | import random
def normalize_probabilities(transitions):
total = sum(transitions.values())
return {state: prob / total for state, prob in transitions.items()}
def generate_sequence(chain: dict, initial_state: str, length: int) -> list:
"""
Generates a sequence of states based on the given Markov chain.... | from solution import generate_sequence
def test_generate_sequence_basic_case():
chain = {"A": {"A": 0.6, "B": 0.4}, "B": {"A": 0.5, "B": 0.5}}
sequence = generate_sequence(chain, "A", 5)
assert len(sequence) == 5
assert sequence[0] == "A"
def test_generate_sequence_single_state():
chain = {"A": {"... | [
{
"docstring": null,
"function_declaration": "def normalize_probabilities(transitions):",
"function_name": "normalize_probabilities",
"parameter_list": "(transitions)"
},
{
"docstring": "Generates a sequence of states based on the given Markov chain.\n\nParameters:\n chain (dict): The Mar... | [
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 normalize_probabilities(probabilities):\n total = sum(probabilities.values())\n return {state: prob / total for state, prob in prob... | trial_gpt4o_1 | {
"original_instruction": "**Context**:\nA predictive text application uses Markov Chains to suggest the next word in a sentence given the current word. Each word (current state) transitions to the next word (next state) based on known probabilities derived from large data analysis.\n\n**Task**:\nWrite a function `ge... | 0.548225 | Data_Structure_22848 | C | [
"normalize_probabilities",
"generate_sequence"
] | 2 | [
[
"generate_sequence",
"normalize_probabilities"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7aeae8b1e3af6e46c2508f4dcc8a30d1adab372f | ea431cd0a27b50008d8768c6d9453473caee8a60 | |||
v1.0 | complete | Data_Structure | Data_Structure_23197_C | def gen_prime(k: int, seed=None) -> int:
""" Generate a k-bit prime number using the Miller-Rabin primality test.
>>> p = gen_prime(16, seed=42)
>>> assert is_prime(p)
>>> assert gen_prime(512) != gen_prime(512)
"""
def modinv(a: int, m: int) -> int:
""" Compute the modular inverse of a und... | import random
# Miller-Rabin Primality Test
def is_prime(n, k=40):
""" Test if a number is a prime """
if n == 2 or n == 3:
return True
if n <= 1 or n % 2 == 0:
return False
# Write (n - 1) as 2^s * d
s, d = 0, n - 1
while d % 2 == 0:
s += 1
d //= 2
# Witness... | from solution import gen_prime, modinv
def test_gen_prime():
prime1 = gen_prime(16, seed=42)
prime2 = gen_prime(16, seed=42)
assert prime1 == prime2, f"Expected {prime1} to be equal to {prime2}"
assert is_prime(prime1), f"Expected {prime1} to be prime"
prime3 = gen_prime(512)
assert is_pri... | [
{
"docstring": "Test if a number is a prime ",
"function_declaration": "def is_prime(n, k=40):",
"function_name": "is_prime",
"parameter_list": "(n, k=40)"
},
{
"docstring": "Generate a k-bit prime number ",
"function_declaration": "def gen_prime(k, seed=None):",
"function_name": "ge... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef miller_rabin_primality_test(n, k=5):\n \"\"\"Miller-Rabin primality test to check if a number is prime.\"\"\"\n if n <= 1:\n ... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with enhancing and fully implementing the RSA encryption system described below. Your enhancements should focus on:\n\n1. Improving the efficiency of prime number generation.\n2. Optimizing the calculation of the modular inverse.\n\n### Task\n\n**Part 1: Efficient Prime Gener... | 0.680889 | Data_Structure_23197 | C | [
"is_prime",
"gen_prime",
"modinv"
] | 3 | [
[
"gen_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0a2ecf39ea6f01249b38c4cd7cd968562b360331 | 34b03a0ea56abf3fe6c94312170c29a4b752d592 | |||
v1.0 | complete | Data_Structure | Data_Structure_22234_C | def optimized_gcd(a: int, b: int) -> int:
""" Calculates the greatest common divisor (GCD) of two integers.
Throws ValueError if any input is zero.
Uses Euclid's Algorithm or Bitwise GCD based on input properties.
>>> optimized_gcd(48, 18)
6
>>> optimized_gcd(0, 15)
Traceback (most rece... | def euclid_gcd(a, b):
while b:
a, b = b, a % b
return a
def bitwise_gcd(a, b):
if a == 0:
return b
if b == 0:
return a
shift = 0
while ((a | b) & 1) == 0:
a >>= 1
b >>= 1
shift += 1
while (a & 1) == 0:
a >>= 1
while b != 0:
... | import pytest
from solution import optimized_gcd
def test_gcd_regular_case():
assert optimized_gcd(48, 18) == 6
assert optimized_gcd(100, 10) == 10
def test_gcd_prime_numbers():
assert optimized_gcd(13, 17) == 1
assert optimized_gcd(29, 13) == 1
def test_gcd_one_zero_input():
with pytest.raises(V... | [
{
"docstring": null,
"function_declaration": "def euclid_gcd(a, b):",
"function_name": "euclid_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def bitwise_gcd(a, b):",
"function_name": "bitwise_gcd",
"parameter_list": "(a, b)"
},
{
"docst... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_gcd(a, b):\n \"\"\"\n Returns the greatest common divisor of a and b using an optimized approach.\n Uses Euclid's method combined with ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Efficient GCD Calculation\n\nYou have been provided with two functions that calculate the greatest common divisor (GCD) of two integers using different methods. Your task is to create a comprehensive function that combines the robustness and error handling of the standard Eucl... | 0.670825 | Data_Structure_22234 | C | [
"euclid_gcd",
"bitwise_gcd",
"optimized_gcd"
] | 3 | [
[
"optimized_gcd",
"bitwise_gcd"
],
[
"optimized_gcd",
"euclid_gcd"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fe9404f8ac46ad92d854f8f23eaa4a7940f0803d | 10a8926375cacd8311c2d07f4093f7b432e83850 | |||
v1.0 | complete | Data_Structure | Data_Structure_22836_C | from typing import List
def search_insert(array: List[int], low: int, high: int, target: int) -> int:
"""
Helper function to perform binary search for the target in the array[low:high+1]
and return the index where the target should be inserted.
"""
pass
def insertion_sort(array: List[int]) -> List... | from typing import List
def search_insert(array: List[int], low: int, high: int, target: int) -> int:
"""
Helper function to perform binary search for the target in the array[low:high+1]
and return the index where the target should be inserted.
"""
while low <= high:
mid = (low + high) // 2... | from solution import insertion_sort
def test_insertion_sort_example_1():
assert insertion_sort([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13]
def test_insertion_sort_example_2():
assert insertion_sort([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12]
def test_insertion_sort_empty():
assert insertion_s... | [
{
"docstring": "Helper function to perform binary search for the target in the array[low:high+1]\nand return the index where the target should be inserted.",
"function_declaration": "def search_insert(array, low, high, target):",
"function_name": "search_insert",
"parameter_list": "(array, low, high... | [
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 Helper function to use binary search to find the index where... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort with Binary Search\n\nYou are required to implement the Insertion Sort algorithm using the binary search helper method `search_insert` provided. The objective is to optimize the insertion step using binary search to locate the position where each element should be inserte... | 0.640201 | Data_Structure_22836 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 120c8fac6872962bce0721cfc69957c5fc8125b2 | dd213e7aee9246b920a4268e682b30cc87ddad21 | |||
v1.0 | complete | Data_Structure | Data_Structure_22593_C | import random
from typing import Dict, Any
def validate_chain(chain: Dict[str, Dict[str, float]]) -> bool:
"""
Validates whether the provided Markov chain is valid.
Parameters:
- chain (dict): Dictionary representing the Markov chain.
Returns:
- bool: True if the chain is valid, False otherwi... | import random
def validate_chain(chain):
"""
Validates whether the provided Markov chain is valid.
Parameters:
- chain (dict): Dictionary representing the Markov chain.
Returns:
- bool: True if the chain is valid, False otherwise.
"""
for state, transitions in chain.items():
... | from solution import validate_chain, predict_state
def test_validate_chain_valid():
my_chain = {
'A': {'A': 0.6, 'E': 0.4},
'E': {'A': 0.7, 'E': 0.3}
}
assert validate_chain(my_chain) == True
def test_validate_chain_invalid_prob_sum():
my_chain = {
'A': {'A': 0.6, 'E': 0.5},
... | [
{
"docstring": "Validates whether the provided Markov chain is valid.\n\nParameters:\n- chain (dict): Dictionary representing the Markov chain. \n\nReturns:\n- bool: True if the chain is valid, False otherwise.",
"function_declaration": "def validate_chain(chain):",
"function_name": "validate_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 validate_chain(chain):\n \"\"\"\n Validates whether the provided Markov chain is valid.\n \n Parameters:\n - chain (dict):... | trial_gpt4o_0 | {
"original_instruction": "You are tasked with enhancing a Markov Chain implementation. This Markov Chain is modeled using a dictionary with each state having a dictionary of possible next states and their respective probabilities. Your goal is to extend the functionality and improve efficiency.\n\n#### Requirements\... | 0.529451 | Data_Structure_22593 | C | [
"validate_chain",
"predict_state",
"__choose_state"
] | 3 | [
[
"predict_state",
"__choose_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 098b6421ef3d65c1154a15c1626bdd7213eb3ce1 | b05d0c249dde63aeded6c66da6e83778d63f80c5 | |||
v1.0 | complete | Data_Structure | Data_Structure_22140_C | def merge_sort(arr):
"""
Sorts an array using the Merge Sort algorithm.
Parameters:
arr (list): The list of elements to be sorted.
Returns:
list: A new list containing the sorted elements.
"""
pass
import random
def is_sorted(arr):
""" Check if the array is sorted in non-decreasi... | import random
# Bogo Sort for comparison (not practical, included just for comparison study)
def is_sorted(arr):
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def bogo_sort(arr):
while not is_sorted(arr):
random.shuffle(arr)
return arr
# Efficient Merge Sort implementation
def merge_s... | from solution import merge_sort, bogo_sort, is_sorted
import time
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_two_elements():
assert merge_sort([2, 1]) == [1, 2]
def test_merge_sort_sorted_list():
as... | [
{
"docstring": null,
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def bogo_sort(arr):",
"function_name": "bogo_sort",
"parameter_list": "(arr)"
},
{
"docstring": "So... | [
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\n# Bogo Sort for comparison (not practical, included just for comparison study)\ndef is_sorted(arr):\n return all(arr[i] <= arr[i+1] for i ... | trial_gpt4o_0 | {
"original_instruction": "You are given a rather impractical algorithm called Bogo Sort, which attempts to sort an array by randomly shuffling it until it is sorted. Despite its lack of practical use, Bogo Sort serves as an educational example.\n\nGiven this, your task is to implement a more efficient sorting algori... | 0.61386 | Data_Structure_22140 | C | [
"is_sorted",
"bogo_sort",
"merge_sort",
"merge"
] | 4 | [
[
"bogo_sort",
"is_sorted"
],
[
"merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 52de5c7dd964257b3c3aa3dc0a5bd9c3a39a6004 | b573a320da0bd9c6af2d4850306903045da8f9af | |||
v1.0 | complete | Data_Structure | Data_Structure_22674_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
""" Perform Merge Sort on the input list and return the sorted list.
>>> merge_sort([34, 7, 23, 32, 5, 62])
[5, 7, 23, 32, 34, 62]
>>> merge_sort([])
[]
>>> merge_sort([1])
[1]
>>> merge_sort([5, 4, 3, 2, 1])
[1, 2... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
merged = [0] * len(arr)
merge(left, right, merged)
return merged
def merge(left: List[int]... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_list():
assert... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right, merged):",
"function_name": "merge",
"parameter_list": "(left, right, merged)"
}... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half =... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Implementation Challenge\n\nMerge Sort is a highly efficient, stable, and comparison-based sorting algorithm. As you have learned, it works on the principle of divide and conquer. Your task is to implement the Merge Sort algorithm based on the provided guidelines.\n\n#### Pro... | 0.576242 | Data_Structure_22674 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 98e6da9eabc8051b6655ceb8a9191156f81b75f8 | e7d2722312f10aac0f6530afbe44e0147bf6b883 | |||
v1.0 | complete | Data_Structure | Data_Structure_23047_C | def iterative_power(a, n, mod=None):
result = 1
base = a if mod is None else a % mod
while n > 0:
if n % 2 == 1: # If n is odd, multiply the current base to the result
result = result * base if mod is None else (result * base) % mod
base = base * base if mod is None else (base *... | def iterative_power(a, n, mod=None):
result = 1
base = a if mod is None else a % mod
while n > 0:
if n % 2 == 1: # If n is odd, multiply the current base to the result
result = result * base if mod is None else (result * base) % mod
base = base * base if mod is None else (base *... | from solution import modular_exponentiation
def test_small_numbers():
assert modular_exponentiation(2, 10) == (1024, 1024)
assert modular_exponentiation(3, 0) == (1, 1)
def test_large_numbers():
a, n, mod = 2, 1000000000, 1000000007
result_iter, result_recur = modular_exponentiation(a, n, mod)
ass... | [
{
"docstring": null,
"function_declaration": "def iterative_power(a, n, mod=None):",
"function_name": "iterative_power",
"parameter_list": "(a, n, mod=None)"
},
{
"docstring": null,
"function_declaration": "def recursive_power(a, n, mod=None):",
"function_name": "recursive_power",
... | [
0,
0,
0,
0,
1,
0,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def iterative_power(a, n, mod=None):\n \"\"\"\n Iterative implementation of binary exponentiation.\n \"\"\"\n result = 1\n base = a if mod is N... | trial_gpt4o_8 | {
"original_instruction": "You are given two implementations of the binary exponentiation algorithm – one iterative and one recursive. Implement a function `modular_exponentiation` that calculates \\(a^n \\mod \\, mod\\) using the provided power functions and compare the outputs for correctness. The function should t... | 0.710621 | Data_Structure_23047 | C | [
"iterative_power",
"recursive_power",
"modular_exponentiation"
] | 3 | [
[
"modular_exponentiation",
"iterative_power"
],
[
"modular_exponentiation",
"recursive_power"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | be346b0ccf9d20872d47eea6bbd1cc23318c0e0b | 5c530b478b1ef325d64ae1945a54de24acab0985 | |||
v1.0 | complete | Data_Structure | Data_Structure_22839_C | import random
from sympy import isprime
def secure_diffie_hellman_key_exchange(a: int, p: int) -> int:
"""
Perform a secure Diffie-Hellman key exchange and return the shared secret key.
:param a: The primitive root modulo p
:param p: A prime number
:return: The shared secret key or None if validati... | import random
from sympy import isprime
def secure_diffie_hellman_key_exchange(a: int, p: int) -> int:
"""
Perform a secure Diffie-Hellman key exchange and return the shared secret key.
:param a: The primitive root modulo p
:param p: A prime number
:return: The shared secret key or None if validati... | def test_secure_diffie_hellman_key_exchange():
# Valid test case
assert isinstance(secure_diffie_hellman_key_exchange(5, 23), int)
# Invalid prime number
assert secure_diffie_hellman_key_exchange(5, 22) == None
# Invalid primitive root
assert secure_diffie_hellman_key_exchange(4, 23) =... | [
{
"docstring": "Perform a secure Diffie-Hellman key exchange and return the shared secret key.\n:param a: The primitive root modulo p\n:param p: A prime number\n:return: The shared secret key or None if validation fails.",
"function_declaration": "def secure_diffie_hellman_key_exchange(a, p):",
"functio... | [
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\n\ndef secure_diffie_hellman_key_exchange(a: int, p: int) -> int:\n \"\"\"\n Perform a secure Diffie-Hellman ke... | trial_gpt4o_0 | {
"original_instruction": "Here is a coding challenge based on the Diffie-Hellman key exchange and its mathematical underpinnings:\n\n### Problem Statement\n\nAlice and Bob want to securely establish a shared secret key using the Diffie-Hellman key exchange protocol. However, the current system requires enhancement t... | 0.571283 | Data_Structure_22839 | C | [
"secure_diffie_hellman_key_exchange",
"is_primitive_root",
"prime_factors"
] | 3 | [
[
"is_primitive_root",
"prime_factors"
],
[
"secure_diffie_hellman_key_exchange",
"is_primitive_root"
]
] | 2 | [] | false | [] | false | pytest | false | [
"sympy"
] | false | 8937ad21d016495b252b53e7d129452a6de6b279 | b98cf6e2bf37b3831ca79a825c33c3bc9c730941 | |||
v1.0 | complete | Data_Structure | Data_Structure_22392_C | from typing import List, Tuple
def binary_search_iter(array: List[int], target: int) -> int:
"""
Implement the binary search algorithm iteratively.
Parameters:
array (List[int]): A sorted list of integers in ascending order.
target (int): An integer value to search for in the array.
R... | from typing import List, Tuple
def binary_search_iter(array: List[int], target: int) -> int:
"""
Implement the binary search algorithm iteratively.
Parameters:
array (List[int]): A sorted list of integers in ascending order.
target (int): An integer value to search for in the array.
R... | from solution import binary_search_iter, binary_search_recur, find_first_and_last
def test_binary_search_iter_found():
assert binary_search_iter([1, 2, 3, 4, 5], 3) == 2
def test_binary_search_iter_not_found():
assert binary_search_iter([1, 2, 3, 4, 5], 6) == -1
def test_binary_search_recur_found():
asse... | [
{
"docstring": "Implement the binary search algorithm iteratively.\n\nParameters:\narray (List[int]): A sorted list of integers in ascending order.\ntarget (int): An integer value to search for in the array.\n\nReturns:\nint: The index of the target in the array if found, otherwise -1.",
"function_declarati... | [
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": "from typing import List, Tuple\n\ndef binary_search_iter(array: List[int], target: int) -> int:\n low, high = 0, array.length - 1\n while low <= high:\n... | trial_gpt4o_5 | {
"original_instruction": "**Problem: Binary Search Implementation and Application**\n\nYou are to implement the binary search algorithm both iteratively and recursively. In addition, you will write a function to use binary search for finding the first and last occurrence of a given target in a sorted array.\n\n### F... | 0.703512 | Data_Structure_22392 | C | [
"binary_search_iter",
"binary_search_recur",
"find_first_and_last",
"find_first_occurrence",
"find_last_occurrence"
] | 5 | [
[
"find_first_and_last",
"find_first_occurrence"
],
[
"find_first_and_last",
"find_last_occurrence"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b98f18f8ce70da0226c890496e9936a740a592a8 | 4a67aeac73824156b075b9864f3e83cd074ba0ca | |||
v1.0 | complete | Data_Structure | Data_Structure_22965_C | from typing import List
def matrix_power(mat: List[List[int]], exp: int) -> List[List[int]]:
"""Compute the matrix raised to the power exp using efficient matrix exponentiation.
Args:
mat (List[List[int]]): A 2D list of integers representing the square matrix.
exp (int): The power to which the matrix ... | from typing import List
def matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
n = len(A)
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += A[i][k] * B[k][j]
return result
def matri... | from solution import matrix_power
def test_matrix_power_example1():
mat = [
[1, 2],
[3, 4]
]
exp = 2
result = matrix_power(mat, exp)
expected = [
[7, 10],
[15, 22]
]
assert result == expected
def test_matrix_power_example2():
mat = [
[2, 0],
... | [
{
"docstring": null,
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def matrix_identity(n):",
"function_name": "matrix_identity",
"parameter_list": "(n)"
},
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_power(mat, exp):\n \"\"\"\n Computes the matrix `mat` raised to the power `exp` using efficient matrix exponentiation.\n\n Parameters:\n ... | trial_gpt4o_2 | {
"original_instruction": "You are given a square matrix `mat` and an integer `exp`. Write a function `matrix_power(mat: List[List[int]], exp: int) -> List[List[int]]` that computes the matrix raised to the power `exp` using efficient matrix exponentiation.\n\n### Function Signature:\n```python\ndef matrix_power(mat:... | 0.497664 | Data_Structure_22965 | C | [
"matrix_multiply",
"matrix_identity",
"matrix_power"
] | 3 | [
[
"matrix_power",
"matrix_identity"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4ab585b0320b0af4f8f923bf03c3127784b55ab9 | 9d409ae65bae58156297c29cd379d15bf632b024 | |||
v1.0 | complete | Data_Structure | Data_Structure_23194_C | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_iterative(root):
""" Iterative In-Order Traversal
Perform an in-order traversal of a binary tree iteratively.
Args:
root (Node): The root of the b... | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_iterative(root):
""" Iterative In-Order Traversal """
res = []
stack = []
while root or stack:
while root:
stack.append(root)
... | from solution import Node, inorder_iterative, inorder_recursive, compare_traversals
def test_inorder_traversal():
# Construct a test binary tree
"""
1
/ \
2 3
/ \ \
4 5 6
"""
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = No... | [] | [
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": "class Node:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef inorder_... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implementing and Optimizing In-Order Traversal\n\nYou are provided with a binary tree. Your task is to implement the in-order traversal for this tree. You need to complete two versions of the traversal: an iterative approach and a recursive approach. Also, you need to implemen... | 0.588259 | Data_Structure_23194 | C | [
"inorder_iterative",
"inorder_recursive",
"compare_traversals"
] | 3 | [
[
"compare_traversals",
"inorder_iterative"
],
[
"compare_traversals",
"inorder_recursive"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | true | [] | true | b0a9aa383453967fff6808aff82a296a4acc9344 | 0b0f86b5047fcc900bbd83512ba694a67677ccfe | |||
v1.0 | complete | Data_Structure | Data_Structure_23365_C | from typing import List
def find_pattern_occurrences(text: str, pattern: str) -> List[int]:
"""Using the Knuth-Morris-Pratt (KMP) algorithm, find all starting positions in the text where the pattern is found as a substring.
>>> find_pattern_occurrences('hello there hero!', 'he')
[0, 7, 12]
>>> find_pat... | from typing import List
def compute_pi(pattern: str) -> List[int]:
pi = [0] * len(pattern)
j = 0
for i in range(1, len(pattern)):
while (j > 0 and pattern[i] != pattern[j]):
j = pi[j - 1]
if pattern[i] == pattern[j]:
j += 1
pi[i] = j
return pi
def find_p... | from solution import find_pattern_occurrences
def test_empty_text():
assert find_pattern_occurrences('', 'pattern') == []
def test_empty_pattern():
assert find_pattern_occurrences('text', '') == []
def test_no_occurrences():
assert find_pattern_occurrences('this is a test', 'pattern') == []
def test_sin... | [
{
"docstring": null,
"function_declaration": "def compute_pi(pattern):",
"function_name": "compute_pi",
"parameter_list": "(pattern)"
},
{
"docstring": null,
"function_declaration": "def find_pattern_occurrences(text, pattern):",
"function_name": "find_pattern_occurrences",
"para... | [
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 compute_prefix_function(pattern: str) -> List[int]:\n m = len(pattern)\n pi = [0] * m\n j = 0\n for i in range(1, m... | trial_gpt4o_2 | {
"original_instruction": "### Question\n\nYou are given a text string and a pattern string. Using the Knuth-Morris-Pratt (KMP) algorithm, find all starting positions in the text where the pattern is found as a substring.\n\n#### Function Signature\n```python\ndef find_pattern_occurrences(text: str, pattern: str) -> ... | 0.673986 | Data_Structure_23365 | C | [
"compute_pi",
"find_pattern_occurrences"
] | 2 | [
[
"find_pattern_occurrences",
"compute_pi"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0b6c87abee9354dba2eea27801b5a757ba39851d | 816091ed73c40fe0e316313a1ca63e8d6f52a02d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.