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_34251_C | from typing import List, Dict
from collections import defaultdict
def word_squares(words: List[str]) -> List[List[str]]:
"""
Find all possible word squares from a given list of words.
>>> word_squares(["area", "lead", "wall", "lady", "ball"])
[['wall', 'area', 'lead', 'lady'], ['ball', 'area', 'l... | from typing import List, Dict
from collections import defaultdict
def build_prefix_dict(words: List[str], word_length: int) -> Dict[str, List[str]]:
prefix_dict = defaultdict(list)
for word in words:
for i in range(word_length):
prefix_dict[word[:i]].append(word)
return prefix_dict
def... | from solution import word_squares
def test_example_case():
words = ["area", "lead", "wall", "lady", "ball"]
result = word_squares(words)
expected = [
["wall", "area", "lead", "lady"],
["ball", "area", "lead", "lady"]
]
assert sorted(result) == sorted(expected)
def test_single_word(... | [
{
"docstring": null,
"function_declaration": "def build_prefix_dict(words, word_length):",
"function_name": "build_prefix_dict",
"parameter_list": "(words, word_length)"
},
{
"docstring": null,
"function_declaration": "def backtrack(step, word_length, square, prefix_dict, results):",
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import defaultdict\n\ndef word_squares(words: List[str]) -> List[List[str]]:\n def build_prefix_dict(words):\n ... | trial_gpt4o_1 | {
"original_instruction": "### Word Squares Construction\n\n**Objective**: Implement a function to find all possible word squares from a given list of words.\n\n**Scenario**:\nYou are designing a crossword puzzle and need to ensure that certain word sequences form valid word squares. Each word sequence must have its ... | 0.628995 | Data_Structure_34251 | C | [
"build_prefix_dict",
"backtrack",
"word_squares"
] | 3 | [
[
"word_squares",
"backtrack"
],
[
"word_squares",
"build_prefix_dict"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a6477e82a55912130c7fce62499f87f18a1a31ff | 708216a92452b65c05d4fd103df79f9e454f3405 | |||
v1.0 | complete | Data_Structure | Data_Structure_37527_C | def probable_prime_checker(n: int, k: int) -> bool:
""" Determines if n is a probable prime using the Miller-Rabin primality test.
>>> probable_prime_checker(11, 5) # Expected output: True
>>> probable_prime_checker(4, 5) # Expected output: False
>>> probable_prime_checker(0, 5) # Expected output: Fa... | import random
def is_prime(n: int, k: int) -> bool:
"""
This helper function checks if n is a probable prime using the Miller-Rabin test.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
# Find r and d such that n-1 = d * 2^r, with d od... | from solution import probable_prime_checker
def test_probable_prime_checker_basic():
assert probable_prime_checker(11, 5) == True
assert probable_prime_checker(4, 5) == False
assert probable_prime_checker(0, 5) == False
assert probable_prime_checker(17, 3) == True
def test_probable_prime_checker_edge_... | [
{
"docstring": "This helper function checks if n is a probable prime using the Miller-Rabin test.",
"function_declaration": "def is_prime(n, k):",
"function_name": "is_prime",
"parameter_list": "(n, k)"
},
{
"docstring": "Determines if n is a probable prime using the Miller-Rabin primality t... | [
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_prime(n, k):\n if n <= 1:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 == 0:\n return ... | trial_gpt4o_2 | {
"original_instruction": "**Probable Prime Finder**\n\nYou are tasked with developing a function that identifies whether a number is a probable prime using the Rabin-Miller primality test. The function should call the `is_prime` function outlined above but needs to include several additional features to handle real-... | 0.76523 | Data_Structure_37527 | C | [
"is_prime",
"probable_prime_checker"
] | 2 | [
[
"probable_prime_checker",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fd89ca0fbaa15d955b4687c9d954932cc2acbd06 | 9c1cb3ee6dde541cdd4a9e74c9e2036b08c5541d | |||
v1.0 | complete | Data_Structure | Data_Structure_8706_C | def count_strobogrammatic_in_range(low: str, high: str) -> int:
""" Count the total strobogrammatic numbers that exist in a range of two integers, `low` and `high` inclusive.
>>> count_strobogrammatic_in_range("50", "100") 3
>>> count_strobogrammatic_in_range("0", "9") 3
>>> count_strobogrammatic_in_ran... | def is_strobogrammatic(num):
"""
Check if a number is strobogrammatic.
"""
strobogrammatic_pairs = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
left, right = 0, len(num) - 1
while left <= right:
if num[left] not in strobogrammatic_pairs or strobogrammatic_pairs[num[left]] != num[ri... | from solution import count_strobogrammatic_in_range
def test_single_digit_range():
assert count_strobogrammatic_in_range("0", "9") == 3 # 0, 1, 8
def test_small_range():
assert count_strobogrammatic_in_range("50", "100") == 3 # 69, 88, 96
def test_no_strobogrammatic():
assert count_strobogrammatic_in_r... | [
{
"docstring": "Check if a number is strobogrammatic.",
"function_declaration": "def is_strobogrammatic(num):",
"function_name": "is_strobogrammatic",
"parameter_list": "(num)"
},
{
"docstring": "Count all strobogrammatic numbers in the inclusive range [low, high].",
"function_declaratio... | [
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 count_strobogrammatic_in_range(low: str, high: str) -> int:\n \"\"\"\n Return the count of strobogrammatic numbers within the inclusive range [low, ... | trial_gpt4o_1 | {
"original_instruction": "### Coding Challenge: Count Strobogrammatic Numbers in a Range\n\n**Problem Statement**:\nA strobogrammatic number is a number that looks the same when rotated 180 degrees (it appears the same upside down). Write a function to count the total strobogrammatic numbers that exist in a range of... | 0.573995 | Data_Structure_8706 | C | [
"is_strobogrammatic",
"count_strobogrammatic_in_range"
] | 2 | [
[
"count_strobogrammatic_in_range",
"is_strobogrammatic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4fd768a85f785a299c65dfea144706d05f819ab5 | 5093b0285cc2589e2c3167cc05b149a01b4e4c14 | |||
v1.0 | complete | Data_Structure | Data_Structure_8954_C | import random
from typing import Tuple
def enhanced_generate_key(k: int, seed: int = None) -> Tuple[int, int, int]:
""" Optimize RSA key generation by improving modular inverse calculation efficiency using
the Extended Euclidean Algorithm and using a robust probabilistic primality test for primes.
Par... | import random
from sympy import isprime
def modular_inverse(e, phi):
# Using the Extended Euclidean Algorithm
t1, t2 = 0, 1
r1, r2 = phi, e
while r2 != 0:
quotient = r1 // r2
r1, r2 = r2, r1 - quotient * r2
t1, t2 = t2, t1 - quotient * t2
if t1 < 0:
t1 += phi
ret... | from solution import enhanced_generate_key
def test_key_generation_small_k():
n, e, d = enhanced_generate_key(16, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
data = 20
encrypted = pow(data, e, n)
decrypted = pow(encrypted, d, n)
assert dec... | [
{
"docstring": null,
"function_declaration": "def modular_inverse(e, phi):",
"function_name": "modular_inverse",
"parameter_list": "(e, phi)"
},
{
"docstring": null,
"function_declaration": "def miller_rabin(n, k=40):",
"function_name": "miller_rabin",
"parameter_list": "(n, k=40... | [
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 modular_inverse(e, phi):\n # Using the Extended Euclidean Algorithm\n t1, t2 = 0, 1\n r1, r2 = phi, e... | trial_gpt4o_0 | {
"original_instruction": "### RSA Key Generation Enhanced\n\nGiven the RSA key generation algorithm provided, write a function that optimizes the modular inverse calculation by using the Extended Euclidean Algorithm for greater efficiency. Additionally, ensure the generated primes `p` and `q` are robust using a prob... | 0.668722 | Data_Structure_8954 | C | [
"modular_inverse",
"miller_rabin",
"generate_large_prime",
"enhanced_generate_key"
] | 4 | [
[
"enhanced_generate_key",
"generate_large_prime"
],
[
"enhanced_generate_key",
"modular_inverse"
],
[
"generate_large_prime",
"miller_rabin"
]
] | 3 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 2188cf92ab0f0a8c189a0d520c3efaa25eda396e | 979a422638667381e295a1ed979f971aebe12bca | |||
v1.0 | complete | Data_Structure | Data_Structure_10604_C | from typing import List
def optimized_insertion_sort(arr: List[int], k: int) -> List[int]:
"""
Function to perform optimized insertion sort where it uses standard insertion sort
if the sublist size is above threshold k, otherwise it uses binary insertion sort.
Args:
arr: List[int] - The list of i... | from typing import List
def binary_search(arr: List[int], val: int, start: int, end: int) -> int:
"""
Helper function to perform binary search to find the index to insert `val`
"""
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
start = mid + 1
else:
... | from solution import optimized_insertion_sort
def test_sorted_array():
arr = [1, 2, 3, 4, 5]
assert optimized_insertion_sort(arr, 2) == [1, 2, 3, 4, 5]
def test_unsorted_array():
arr = [5, 2, 9, 1, 5, 6]
assert optimized_insertion_sort(arr, 3) == [1, 2, 5, 5, 6, 9]
def test_single_element_array():
... | [
{
"docstring": "Helper function to perform binary search to find the index to insert `val`",
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "Function to perform optimized inser... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef binary_search(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Helper function to perform binary search... | trial_gpt4o_0 | {
"original_instruction": "### Insertion Sort Implementation with Additional Requirements\n\n**Context**: You have been hired to optimize the sorting operations of a software dealing with customer orders. One of the tasks involves ensuring that a list of order values is sorted efficiently given different types of inp... | 0.682072 | Data_Structure_10604 | C | [
"binary_search",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ca3128ff39f08f91ddf6364ef003617dbb0390c6 | f738429496c086ba34fec7e656df3b1a480bf85c | |||
v1.0 | complete | Data_Structure | Data_Structure_10859_C | from typing import List
def maximum_flow_bfs(adjacency_matrix: List[List[int]]) -> int:
"""
Implement Edmonds-Karp algorithm to calculate the maximum flow from the source
to the sink in a given flow network represented by an adjacency matrix.
Args:
adjacency_matrix (List[List[int]]): 2D list rep... | from typing import List
from collections import deque
def bfs_capacity_path(graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:
visited = [False] * len(graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, cap... | from solution import maximum_flow_bfs
def test_simple_case():
graph = [
[0, 1],
[0, 0]
]
assert maximum_flow_bfs(graph) == 1
def test_example_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
... | [
{
"docstring": null,
"function_declaration": "def bfs_capacity_path(graph, source, sink, parent):",
"function_name": "bfs_capacity_path",
"parameter_list": "(graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(adjacency_matrix):",
"func... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(residual_graph, source, sink, parent):\n visited = [False] * len(residual_graph)\n que... | trial_gpt4o_1 | {
"original_instruction": "### Maximum Flow with Residual Graph and BFS\n\n**Scenario**:\nYou are tasked with optimizing a city's water distribution network. The city's water network can be represented as a flow network with nodes representing junctions and directed edges representing pipes with specific capacities. ... | 0.562919 | Data_Structure_10859 | C | [
"bfs_capacity_path",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs_capacity_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 148aa6d122cc516e29e33359835b71b74aca4c8a | 2f56c03dd1501a26ab39b5587c06bd49777fb3eb | |||
v1.0 | complete | Data_Structure | Data_Structure_11910_C | def enhanced_shell_sort(arr: List[int]) -> List[int]:
"""
Modify the given Shell Sort algorithm to use Sedgewick's gap sequence for improved performance.
Use the sequence of gaps starting at:
1, 5, 19, 41, 109, 209, 505, 929,...
The elements of this sequence can be generated using two parts:
1... | def generate_sedgewick_gaps(n):
"""
Generates the Sedgewick gap sequence up to the largest gap less than n.
"""
gaps = []
index = 0
gap = 0
while True:
if index % 2 == 0:
gap = 9 * (4**index - 2**index) + 1
else:
gap = 8 * (2**(index + 1) - 1) + 1... | from solution import enhanced_shell_sort
def test_enhanced_shell_sort_normal_case():
assert enhanced_shell_sort([12, 34, 54, 2, 3]) == [2, 3, 12, 34, 54]
def test_enhanced_shell_sort_with_negative_numbers():
assert enhanced_shell_sort([7, -4, 1, 8, -5, 2]) == [-5, -4, 1, 2, 7, 8]
def test_enhanced_shell_sort... | [
{
"docstring": "Generates the Sedgewick gap sequence up to the largest gap less than n.",
"function_declaration": "def generate_sedgewick_gaps(n):",
"function_name": "generate_sedgewick_gaps",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def enhanced_shell_sor... | [
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 sedgewick_gaps(max_length: int) -> List[int]:\n gaps = []\n k = 0\n while True:\n gap1 = 4**k + 3 * 2**(k - 1) ... | trial_gpt4o_1 | {
"original_instruction": "### Shell Sort Enhancement\n\nShell Sort is an improved insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, taking every `h`th element (where `h` is an integer variable constantly decreasing) yields a s... | 0.614803 | Data_Structure_11910 | C | [
"generate_sedgewick_gaps",
"enhanced_shell_sort"
] | 2 | [
[
"enhanced_shell_sort",
"generate_sedgewick_gaps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 06ff3ae91a833d9e3495e1cc8e8590d41e15db6d | 08c319273d5877a52859cd32e3d8fb88647de59d | |||
v1.0 | complete | Data_Structure | Data_Structure_12636_C | def compress_and_decompress(input: str) -> str:
"""
Compresses the input string using Run-Length Encoding (RLE) and then
decompresses it to validate correctness ensuring the decompressed string
matches the original input.
>>> compress_and_decompress("aaabbccccdaa") == "aaabbccccdaa"
>>> ... | def run_length_encode(input_string):
"""
Compresses a string using Run-Length Encoding (RLE).
"""
if not input_string:
return ""
encoded_string = []
count = 1
for i in range(1, len(input_string)):
if input_string[i] == input_string[i-1]:
count += 1
... | from solution import compress_and_decompress
def test_compress_and_decompress_empty_string():
assert compress_and_decompress("") == ""
def test_compress_and_decompress_single_character():
assert compress_and_decompress("a") == "a"
assert compress_and_decompress("z") == "z"
def test_compress_and_decompres... | [
{
"docstring": "Compresses a string using Run-Length Encoding (RLE).",
"function_declaration": "def run_length_encode(input_string):",
"function_name": "run_length_encode",
"parameter_list": "(input_string)"
},
{
"docstring": "Decompresses a string using Run-Length Encoding (RLE).",
"fun... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def compress(input: str) -> str:\n \"\"\"\n Compresses the input string using Run-Length Encoding (RLE).\n\n Args:\n input (str): The input string... | trial_gpt4o_1 | {
"original_instruction": "**Context**\n\nRun-Length Encoding (RLE) is used as a basic lossless data compression technique that compresses consecutive repeated characters by storing the character followed by the number of repeats. Consider you have a text that you'd like to compress and later decompress while ensurin... | 0.693374 | Data_Structure_12636 | C | [
"run_length_encode",
"run_length_decode",
"compress_and_decompress"
] | 3 | [
[
"compress_and_decompress",
"run_length_decode"
],
[
"compress_and_decompress",
"run_length_encode"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1459f74406e1e12ddfd3910da362722da045c1b7 | e5dc7673de6188a0e8a70a1342a3a1a17373a627 | |||
v1.0 | complete | Data_Structure | Data_Structure_10557_C | from typing import List
def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
""" Sort an integer array using the Radix Sort algorithm.
>>> radix_sort([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66, 75, 90, 170, 802]
>>> radix_sort([])
[]
>>> radix_sort([1])
[1]
>>> ... | from typing import List
def counting_sort_for_radix(arr: List[int], exp: int, base: int = 10) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * base
for i in range(n):
index = (arr[i] // exp) % base
count[index] += 1
for i in range(1, base):
count[i] +=... | from solution import radix_sort
def test_radix_sort_basic_cases():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort([1]) == [1]
assert radix_sort([1000]) == [1000]
def test_rad... | [
{
"docstring": null,
"function_declaration": "def counting_sort_for_radix(arr, exp, base=10):",
"function_name": "counting_sort_for_radix",
"parameter_list": "(arr, exp, base=10)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name... | [
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_for_radix(arr: List[int], exp: int, base: int = 10) -> List[int]:\n n = len(arr)\n output = [0] * n \n ... | trial_gpt4o_0 | {
"original_instruction": "### Radix Sort Implementation Challenge\n\nYou are given an integer array `arr` that needs to be sorted in non-decreasing order. Implement the Radix Sort algorithm to sort the array. \n\n#### Function Signature\n```python\ndef radix_sort(arr: List[int], simulation: bool = False) -> List[int... | 0.59426 | Data_Structure_10557 | C | [
"counting_sort_for_radix",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort_for_radix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 538afe2e1cb6be1071f74d6ee53571cf2b542764 | c7c0015ae4f7204e87672aca78bfb90586a5f5d7 | |||
v1.0 | complete | Data_Structure | Data_Structure_10801_C | from typing import Tuple, Dict, Any
def enhanced_distance(x: Tuple[float, ...], y: Tuple[float, ...]) -> float:
"""
Calculates the Euclidean distance between two vectors x and y.
>>> round(enhanced_distance((1.0, 2.0), (4.0, 6.0)), 2) == 5.0
>>> round(enhanced_distance((0.0, 0.0), (0.0, 0.0)), 2) == 0.... | from typing import Tuple, Dict, Any, Optional
import numpy as np
from scipy.spatial import KDTree
def enhanced_distance(x: Tuple[float, ...], y: Tuple[float, ...]) -> float:
"""
Calculates the Euclidean distance between two vectors x and y.
"""
return np.linalg.norm(np.array(x) - np.array(y))
def enha... | import pytest
from solution import enhanced_distance, enhanced_nearest_neighbor
def test_enhanced_distance():
assert pytest.approx(enhanced_distance((1.0, 2.0), (4.0, 6.0)), 0.01) == 5.0
assert pytest.approx(enhanced_distance((0.0, 0.0), (0.0, 0.0)), 0.01) == 0.0
assert pytest.approx(enhanced_distance((1.5... | [
{
"docstring": "Calculates the Euclidean distance between two vectors x and y.",
"function_declaration": "def enhanced_distance(x, y):",
"function_name": "enhanced_distance",
"parameter_list": "(x, y)"
},
{
"docstring": "Returns the class/value of the nearest neighbor for the input vector x ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Tuple, Dict, Any\nimport math\n\ndef enhanced_distance(x: Tuple[float, ...], y: Tuple[float, ...]) -> float:\n \"\"\"\n Returns the E... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement Enhanced Nearest Neighbor Algorithm\n\n#### Scenario\nYou are working on a machine learning project for classifying objects based on their features in a multidimensional space. The classification is performed using a Nearest Neighbor algorithm. Given new data points,... | 0.636272 | Data_Structure_10801 | C | [
"enhanced_distance",
"enhanced_nearest_neighbor"
] | 2 | [
[
"enhanced_nearest_neighbor",
"enhanced_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 660a241a8df8e41c921a96448a80f657022f3d55 | 8b9c56309cc48329e23fdcc543a378c4e1342297 | |||
v1.0 | complete | Data_Structure | Data_Structure_12022_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big: TreeNode, small: TreeNode) -> bool:
""" Determine if one binary tree is a subtree of another binary tree.
>>> big = TreeNode(1)
>>> big.left ... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_same_tree(s: TreeNode, t: TreeNode) -> bool:
if not s and not t:
return True
if not s or not t:
return False
if s.val != t.val:
ret... | import pytest
from solution import TreeNode, is_subtree
def test_is_subtree_exact_match():
big = TreeNode(1)
big.left = TreeNode(2)
big.right = TreeNode(3)
small = TreeNode(1)
small.left = TreeNode(2)
small.right = TreeNode(3)
assert is_subtree(big, small) == True
def test_is_sub... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_1 | {
"original_instruction": "### Scenario\nImagine you are working on a large-scale hierarchical data processing system, such as a file system or an organizational chart. Given the dynamic nature of such systems, you often need to verify if a particular structure is a subset of a larger structure.\n\n### Task\nWrite a ... | 0.5958 | Data_Structure_12022 | C | [
"is_same_tree",
"is_subtree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 118047509b8a3d9a069e2a1925b093d2f4298676 | 358abc599db1a0b4b094764948a5d24b0995d9ca | |||
v1.0 | complete | Data_Structure | Data_Structure_11586_C | from typing import List
def find_indices(numbers: List[int], target: int) -> List[int]:
""" Find the indices of two numbers that add up to the target.
This function uses three methods to find the indices:
1. Binary Search Method
2. Hash Table Method
3. Two Pointers Method
>>> find_ind... | from typing import List, Tuple
def find_indices_binary_search(numbers: List[int], target: int) -> List[int]:
import bisect
for i in range(len(numbers)):
complement = target - numbers[i]
idx = bisect.bisect_left(numbers, complement, i + 1)
if idx < len(numbers) and numbers[idx] == comple... | from solution import find_indices
def test_find_indices_two_pointers():
assert find_indices([2, 7, 11, 15], 9) == [1, 2]
assert find_indices([1, 2, 3, 4, 4], 8) == [4, 5]
assert find_indices([-3, 3, 4, 90], 0) == [1, 2]
assert find_indices([5, 25, 75], 100) == [2, 3]
assert find_indices([1, 2, 3, 4... | [
{
"docstring": null,
"function_declaration": "def find_indices_binary_search(numbers, target):",
"function_name": "find_indices_binary_search",
"parameter_list": "(numbers, target)"
},
{
"docstring": null,
"function_declaration": "def find_indices_hash_table(numbers, target):",
"func... | [
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 find_indices(numbers: List[int], target: int) -> List[int]:\n def find_indices_binary_search():\n def binary_search(l... | trial_gpt4o_4 | {
"original_instruction": "### Question: Two Sum with Multiple Methods\n\nYou are given a list of integers `numbers` sorted in ascending order, and a target integer `target`. Your task is to write a function `find_indices` that returns the list of indices of two numbers such that they add up to the `target`. There ar... | 0.605819 | Data_Structure_11586 | C | [
"find_indices_binary_search",
"find_indices_hash_table",
"find_indices_two_pointers",
"find_indices"
] | 4 | [
[
"find_indices",
"find_indices_two_pointers"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1c095cbe063aa1900dac845c2f7b8482eeee1801 | 64f16752664959d48c91b23e14681b28b0281bf2 | |||
v1.0 | complete | Data_Structure | Data_Structure_13362_C | def extended_euler_totient(n: int) -> Tuple[int, List[int]]:
"""Computes the value of Euler's Totient function ϕ(n) for a given integer n,
and returns a list of integers that are coprime with n.
Args:
n (int): A positive integer n >= 1.
Returns:
Tuple containing:
- An integer represen... | from typing import List, Tuple
def gcd(a: int, b: int) -> int:
"""
Compute the greatest common divisor of a and b using the Euclidean algorithm.
"""
while b:
a, b = b, a % b
return a
def extended_euler_totient(n: int) -> Tuple[int, List[int]]:
"""
Computes Euler's Totient function ... | from solution import extended_euler_totient
def test_extended_euler_totient_case_1():
"""Test case for n=1"""
assert extended_euler_totient(1) == (1, [1])
def test_extended_euler_totient_case_6():
"""Test case for n=6"""
assert extended_euler_totient(6) == (2, [1, 5])
def test_extended_euler_totient_... | [
{
"docstring": "Compute the greatest common divisor of a and b using the Euclidean algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes Euler's Totient function value for n and also provides the list \nof intege... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef extended_euler_totient(n: int):\n coprimes = []\n for i in range(1, n+1):\n ... | trial_gpt4o_2 | {
"original_instruction": "### Euler's Totient Function Implementation and Extension\n\nEuler's totient function, also known as the phi-function \\(ϕ(n)\\), counts the number of integers between 1 and \\(n\\) inclusive, which are coprime to \\(n\\) (Two numbers are coprime if their greatest common divisor (GCD) equal... | 0.533237 | Data_Structure_13362 | C | [
"gcd",
"extended_euler_totient"
] | 2 | [
[
"extended_euler_totient",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3f9b772d7b0778e0b4c1782cb5245fa5ef8d7d94 | afdcc4e7bab0b85abe7c2b185eb573d3fc4e937d | |||
v1.0 | complete | Data_Structure | Data_Structure_13221_C | def radix_sort(arr: List[int], simulation: bool=False) -> List[int]:
"""
You are tasked with implementing the radix sort algorithm that sorts a list of integers. The algorithm should process individual digits, starting from the least significant digit to the most significant digit, efficiently handling a varie... | def counting_sort(arr, exp):
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 - 1
while i >= 0:
index = (arr[i] // exp) % 10
output... | from solution import radix_sort
def test_empty_array():
assert radix_sort([]) == []
def test_single_element():
assert radix_sort([1]) == [1]
def test_already_sorted():
assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted():
assert radix_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, ... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort",
"parameter_list":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n for i in range(n):\n index = (arr[i] // exp) % 10\n ... | trial_gpt4o_0 | {
"original_instruction": "You are tasked with implementing the radix sort algorithm that sorts a list of integers. The algorithm should process individual digits, starting from the least significant digit to the most significant digit, efficiently handling a variety of input scenarios.\n\n### Requirements\n1. Implem... | 0.677528 | Data_Structure_13221 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 974b9ab31891ea8bbab2c4c4bb7f4feb9a4f1392 | a17ea3bd3f7a51a95ea449b018cf4ab58ce68fbb | |||
v1.0 | complete | Data_Structure | Data_Structure_13634_C | from typing import List, Dict
def enhanced_rabin_miller(numbers: List[int], k: int) -> Dict[int, bool]:
""" Enhance the Rabin-Miller primality test to handle a list of numbers and
small primes efficiently.
Args:
numbers (List[int]): A list of integers to be tested for primality.
k (int): The n... | from typing import List, Dict
import random
def _miller_rabin_test(n: int, k: int) -> bool:
"""Perform the Miller-Rabin primality test on number n with k iterations."""
if n <= 1:
return False
if n <= 3:
return True if n > 1 else False
if n % 2 == 0:
return False
# Find... | from solution import enhanced_rabin_miller
def test_small_primes():
numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
k = 5
result = enhanced_rabin_miller(numbers, k)
assert all(result[num] for num in numbers)
def test_small_non_primes():
numbers = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]
k = 5
r... | [
{
"docstring": "Perform the Miller-Rabin primality test on number n with k iterations.",
"function_declaration": "def _miller_rabin_test(n, k):",
"function_name": "_miller_rabin_test",
"parameter_list": "(n, k)"
},
{
"docstring": "Test a list of numbers for primality using an enhanced Rabin-... | [
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, Dict\n\ndef _is_prime(n: int, k: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return T... | trial_gpt4o_1 | {
"original_instruction": "### Rabin-Miller Primality Test Enhancement\n\n**Context**: You are working on a cryptography project that requires frequent and reliable primality testing for large numbers. To ensure high levels of accuracy and performance, you need to optimize and extend the Rabin-Miller primality test.\... | 0.632327 | Data_Structure_13634 | C | [
"_miller_rabin_test",
"enhanced_rabin_miller"
] | 2 | [
[
"enhanced_rabin_miller",
"_miller_rabin_test"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c97cb97d148ab9ee7c6ed46059ea2b53b0ea60f7 | d828a5609d96cbb0a262a9b9cfb805653543631a | |||
v1.0 | complete | Data_Structure | Data_Structure_10414_C | from typing import Tuple
def enhanced_gcd(a: int, b: int) -> int:
""" Calculate the GCD of two integers using the Euclidean Algorithm.
Handles negative inputs gracefully and returns the other number if either input is zero.
>>> enhanced_gcd(48, 18)
6
>>> enhanced_gcd(-48, 18)
6
>>> enhanc... | def enhanced_gcd(a, b):
"""
Calculate the GCD of two integers using the Euclidean Algorithm.
Return the other number if either input is zero.
"""
while b:
a, b = b, a % b
return abs(a)
def robust_lcm(a, b):
"""
Compute the LCM of two integers using the GCD function.
Return z... | from solution import enhanced_gcd, robust_lcm, bitwise_gcd
def test_enhanced_gcd():
assert enhanced_gcd(48, 18) == 6
assert enhanced_gcd(-48, 18) == 6
assert enhanced_gcd(0, 18) == 18
assert enhanced_gcd(18, 0) == 18
assert enhanced_gcd(0, 0) == 0
assert enhanced_gcd(7, 5) == 1
assert enhan... | [
{
"docstring": "Calculate the GCD of two integers using the Euclidean Algorithm.\nReturn the other number if either input is zero.",
"function_declaration": "def enhanced_gcd(a, b):",
"function_name": "enhanced_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Compute the LCM of two intege... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_gcd(a: int, b: int) -> int:\n \"\"\"\n Returns the greatest common divisor (GCD) of the integers a and b using the Euclidean Algorithm.\n ... | trial_gpt4o_1 | {
"original_instruction": "### Question: Advanced GCD and LCM Calculations\n\nIn this task, you'll work on optimizing and applying fundamental arithmetic algorithms, specifically the greatest common divisor (GCD) and the lowest common multiple (LCM).\n\n#### Task 1: Enhanced Euclidean GCD Function\nWrite a function `... | 0.641046 | Data_Structure_10414 | C | [
"enhanced_gcd",
"robust_lcm",
"bitwise_gcd"
] | 3 | [
[
"robust_lcm",
"enhanced_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 12b8b3398d76194f78b354a4884251b6727ced02 | 9bc672d8339d538b7b580471ef3752f5fdc921c5 | |||
v1.0 | complete | Data_Structure | Data_Structure_13609_C | def is_valid_roman(s: str) -> bool:
""" Validate if the given string is a valid Roman numeral.
>>> is_valid_roman("DCXXI") True
>>> is_valid_roman("MMXIV") True
>>> is_valid_roman("IIII") False
>>> is_valid_roman("IIV") False
>>> is_valid_roman("") True
>>> is_valid_roman("ABC") False
>>... | def is_valid_roman(s: str) -> bool:
"""
Validate if the given string is a valid Roman numeral.
"""
# Define valid Roman numeral patterns
valid_roman_regex = r"^(M{0,3})(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$"
# Use regex to match the string against valid patterns
import re
... | from solution import is_valid_roman, roman_to_int
def test_is_valid_roman():
assert is_valid_roman("DCXXI") == True
assert is_valid_roman("MMXIV") == True
assert is_valid_roman("IIII") == False
assert is_valid_roman("IIV") == False
assert is_valid_roman("") == True
assert is_valid_roman("ABC") ... | [
{
"docstring": "Validate if the given string is a valid Roman numeral.",
"function_declaration": "def is_valid_roman(s):",
"function_name": "is_valid_roman",
"parameter_list": "(s)"
},
{
"docstring": "Convert a Roman numeral string into an integer.",
"function_declaration": "def roman_to... | [
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 is_valid_roman(s: str) -> bool:\n \"\"\"\n Validate if the given string is a valid Roman numeral.\n \"\"\"\n # Define valid Roman numeral patt... | trial_gpt4o_0 | {
"original_instruction": "### Question: Implement and Validate a Roman Numeral to Integer Converter\n\n**Context**:\nYou are tasked with enhancing a legacy system that processes historical data in Roman numerals. Given the nature of this data, it is essential to handle both valid and invalid inputs gracefully. Your ... | 0.717517 | Data_Structure_13609 | C | [
"is_valid_roman",
"roman_to_int"
] | 2 | [
[
"roman_to_int",
"is_valid_roman"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9922dc60853aab62b7791789bb053748f097f94b | 6626bbbec12c97c0a8398fa7b14b0b017a0919b5 | |||
v1.0 | complete | Data_Structure | Data_Structure_11194_C | from typing import List
def ford_fulkerson(capacity: List[List[int]], source: int, sink: int) -> int:
""" Implement the Ford-Fulkerson algorithm to find the maximum flow from source to sink in a given capacity matrix.
>>> capacity = [
... [0, 16, 13, 0, 0, 0],
... [0, 0, 10, 12, 0, 0],
... ... | from collections import deque
# Ford-Fulkerson Algorithm using DFS
def dfs_find_path(capacity, residual_capacity, source, sink, parent):
visited = [False] * len(capacity)
stack = [source]
while stack:
node = stack.pop()
if node == sink:
return True
for next_node in ... | def test_ford_fulkerson():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert ford_fulkerson(capacity, source, sink) == 23
def test_edm... | [
{
"docstring": null,
"function_declaration": "def dfs_find_path(capacity, residual_capacity, source, sink, parent):",
"function_name": "dfs_find_path",
"parameter_list": "(capacity, residual_capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def ford_fulker... | [
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 collections import deque\n\n# Ford-Fulkerson Algorithm using DFS\ndef dfs_find_path(capacity, residual_capacity, source, sink, parent):\n visited = [F... | trial_gpt4o_0 | {
"original_instruction": "### Maximum Flow Problem\nYou're given a directed graph represented by a capacity matrix, a source node, and a sink node. Your task is to implement three different algorithms to find the maximum flow from the source to the sink node: Ford-Fulkerson (DFS-based), Edmonds-Karp (BFS-based), and... | 0.593318 | Data_Structure_11194 | C | [
"dfs_find_path",
"ford_fulkerson",
"bfs_find_path",
"edmonds_karp",
"bfs_level_graph",
"dfs_flow",
"dinic"
] | 7 | [
[
"dinic",
"bfs_level_graph"
],
[
"dinic",
"dfs_flow"
],
[
"edmonds_karp",
"ford_fulkerson"
],
[
"ford_fulkerson",
"dfs_find_path"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | d8bdbc2d513b147e9f3d9f43c7d082b3ce40538b | 14f62ecbbfb2cfd0cc7f08f9e9696a0c5c901588 | |||
v1.0 | complete | Data_Structure | Data_Structure_12243_C | def generate_key(k, seed=None):
""" Generate RSA keys (n, e, d).
- k (int): Number of bits for modulus n.
- seed (int, optional): Seed for random number generator.
Returns:
- (tuple): Containing three integers n, e, d.
"""
def encrypt(data, e, n):
""" Encrypt data using RSA encryption.
... | import random
from sympy import isprime, mod_inverse
def generate_prime(bits, seed=None):
if seed is not None:
random.seed(seed)
while True:
prime_candidate = random.getrandbits(bits)
if isprime(prime_candidate):
return prime_candidate
def generate_key(k, seed=None):
as... | from solution import generate_key, encrypt, decrypt
def test_rsa():
n, e, d = generate_key(16, seed=42)
data = 20
encrypted = encrypt(data, e, n)
decrypted = decrypt(encrypted, d, n)
assert decrypted == data
def test_large_numbers():
n, e, d = generate_key(512, seed=100)
dat... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bits, seed=None):",
"function_name": "generate_prime",
"parameter_list": "(bits, seed=None)"
},
{
"docstring": null,
"function_declaration": "def generate_key(k, seed=None):",
"function_name": "generate_key",
"param... | [
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, nextprime\nfrom math import gcd\n\ndef generate_key(k, seed=None):\n \"\"\"\n Generates RSA key pair (n, e, d)... | trial_gpt4o_1 | {
"original_instruction": "### RSA Encryption \nAs a part of a secure communication system, you are tasked to implement a function to generate RSA keys, encrypt, and decrypt messages. The RSA system relies on the difficulty of factoring a large integer formed by the product of two large prime numbers.\n\n#### Task\... | 0.740914 | Data_Structure_12243 | C | [
"generate_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 84fec57c3f520aa42d4902fd99cb45a5b47f5b4d | eece9a6c4e981a2574e8d1b6dfde268af36d743b | |||
v1.0 | complete | Data_Structure | Data_Structure_12385_C | from typing import List
def max_flow_with_balanced_node(capacity: List[List[int]], source: int, sink: int, balance_node: int) -> int:
""" Calculate the maximum flow in a flow network with an additional constraint that ensures
the outgoing flow from a specific balancing node is evenly distributed among its out... | from collections import deque
def bfs(capacity, source, sink, parent):
visited = [False] * len(capacity)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v in range(len(capacity)):
if not visited[v] and capacity[u][v] > 0:
... | def test_max_flow_basic():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
balance_node = 3
result = max_flow_with_balanced_node(capacit... | [
{
"docstring": null,
"function_declaration": "def bfs(capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def distribute_flows(balance_node, flow):",
"function_name": "distrib... | [
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 collections import deque\n\ndef bfs(capacity, source, sink, parent):\n n = len(capacity)\n visited = [False] * n\n queue = deque([source])\n ... | trial_gpt4o_4 | {
"original_instruction": "## Maximum Flow Problem with Modified Constraints\n\n### Background\nIn network optimization problems, finding the maximum possible flow from a source to a sink in a flow network is crucial. The three widely used algorithms for this are Ford-Fulkerson, Edmonds-Karp, and Dinic's algorithm. E... | 0.60216 | Data_Structure_12385 | C | [
"bfs",
"distribute_flows",
"edmonds_karp",
"max_flow_with_balanced_node"
] | 4 | [
[
"edmonds_karp",
"bfs"
],
[
"edmonds_karp",
"distribute_flows"
],
[
"max_flow_with_balanced_node",
"edmonds_karp"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | e26139eb624a013e79559266bd755bbb6130d669 | 33979d1e740aa3db2560fd120c5decb40481835a | |||
v1.0 | complete | Data_Structure | Data_Structure_13488_C | import random
def miller_rabin_prime(k, seed=None):
""" Generate a k-bit prime number using the Miller-Rabin primality test.
Args:
k (int): Number of bits in the desired prime number.
seed (optional, int): Seed for the random number generator for reproducibility.
Returns:
int: A k-bit prime nu... | import random
def miller_rabin_test(n, d):
a = random.randint(2, n - 2)
x = pow(a, d, n)
if x == 1 or x == n - 1:
return True
while d != n - 1:
x = (x * x) % n
d *= 2
if x == 1:
return False
if x == n - 1:
return True
return... | from solution import generate_key, encrypt, decrypt
import pytest
def test_prime_generation():
prime = miller_rabin_prime(128, seed=42)
assert is_prime(prime)
prime2 = miller_rabin_prime(128, seed=42)
assert prime == prime2 # Same seed must generate the same prime
def test_key_generation():
n, e,... | [
{
"docstring": null,
"function_declaration": "def miller_rabin_test(n, d):",
"function_name": "miller_rabin_test",
"parameter_list": "(n, d)"
},
{
"docstring": null,
"function_declaration": "def is_prime(n, k=5):",
"function_name": "is_prime",
"parameter_list": "(n, k=5)"
},
... | [
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": "import random\n\ndef miller_rabin_prime(k, seed=None):\n def is_probable_prime(n, rounds=40):\n # Check if n is a probable prime using Miller-Rabin ... | trial_gpt4o_7 | {
"original_instruction": "### RSA Encryption/Decryption Enhancement Task\n\nYou are tasked with improving the key generation part of the RSA encryption algorithm and implementing an optimized function to generate large prime numbers using the Miller-Rabin primality test. Your goal is to enhance the prime number gene... | 0.579533 | Data_Structure_13488 | C | [
"miller_rabin_test",
"is_prime",
"generate_prime_candidate",
"miller_rabin_prime",
"gcd",
"modinv",
"generate_key",
"encrypt",
"decrypt"
] | 9 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"miller_rabin_prime"
],
[
"generate_key",
"modinv"
],
[
"is_prime",
"miller_rabin_test"
],
[
"miller_rabin_prime",
"generate_prime_candidate"
],
[
"miller_rabin_prime",
"is_prime"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | f2445274fb2352420098ae2bba739baa761fb59a | 49f4132a114f9355ff4894e8663e50bd6cd19ee5 | |||
v1.0 | complete | Data_Structure | Data_Structure_14506_C | import math
def gcd(a, b):
"""
Helper function to calculate the greatest common divisor of a and b.
"""
while b:
a, b = b, a % b
return a
def find_order(a: int, n: int) -> int:
"""
Returns the order of a modulo n, or -1 if no such order exists.
The order of a modulo n is d... | import math
def gcd(a, b):
"""
Helper function to calculate the greatest common divisor of a and b.
"""
while b:
a, b = b, a % b
return a
def find_order(a: int, n: int) -> int:
"""
Returns the order of a modulo n, or -1 if no such order exists.
"""
if a <= 0 or n <= 0:
... | from solution import find_order
def test_find_order_basic_cases():
assert find_order(2, 3) == 2
assert find_order(3, 7) == 6
assert find_order(2, 5) == 4
def test_find_order_non_coprime():
assert find_order(10, 15) == -1
assert find_order(6, 14) == -1
def test_find_order_large_numbers():
asse... | [
{
"docstring": "Helper function to calculate the greatest common divisor of a and b.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the order of a modulo n, or -1 if no such order exists.",
"function_declaration":... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import gcd\n\ndef find_order(a: int, n: int) -> int:\n \"\"\"\n Returns the order of 'a' modulo 'n', which is the smallest positive integer 'k... | trial_gpt4o_8 | {
"original_instruction": "You are working as a software engineer in a company specializing in cryptographic solutions. One of your tasks involves working with modular arithmetic, specifically finding the order of numbers modulo `n`.\n\nYour goal is to implement a function `find_order(a, n)` that returns the order of... | 0.759401 | Data_Structure_14506 | C | [
"gcd",
"find_order"
] | 2 | [
[
"find_order",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c869d97ee31533230a8bec0ce86539aa5dda38c1 | 5bc87e8615f0461de0ac5301abfa3e3896c4896d | |||
v1.0 | complete | Data_Structure | Data_Structure_15286_C | from typing import List
def optimized_quick_sort(arr: List[int]) -> List[int]:
"""
This function sorts an array using the optimized quick sort algorithm
with a hybrid approach.
Args:
arr (List[int]): Unsorted list of integers.
Returns:
List[int]: Sorted list of integers.
... | 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 arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def partition(arr: List[int], low:... | import pytest
from solution import optimized_quick_sort
def test_sorted_array():
arr = [1, 2, 3, 4, 5]
assert optimized_quick_sort(arr) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
arr = [5, 4, 3, 2, 1]
assert optimized_quick_sort(arr) == [1, 2, 3, 4, 5]
def test_duplicate_elements():
arr ... | [
{
"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... | [
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 for i in range(left + 1, right + 1):\n key = arr[i]\... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with implementing a robust quick sort algorithm. This implementation must handle potential pitfalls of a basic quick-sort, such as poor pivot selection. Additionally, you are required to enhance the basic quick sort to better manage worst-case scenarios.\n\n### Function Speci... | 0.667884 | Data_Structure_15286 | C | [
"insertion_sort",
"partition",
"quick_sort",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"quick_sort"
],
[
"quick_sort",
"insertion_sort"
],
[
"quick_sort",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 8be04293e78272de34c8645634bbcea31ba4aa85 | ebaf277542bae1dc21efdceb3f689c98424b37e1 | |||
v1.0 | complete | Data_Structure | Data_Structure_13824_C | def multiply(matA: list, matB: list) -> list:
n = len(matA)
matC = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
matC[i][j] += matA[i][k] * matB[k][j]
return matC
def identity(n: int) -> list:
I = [[0... | def multiply(matA: list, matB: list) -> list:
n = len(matA)
matC = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
matC[i][j] += matA[i][k] * matB[k][j]
return matC
def identity(n: int) -> list:
I = [[0... | from solution import matrix_power
def test_matrix_power_basic():
matrix = [
[1, 2],
[3, 4]
]
power = 2
expected = [
[7, 10],
[15, 22]
]
assert matrix_power(matrix, power) == expected
def test_matrix_power_zero():
matrix = [
[1, 2],
[3, 4]
... | [
{
"docstring": null,
"function_declaration": "def multiply(matA, matB):",
"function_name": "multiply",
"parameter_list": "(matA, matB)"
},
{
"docstring": null,
"function_declaration": "def identity(n):",
"function_name": "identity",
"parameter_list": "(n)"
},
{
"docstring... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply(matA: list, matB: list) -> list:\n n = len(matA)\n matC = [[0 for _ in range(n)] for _ in range(n)]\n \n for i in range(n):\n ... | trial_gpt4o_2 | {
"original_instruction": "### Matrix Exponentiation Challenge\n\nYou are given a `d x d` square matrix (a list of lists in Python) and a non-negative integer `k`. Your task is to compute the `k`th power of the given matrix using the matrix exponentiation technique provided above.\n\n#### Functional Requirements\n\n1... | 0.539364 | Data_Structure_13824 | C | [
"multiply",
"identity",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity"
],
[
"matrix_power",
"multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1155b786e6f1eb8d77723f4cd202de57e9e7e397 | f900031d68b9c27c3c65ef0652fe760f7864f197 | |||
v1.0 | complete | Data_Structure | Data_Structure_14817_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Function to perform merge sort on a list of integers.
>>> merge_sort([38, 27, 43, 3, 9, 82, 10])
[3, 9, 10, 27, 38, 43, 82]
>>> merge_sort([])
[]
>>> merge_sort([1])
[1]
>>> merge_sort([1, 2, 3,... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Function to perform merge sort on a list of integers.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_ha... | from solution import merge_sort
def test_merge_sort_basic():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_already_sorted():
... | [
{
"docstring": "Function to perform merge sort on a list of integers.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Helper function to merge two sorted lists.",
"function_declaration": "def merge(left, right)... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n def merge(left: List[int], right: Li... | trial_gpt4o_2 | {
"original_instruction": "**Problem Description**:\nSuppose you are in charge of designing a library that deals with data processing. One of the key functionalities is to sort a list of integers. To achieve this, you will implement a standard sorting algorithm.\n\nYour task is to implement the `merge_sort` function ... | 0.603766 | Data_Structure_14817 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e57a88779ef9bc3c0861fe5f67eec78274be90f3 | 3f63ced78b9354e3f96a882f0619c3453045df2e | |||
v1.0 | complete | Data_Structure | Data_Structure_14129_C | def is_prime(n):
"""
Check if a number n is a prime
"""
pass
def find_primitive_root(p):
"""
Find a primitive root of the prime number p.
"""
pass
def diffie_hellman_key_exchange(a, p):
"""
Perform Diffie-Hellman Key Exchange simulation between two parties
"""
pass
def... | import random
def is_prime(n):
"""
Check if a number n is a prime
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i +=... | from solution import diffie_hellman_key_exchange, is_prime, find_primitive_root
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(29) == True
assert is_prime(100) == False
def test_find_primitive_root():
assert find_primitive... | [
{
"docstring": "Check if a number n is a prime",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find a primitive root of the prime number p.",
"function_declaration": "def find_primitive_root(p):",
"function_name": ... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(n):\n \"\"\"\n Check if a number n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n re... | trial_gpt4o_2 | {
"original_instruction": "#### Context:\nIn cryptographic systems, ensuring secure communication channels is paramount. One common approach is the Diffie-Hellman Key Exchange, which allows two parties to establish a shared secret over a non-secure channel. Your task is to write an implementation that simulates the f... | 0.559516 | Data_Structure_14129 | C | [
"is_prime",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 3 | [
[
"diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"diffie_hellman_key_exchange",
"is_prime"
],
[
"find_primitive_root",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 9bf7f1953cbb6ba4cc78232c4d028c3bce6407ac | a2157382dcfc66cf0a17d78aac2651b6764a197a | |||
v1.0 | complete | Data_Structure | Data_Structure_15943_C | import random
def constrained_bogo_sort(arr, max_iterations):
"""
Sorts the array using Bogo Sort method.
Parameters:
arr (list[int]): The list of integers to sort.
max_iterations (int): The maximum number of shuffles allowed.
Returns:
list[int] or None: The sorted list if sorted ... | import random
def is_sorted(arr):
""" Helper function to check if the array is sorted """
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def constrained_bogo_sort(arr, max_iterations):
"""
Sorts the array using Bogo Sort method.
Parameters:
arr (list[int]): The list of integers... | from solution import constrained_bogo_sort
def test_sorted_case():
assert constrained_bogo_sort([1, 2, 3], 1000) == [1, 2, 3]
def test_single_element():
assert constrained_bogo_sort([1], 10) == [1]
def test_empty_list():
assert constrained_bogo_sort([], 10) == []
def test_reversed_list():
result = c... | [
{
"docstring": "Helper function to check if the array is sorted ",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the array using Bogo Sort method.\n\nParameters:\narr (list[int]): The list of integers to sort.\... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Checks if the array is sorted in non-decreasing order.\n \"\"\"\n return all(arr[i] <= arr[i+1] fo... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nBogo Sort is known for its simplicity and serves as a fun example in theoretical computer science. However, due to its inefficiency, you'll rarely, if ever, use it in practical applications. Nevertheless, it provides good practice for understanding sorting algorithms and proba... | 0.651845 | Data_Structure_15943 | C | [
"is_sorted",
"constrained_bogo_sort"
] | 2 | [
[
"constrained_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 23c5202dff9813fc272cc90419dc1b75def663c5 | 96f88e9f69637a880f77cb99ee1706963d285629 | |||
v1.0 | complete | Data_Structure | Data_Structure_14596_C | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if the array is sorted in ascending order.
:param arr: List of integers
:return: True if sorted, False otherwise
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
... | import random
def is_sorted(arr):
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort_bracket(participants_list):
"""
Sorts the list using the Bogo Sort algorithm.
:param participants_list: List of integers representing the skill ra... | from solution import bogo_sort_bracket
def test_bogo_sort_with_multiple_elements():
assert bogo_sort_bracket([4, 1, 3, 2]) == [1, 2, 3, 4]
assert bogo_sort_bracket([3, 2, 1]) == [1, 2, 3]
assert bogo_sort_bracket([10, 9, 8, 7, 6]) == [6, 7, 8, 9, 10]
def test_bogo_sort_with_single_element():
assert bo... | [
{
"docstring": null,
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the list using the Bogo Sort algorithm.\n\n:param participants_list: List of integers representing the skill ratings\n:return: Sorted list of i... | [
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\n\ndef bogo_sort_bracket(participants_list):\n def is_sorted(lst):\n return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))\n\n... | trial_gpt4o_1 | {
"original_instruction": "### Question\n\n**Bogo Sort Bracket Organizer**\n\nYou are the coordinator of a sports event. The order of the participants in a knockout stage bracket is crucial. Luckily, you have heard of a method called Bogo Sort for organizing participants, just for fun!\n\nWrite a function, `bogo_sort... | 0.639526 | Data_Structure_14596 | C | [
"is_sorted",
"bogo_sort_bracket"
] | 2 | [
[
"bogo_sort_bracket",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b244333325e980984664c647e08f8805685c1e06 | 932706889427c4e565b770deab87d1b1692b0371 | |||
v1.0 | complete | Data_Structure | Data_Structure_15542_C | from typing import List
def optimized_insertion_sort(arr: List[int], simulation: bool = False) -> List[int]:
"""
Sorts a list of integers using the insertion sort algorithm with enhancements for
early exit and binary search. Prints the state of the list after each iteration
if simulation is True.
... | from typing import List
def binary_search_insert(arr: List[int], val: int, start: int, end: int) -> int:
"""
Binary search helper to find the correct insert position for val within arr[start:end]
"""
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
start = mid ... | from solution import optimized_insertion_sort
def test_sorted_list():
arr = [1, 2, 3, 4, 5]
assert optimized_insertion_sort(arr) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list():
arr = [5, 4, 3, 2, 1]
assert optimized_insertion_sort(arr) == [1, 2, 3, 4, 5]
def test_unsorted_list():
arr = [4, 3, ... | [
{
"docstring": "Binary search helper to find the correct insert position for val within arr[start:end]",
"function_declaration": "def binary_search_insert(arr, val, start, end):",
"function_name": "binary_search_insert",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "Sorts the... | [
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 binary_search(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Helper function to perform binary search... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nYou are assisting in improving the performance of a startup's inventory management system. The current system works well with just a few hundred items but shows considerable lag as more items are added. You are asked to implement a function that sorts the list of items using t... | 0.622181 | Data_Structure_15542 | C | [
"binary_search_insert",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"binary_search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5649cc73e2fc95a8844e62576c786af1851e8c9b | ca4cb100fb0e75ea1224de47dc934817617f3fe3 | |||
v1.0 | complete | Data_Structure | Data_Structure_14102_C | from typing import Tuple
def generate_key(k: int) -> Tuple[int, int, int]:
""" Generate RSA keys.
Args:
k (int): Number of bits for the modulus n.
Returns:
Tuple[int, int, int]: A tuple (n, e, d) where n is the modulus, e is the encryption exponent, and d is the decryption exponent.
"... | import random
from sympy import isprime, randprime
def generate_large_prime(bits):
while True:
prime_candidate = random.getrandbits(bits)
if isprime(prime_candidate):
return prime_candidate
def gcd_extended(a, b):
if a == 0:
return (b, 0, 1)
gcd, x1, y1 = gcd_extended(b... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert e == 65537
def test_encrypt_decrypt():
n, e, d = generate_key(16)
data = 42
encrypted = encrypt(d... | [
{
"docstring": null,
"function_declaration": "def generate_large_prime(bits):",
"function_name": "generate_large_prime",
"parameter_list": "(bits)"
},
{
"docstring": null,
"function_declaration": "def gcd_extended(a, b):",
"function_name": "gcd_extended",
"parameter_list": "(a, b... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\n\ndef generate_prime(bits):\n while True:\n p = random.getrandbits(bits)\n if isprim... | trial_gpt4o_2 | {
"original_instruction": "### RSA Key Generation and Encryption\nAs a foundational exercise in cryptography, you are tasked with implementing a robust version of the RSA key generation, encryption, and decryption in Python.\n\n### Objective\nWrite a function `generate_key(k)` to generate RSA keys, and two functions ... | 0.729224 | Data_Structure_14102 | C | [
"generate_large_prime",
"gcd_extended",
"lcm",
"generate_key",
"encrypt",
"decrypt"
] | 6 | [
[
"generate_key",
"gcd_extended"
],
[
"generate_key",
"generate_large_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 5f4e7b0ac277811446f2848909914784b70578c0 | 76525a5409d4e132b29d7a93b2b84ba0ab84500b | |||
v1.0 | complete | Data_Structure | Data_Structure_15283_C | from typing import List, Dict
def multi_pattern_kmp(text: str, patterns: List[str]) -> Dict[str, List[int]]:
"""Implement a Modified KMP Algorithm for Multi-Pattern Matching.
Args:
text (str): The text in which to search.
patterns (List[str]): The list of patterns to search for within the text.
... | from typing import List, Dict
def compute_lps(pattern: str) -> List[int]:
"""Compute the Longest Prefix Suffix (LPS) array for the KMP algorithm."""
lps = [0] * len(pattern)
length = 0
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
lps[i]... | def test_compute_lps():
assert compute_lps("ababc") == [0, 0, 1, 2, 0]
assert compute_lps("aaaa") == [0, 1, 2, 3]
assert compute_lps("abcd") == [0, 0, 0, 0]
assert compute_lps("aabaaac") == [0, 1, 0, 1, 2, 2, 0]
def test_kmp_search():
assert kmp_search("testtexttext", "test") == [0]
assert kmp_... | [
{
"docstring": "Compute the Longest Prefix Suffix (LPS) array for the KMP algorithm.",
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": "Perform KMP search for a single pattern in the text.",
"function_de... | [
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, Dict\n\ndef kmp_pattern_table(pattern: str) -> List[int]:\n \"\"\"\n Computes the partial match table (also known as \"failure ... | trial_gpt4o_2 | {
"original_instruction": "**Problem Statement: Implement a Modified KMP Algorithm for Multi-Pattern Matching**\n\nYou are tasked with modifying the Knuth-Morris-Pratt (KMP) algorithm to handle multiple patterns within a given text. This requires preprocessing a list of patterns and then searching for any of these pa... | 0.611647 | Data_Structure_15283 | C | [
"compute_lps",
"kmp_search",
"multi_pattern_kmp"
] | 3 | [
[
"kmp_search",
"compute_lps"
],
[
"multi_pattern_kmp",
"kmp_search"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 2078e3efab211b58fd46133278361fe08702aba9 | 9342d3964eaf5e828b94e6af1e6b405bd8d23594 | |||
v1.0 | complete | Data_Structure | Data_Structure_16015_C | def validate_roman(s: str) -> bool:
""" Validates if the provided string is a valid Roman numeral.
>>> validate_roman("MCMXCIV") True
>>> validate_roman("IIII") False
"""
pass
def roman_to_int(s: str) -> int:
""" Converts a roman numeral string to its integer value, returns -1 if input is inval... | def validate_roman(s: str) -> bool:
valid_chars = {'I', 'V', 'X', 'L', 'C', 'D', 'M'}
if not s:
return False
if any(char not in valid_chars for char in s):
return False
invalid_repeats = ["IIII", "VV", "XXXX", "LL", "CCCC", "DD", "MMMM"]
for repeat in invalid_repeats:
... | from solution import validate_roman, roman_to_int
def test_validate_roman_valid():
assert validate_roman("MCMXCIV") == True
assert validate_roman("III") == True
assert validate_roman("MMXXII") == True
def test_validate_roman_invalid():
assert validate_roman("IIII") == False
assert validate_roman("... | [
{
"docstring": null,
"function_declaration": "def validate_roman(s):",
"function_name": "validate_roman",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def roman_to_int(s):",
"function_name": "roman_to_int",
"parameter_list": "(s)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def validate_roman(s: str) -> bool:\n \"\"\"\n Validates a Roman numeral string.\n Returns True if the string is a valid Roman numeral, otherwise Fal... | trial_gpt4o_2 | {
"original_instruction": "### Roman Numeral Validation and Conversion\n\nYou have been given a function `roman_to_int` that converts a Roman numeral string into its corresponding integer value. This function assumes that the given Roman numeral string is always valid and within the range from 1 to 3999.\n\nHowever, ... | 0.709185 | Data_Structure_16015 | C | [
"validate_roman",
"roman_to_int"
] | 2 | [
[
"roman_to_int",
"validate_roman"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3a7c38077d6647d24c8c9edb4cf0388ab4dc18dc | 59c76c406d00fbf3fb8fa21cf02c29e3473e13aa | |||
v1.0 | complete | Data_Structure | Data_Structure_15352_C | class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, val):
"""Insert a value into the BST.
Args:
- root: The root of the BST (or None if tree is empty).
- val: The value to be inserted.
Returns:
- The new root of... | class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, val):
if root is None:
return TreeNode(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
... | from solution import TreeNode, insert, search, deleteNode
def tree_to_list(root):
result = []
def inorder(node):
if node:
inorder(node.left)
result.append(node.val)
inorder(node.right)
inorder(root)
return result
def test_insert():
root = None
root =... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef in... | trial_gpt4o_2 | {
"original_instruction": "**Implement BST Operations**\n\nYou are required to implement a Binary Search Tree (BST) with the following functionalities:\n1. **Insert a node**\n2. **Search for a node**\n3. **Delete a node**\n\nYour implementation should consist of the following functions:\n\n1. `insert(root, val)`: Ins... | 0.592172 | Data_Structure_15352 | C | [
"insert",
"search",
"minValueNode",
"deleteNode"
] | 4 | [
[
"deleteNode",
"minValueNode"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | e4ce0e7f31c5c2196badc6fa81212548caf119f3 | 18222181834305f4cb50ef3305375abb9db7ebb8 | |||
v1.0 | complete | Data_Structure | Data_Structure_14501_C | import time
from typing import List
def optimized_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers using an efficient sorting algorithm.
Ensures better time complexity than O(n^2).
"""
# Efficient sorting algorithm implementation goes here
pass
def stoogesort(arr: List[int], l... | import time
from typing import List
def optimized_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers using Quick Sort algorithm.
"""
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
... | from solution import optimized_sort, stoogesort
def test_optimized_sort_empty_array():
assert optimized_sort([]) == []
def test_optimized_sort_single_element():
assert optimized_sort([1]) == [1]
def test_optimized_sort_multiple_same_elements():
assert optimized_sort([2, 2, 2, 2]) == [2, 2, 2, 2]
def tes... | [
{
"docstring": "Sorts an array of integers using Quick Sort algorithm.",
"function_declaration": "def optimized_sort(arr):",
"function_name": "optimized_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def stoogesort(arr, l, h):",
"function_name": "st... | [
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 optimized_sort(arr):\n \"\"\"\n Implements the QuickSort algorithm to sort the list.\n \"\"\"\n def quicksort(arr, low, high):\n if low... | trial_gpt4o_2 | {
"original_instruction": "Stooge Sort Enhancement\n\n**Context:**\nStooge Sort is a recursive sorting algorithm known for its impractical efficiency. It serves as an educational example to understand the mechanics of recursive sorting approaches. In this exercise, you will implement a more optimized sorting algorith... | 0.553785 | Data_Structure_14501 | C | [
"optimized_sort",
"stoogesort",
"compare_performance"
] | 3 | [
[
"compare_performance",
"optimized_sort"
],
[
"compare_performance",
"stoogesort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 58d9a1538324c3ae35b8dc8cc798bad5ce7b68a3 | de950721e76706116f943539c1ea8518d0a42f09 | |||
v1.0 | complete | Data_Structure | Data_Structure_16523_C | def is_in_cycle(graph, traversal_states, vertex):
"""
Helper function to check if the current vertex is part of a cycle.
Uses DFS and vertex states to track the traversal.
"""
pass
def contains_cycle(graph):
"""
Checks if the directed graph contains any cycles.
>>> contains_cycle({'A': ... | WHITE = 0 # Vertex has not been visited yet
GRAY = 1 # Vertex is in the current DFS traversal stack
BLACK = 2 # Vertex and its descendants have been fully explored
def is_in_cycle(graph, traversal_states, vertex):
"""
Helper function to check if the current vertex is part of a cycle.
Uses DFS and verte... | from solution import contains_cycle
def test_contains_cycle_with_simple_cycle():
graph = {
'A': ['B'],
'B': ['C'],
'C': ['A']
}
assert contains_cycle(graph) == True # This graph contains a cycle.
def test_contains_cycle_no_edges():
graph = {
'A': [],
'B': [],
... | [
{
"docstring": "Helper function to check if the current vertex is part of a cycle.\nUses DFS and vertex states to track the traversal.",
"function_declaration": "def is_in_cycle(graph, traversal_states, vertex):",
"function_name": "is_in_cycle",
"parameter_list": "(graph, traversal_states, vertex)"
... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "WHITE = 0 # Vertex has not been visited yet\nGRAY = 1 # Vertex is in the current DFS traversal stack\nBLACK = 2 # Vertex and its descendants have been ful... | trial_gpt4o_0 | {
"original_instruction": "#### Scenario\nA project planner uses a directed graph to represent tasks in a project and their dependencies. Each task is a node, and a directed edge from task A to task B means that task A must be completed before task B can start. The planner needs to check whether the graph of tasks co... | 0.57903 | Data_Structure_16523 | C | [
"is_in_cycle",
"contains_cycle"
] | 2 | [
[
"contains_cycle",
"is_in_cycle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 995120b8074a053bbc559287acb3e7dcb3ba07b9 | 10586293993c98a76a5a5de7cbde8e820c4d3e4e | |||
v1.0 | complete | Data_Structure | Data_Structure_16857_C | def iterative_merge_sort(arr: List[int]) -> List[int]:
""" Use an iterative merge sort algorithm to sort a list of integers.
>>> iterative_merge_sort([38, 27, 43, 3, 9, 82, 10])
[3, 9, 10, 27, 38, 43, 82]
>>> iterative_merge_sort([1, 3, 2, 5, 4, 6])
[1, 2, 3, 4, 5, 6]
>>> iterative_merge_so... | def iterative_merge_sort(arr):
if not arr: # Edge case: empty array
return arr
n = len(arr)
width = 1
while width < n:
for i in range(0, n, 2 * width):
left = arr[i:i + width]
right = arr[i + width:i + 2 * width]
arr[i:i + 2 * width] = merge(left, ri... | def test_iterative_merge_sort():
assert iterative_merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
assert iterative_merge_sort([1, 3, 2, 5, 4, 6]) == [1, 2, 3, 4, 5, 6]
assert iterative_merge_sort([5]) == [5]
assert iterative_merge_sort([]) == []
assert iterative_merge_sort([9, -... | [
{
"docstring": null,
"function_declaration": "def iterative_merge_sort(arr):",
"function_name": "iterative_merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef iterative_merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n width = 1\n n = len(arr... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with implementing a variation of the Merge Sort algorithm. This variation, called \"Iterative Merge Sort,\" avoids recursion by using an iterative approach to divide the array and then merge the parts. Your task is to write a function that sorts an input list of integers usin... | 0.609844 | Data_Structure_16857 | C | [
"iterative_merge_sort",
"merge"
] | 2 | [
[
"iterative_merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 1fd8ed7209b15b4f9f0127ae7e413aa80b983be3 | 9373d08e36521ffc250aefb852ad12a243816a9d | |||
v1.0 | complete | Data_Structure | Data_Structure_16780_C | def invert_matrix(matrix):
""" Inverts a given n x n matrix.
>>> invert_matrix([[4, 7], [2, 6]])
[[0.6, -0.7], [-0.2, 0.4]]
>>> invert_matrix([[1, 2, 3], [0, 1, 4], [5, 6, 0]])
[[-24, 18, 5], [20, -15, -4], [-5, 4, 1]]
>>> invert_matrix([[1, 2], [2, 4]])
[[None]]
>>> invert_matrix([[1, 0... | def get_determinant(matrix):
"""
Calculates the determinant of a (n x n) matrix.
"""
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]
determinant = 0
for c in range(n):
determinant += ((-1... | from solution import invert_matrix
def approx_equal(matrix1, matrix2, tol=1e-9):
for row1, row2 in zip(matrix1, matrix2):
for el1, el2 in zip(row1, row2):
if abs(el1 - el2) > tol:
return False
return True
def test_invert_matrix_2x2():
matrix = [
[4, 7],
... | [
{
"docstring": "Calculates the determinant of a (n x n) matrix.",
"function_declaration": "def get_determinant(matrix):",
"function_name": "get_determinant",
"parameter_list": "(matrix)"
},
{
"docstring": "Returns the minor of the matrix after removing the ith row and jth column.",
"func... | [
0,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_determinant(matrix):\n \"\"\"\n Computes the determinant of a 2x2 or 3x3 matrix.\n \"\"\"\n n = len(matrix)\n \n if n == 2:\n ... | trial_gpt4o_3 | {
"original_instruction": "### Matrix Inversion Function\n\n#### Scenario\nYou are tasked with building on an existing module that inverts \\(n \\times n\\) matrices. This function is crucial in numerical linear algebra for solving systems of linear equations, among other applications. You'll implement a matrix inver... | 0.574966 | Data_Structure_16780 | C | [
"get_determinant",
"get_minor",
"transpose_and_multiply",
"invert_matrix"
] | 4 | [
[
"get_determinant",
"get_minor"
],
[
"invert_matrix",
"get_determinant"
],
[
"invert_matrix",
"get_minor"
],
[
"invert_matrix",
"transpose_and_multiply"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 7fc76f9dd278d1258df230b59ef9d9a2d86ffc48 | 9caa8c4994556a2dfdd7911be7af1ce502e2a827 | |||
v1.0 | complete | Data_Structure | Data_Structure_16216_C | import random
def is_sorted(arr: list) -> bool:
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr: list, simulation: bool = False) -> list:
"""
Function that implemen... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr, simulation=False):
"""
Function that implements Bogo Sort.
Parameters:
... | from solution import bogo_sort
def test_bogo_sort_empty():
assert bogo_sort([]) == []
def test_bogo_sort_single_element():
assert bogo_sort([1]) == [1]
def test_bogo_sort_already_sorted():
assert bogo_sort([1, 2, 3]) == [1, 2, 3]
def test_bogo_sort_reverse_sorted():
result = bogo_sort([3, 2, 1])
... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Function that implements Bogo Sort.\n\nParameters:\narr (list): List of integers to be sorted.\nsimulat... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Checks if the given list is sorted in ascending order.\n \"\"\"\n for i in range(len(arr)-1):\n ... | trial_gpt4o_1 | {
"original_instruction": "Implement and Analyze Bogo Sort\n\n#### Background:\nBogo Sort (also known as Monkey Sort) is a highly inefficient sorting algorithm that works by randomly shuffling an array until it is sorted. While impractical, it serves as a theoretical exploration of algorithm performance and randomnes... | 0.620696 | Data_Structure_16216 | C | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a8cef8c40f8fb2a7acda7eebadae4d1bf70362d7 | bfb965ec1303d0780e76c58d9b73419e7b67481f | |||
v1.0 | complete | Data_Structure | Data_Structure_16337_C | def bucket_sort(arr):
"""
Sorts an array of floating-point numbers using the Bucket Sort algorithm with Selection Sort as the secondary sorting mechanism.
:param arr: List[float] - A list of floating-point numbers to be sorted.
:return: List[float] - The sorted list of floating-point numbers.
>... | def selection_sort(arr):
"""
Performs selection sort on the given list.
"""
n = len(arr)
for i in range(n - 1):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
def b... | from solution import bucket_sort
def test_bucket_sort_example_case():
arr = [0.23, 0.45, 0.12, 0.68, 0.34]
expected = [0.12, 0.23, 0.34, 0.45, 0.68]
assert bucket_sort(arr) == expected
def test_bucket_sort_already_sorted():
arr = [0.1, 0.2, 0.3, 0.4, 0.5]
expected = [0.1, 0.2, 0.3, 0.4, 0.5]
a... | [
{
"docstring": "Performs selection sort on the given list.",
"function_declaration": "def selection_sort(arr):",
"function_name": "selection_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts an array of floating-point numbers using the Bucket Sort algorithm with Selection Sort as the... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bucket_sort(arr):\n \"\"\"\n Sorts an array of floating-point numbers using the Bucket Sort algorithm with Selection Sort as the secondary sorting m... | trial_gpt4o_2 | {
"original_instruction": "#### Problem Statement\n\nYou have been tasked with implementing a custom sorting algorithm that efficiently sorts an array of floating-point numbers. The sorting technique you're implementing is a variation of the Bucket Sort, using a specified secondary sorting algorithm within each bucke... | 0.604135 | Data_Structure_16337 | C | [
"selection_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"selection_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 07b01a9fd9fb9b73304437ce6fc9a570f1d9f691 | 1cf0704e13b2bedfd46ada25595aa5de888d4714 | |||
v1.0 | complete | Data_Structure | Data_Structure_15781_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def serialize(root):
"""Encodes a tree to a single string."""
if not root:
return "None"
return f"{root.val},{serialize(root.left)},{serialize(root.right)... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def serialize(root):
"""Encodes a tree to a single string."""
if not root:
return "None"
return f"{root.val},{serialize(root.left)},{serialize(root.right)... | from solution import TreeNode, compare_serializations
def test_compare_serializations_identical_trees():
# Tree 1: 1
# / \
# 2 3
# / \
# 4 5
root1 = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))
# Tre... | [] | [
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 se... | trial_gpt4o_2 | {
"original_instruction": "### Task Description\nDesign a function `compare_serializations` that takes the root of two binary trees and returns `True` if their serialized forms are identical, otherwise return `False`. This function will help ensure consistency in tree structure and node values between two trees.\n\n#... | 0.491083 | Data_Structure_15781 | C | [
"serialize",
"compare_serializations"
] | 2 | [
[
"compare_serializations",
"serialize"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | cc55db09746833b50d47c391cd52f4cf343d72a1 | e949354227614f061ef24feb37290ae04cc15081 | |||
v1.0 | complete | Data_Structure | Data_Structure_16014_C | def optimized_encode_rle(input: str) -> str:
""" Perform run-length encoding on the input string, optimized for large inputs.
>>> optimized_encode_rle('') == ''
>>> optimized_encode_rle('a') == '1a'
>>> optimized_encode_rle('aaaaa') == '5a'
>>> optimized_encode_rle('aabcc') == '2a1b2c'
>>> optim... | def optimized_encode_rle(input: str) -> str:
"""
Perform run-length encoding on the input string, optimized for large inputs.
"""
if not input:
return ''
encoded_string = []
count = 1
prev_char = input[0]
for char in input[1:]:
if char == prev_char:
... | from solution import optimized_encode_rle, verify_decode_rle, decode_rle
def test_optimized_encode_rle_empty_string():
assert optimized_encode_rle('') == ''
def test_optimized_encode_rle_single_char():
assert optimized_encode_rle('a') == '1a'
assert optimized_encode_rle('aaaaa') == '5a'
def test_optimize... | [
{
"docstring": "Perform run-length encoding on the input string, optimized for large inputs.",
"function_declaration": "def optimized_encode_rle(input):",
"function_name": "optimized_encode_rle",
"parameter_list": "(input)"
},
{
"docstring": "Decode a run-length encoded string.",
"functi... | [
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 optimized_encode_rle(input: str) -> str:\n \"\"\"\n This function performs run-length encoding on the input string in an optimized manner.\n \"\"... | trial_gpt4o_1 | {
"original_instruction": "### Run-Length Encoding and Decoding\n\nYou are provided with two functions: `encode_rle` and `decode_rle`, which perform run-length encoding and decoding, respectively. Your task is to implement additional functionalities to enhance the Run-Length Encoding.\n\nImplement a function `optimiz... | 0.643258 | Data_Structure_16014 | C | [
"optimized_encode_rle",
"decode_rle",
"verify_decode_rle"
] | 3 | [
[
"verify_decode_rle",
"decode_rle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 87d1a0d4bbb19843766a8f5b31cb6084173d0ec1 | faa5222b9534124b482aa5f79ccad65c7156b4e8 | |||
v1.0 | complete | Data_Structure | Data_Structure_16827_C | from typing import List
def search_insert(sorted_array: List[int], target: int) -> int:
"""
Uses binary search to find the insert position for the target in the sorted_array.
"""
left, right = 0, len(sorted_array)
while left < right:
mid = (left + right) // 2
if sorted_array[mid] < ... | from typing import List
def search_insert(sorted_array: List[int], target: int) -> int:
"""
Uses binary search to find the insert position for the target in the sorted_array.
"""
left, right = 0, len(sorted_array)
while left < right:
mid = (left + right) // 2
if sorted_array[mid] < ... | from solution import insertion_sort_with_search_insert
def test_insertion_sort_with_search_insert_basic():
assert insertion_sort_with_search_insert([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13]
assert insertion_sort_with_search_insert([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12]
def test_insertion_so... | [
{
"docstring": "Uses binary search to find the insert position for the target in the sorted_array.",
"function_declaration": "def search_insert(sorted_array, target):",
"function_name": "search_insert",
"parameter_list": "(sorted_array, target)"
},
{
"docstring": "Sorts an array of integers ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(sorted_array: List[int], target: int) -> int:\n \"\"\"\n Finds the index at which the target should be inse... | trial_gpt4o_2 | {
"original_instruction": "Implement Insertion Sort using Search Insert\n\n#### Context\nGiven an array of integers, you are required to sort it using the insertion sort algorithm. However, to optimize the insertion point search, you should use the provided `search_insert` function that employs binary search to find ... | 0.667463 | Data_Structure_16827 | C | [
"search_insert",
"insertion_sort_with_search_insert"
] | 2 | [
[
"insertion_sort_with_search_insert",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d944042a7acd307c18972128d7ce5365b63dc47e | 4dac64626bbe87576389b3bee435788fdaab9005 | |||
v1.0 | complete | Data_Structure | Data_Structure_17087_C | def power(a: int, n: int, mod: int = None) -> int:
"""
Iterative version to compute a^n % mod
"""
def power_recur(a: int, n: int, mod: int = None) -> int:
"""
Recursive version to compute a^n % mod
"""
def validate_exponentiation(a: int, n: int, mod: int = None) -> bool:
"""Validate if... | def power(a: int, n: int, mod: int = None) -> int:
"""
Iterative version to compute a^n % mod
"""
if n == 0:
return 1 if mod is None else 1 % mod
result = 1
base = a if mod is None else a % mod
while n > 0:
if n % 2 == 1:
result = (result * base) % mod if mod else... | from solution import power, power_recur, validate_exponentiation
def test_power_iter():
assert power(2, 10) == 1024
assert power(2, 10, 1000) == 24
assert power(0, 0) == 1
assert power(100, 0, 10) == 1
assert power(3, 0) == 1
assert power(10, 5) == 100000
def test_power_recur():
assert pow... | [
{
"docstring": "Iterative version to compute a^n % mod",
"function_declaration": "def power(a, n, mod=None):",
"function_name": "power",
"parameter_list": "(a, n, mod=None)"
},
{
"docstring": "Recursive version to compute a^n % mod",
"function_declaration": "def power_recur(a, n, mod=Non... | [
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 power(a: int, n: int, mod: int = None) -> int:\n \"\"\"\n Iterative function to compute a^n % mod.\n \"\"\"\n result = 1\n base = a\n \n... | trial_gpt4o_2 | {
"original_instruction": "You are provided with two functions designed to compute the exponentiation of given integers, optionally modulo another integer:\n\n1. **Iterative Version**: `power(a: int, n: int, mod: int = None)`\n2. **Recursive Version**: `power_recur(a: int, n: int, mod: int = None)`\n\n### Task\n\nImp... | 0.668484 | Data_Structure_17087 | C | [
"power",
"power_recur",
"validate_exponentiation"
] | 3 | [
[
"validate_exponentiation",
"power"
],
[
"validate_exponentiation",
"power_recur"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2c06dc9d4a422eb541a56b0875948d0d92433745 | 32f3190f2f30b8310e75fbac9562c6720a691488 | |||
v1.0 | complete | Data_Structure | Data_Structure_16759_C | def extended_gcd(a: int, b: int) -> int:
""" Returns the Greatest Common Divisor (GCD) of two integers a and b using bitwise operations.
>>> extended_gcd(18, 24) 6
>>> extended_gcd(48, 180) 12
>>> extended_gcd(0, 16) 16
"""
pass
def optimized_lcm(a: int, b: int) -> int:
""" Returns the Leas... | def extended_gcd(a: int, b: int) -> int:
"""
Returns the Greatest Common Divisor (GCD) of two integers a and b using bitwise operations.
"""
if a == 0:
return b
if b == 0:
return a
shift = 0
while ((a | b) & 1) == 0:
a >>= 1
b >>= 1
shift += 1
... | from solution import extended_gcd, optimized_lcm, count_trailing_zeros
def test_extended_gcd():
assert extended_gcd(18, 24) == 6
assert extended_gcd(48, 180) == 12
assert extended_gcd(0, 16) == 16
assert extended_gcd(16, 0) == 16
assert extended_gcd(0, 0) == 0
assert extended_gcd(37, 600) == 1
... | [
{
"docstring": "Returns the Greatest Common Divisor (GCD) of two integers a and b using bitwise operations.",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the Least Common Multiple (LCM) of two integ... | [
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 extended_gcd(a: int, b: int) -> int:\n \"\"\"\n Compute the GCD of two integers using the Euclidean algorithm.\n \"\"\"\n if a == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question Title: Efficiently Finding GCD and LCM Using Custom Functions\n\n### Question Description:\nYou are tasked with implementing a set of functions to compute the Greatest Common Divisor (GCD), Least Common Multiple (LCM), and trailing zeros in the binary representation of integers... | 0.711739 | Data_Structure_16759 | C | [
"extended_gcd",
"optimized_lcm",
"count_trailing_zeros"
] | 3 | [
[
"optimized_lcm",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 83fa7b659e1ec3e378538bbba9cf6241079cf292 | 00d25734c93b628e5edf1a2681244167ab2e26f6 | |||
v1.0 | complete | Data_Structure | Data_Structure_15178_C | from typing import List
def optimized_bitonic_sort(arr: List[int], reverse: bool = False) -> List[int]:
"""
Implement an optimized Bitonic Sort algorithm that can handle arrays of arbitrary size by padding them to the next power of two.
Args:
arr: A list of integers (can be of arbitrary size, not... | import math
def bitonic_compare_and_swap(arr, i, j, direction):
if (direction and arr[i] > arr[j]) or (not direction and arr[i] < arr[j]):
arr[i], arr[j] = arr[j], arr[i]
def bitonic_merge(arr, low, cnt, direction):
if cnt > 1:
k = cnt // 2
for i in range(low, low + k):
bit... | from solution import optimized_bitonic_sort
def test_sorted_array():
assert optimized_bitonic_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert optimized_bitonic_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_random_array():
assert optimized_bitonic_sort([3, 7, 2, 5, 1, ... | [
{
"docstring": null,
"function_declaration": "def bitonic_compare_and_swap(arr, i, j, direction):",
"function_name": "bitonic_compare_and_swap",
"parameter_list": "(arr, i, j, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, low, cnt, direction):",
... | [
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 next_power_of_two(x: int) -> int:\n return 1 if x == 0 else 2**(x - 1).bit_length()\n\ndef bitonic_merge(arr: List[int], low... | trial_gpt4o_1 | {
"original_instruction": "### Question: Implement and Optimize Bitonic Sort\n\nYou are given an implementation of the Bitonic Sort algorithm in Python. Bitonic Sort is a parallel algorithm capable of efficiently sorting arrays, but the provided version is a sequential (non-parallel) one. \n\nYour task is to perform ... | 0.679636 | Data_Structure_15178 | C | [
"bitonic_compare_and_swap",
"bitonic_merge",
"bitonic_sort",
"get_next_power_of_two",
"optimized_bitonic_sort"
] | 5 | [
[
"bitonic_merge",
"bitonic_compare_and_swap"
],
[
"bitonic_sort",
"bitonic_merge"
],
[
"optimized_bitonic_sort",
"bitonic_sort"
],
[
"optimized_bitonic_sort",
"get_next_power_of_two"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 592633d422d577aaa7c9e7f91d9db9046b97a00f | e45fa60c27ceca35c30852a90192b9767bb05e81 | |||
v1.0 | complete | Data_Structure | Data_Structure_16298_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big: TreeNode, small: TreeNode) -> bool:
""" Determines if one binary tree is a subtree of another binary tree.
>>> big = TreeNode(3)
>>> big.... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big: TreeNode, small: TreeNode) -> bool:
if not small:
return True # An empty tree is always a subtree
if not big:
return False # big... | from solution import TreeNode, is_subtree, are_identical
def test_is_subtree():
# Test case 1:
# big: 3
# / \
# 4 5
# / \
# 1 2
# small: 4
# / \
# 1 2
big = TreeNode(3)
big.left = TreeNode(4)
big.right = TreeNo... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_1 | {
"original_instruction": "### Question\nYou are tasked with implementing a function to determine if one binary tree is a subtree of another binary tree. Given two binary trees `big` and `small`, write a function `is_subtree(big, small)` that returns `True` if `small` is a subtree of `big`, and `False` otherwise.\n\n... | 0.61627 | Data_Structure_16298 | C | [
"is_subtree",
"are_identical"
] | 2 | [
[
"is_subtree",
"are_identical"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 5e9f2e46aafddf17b579c5899178efdc74f65bdd | 1060dba30b70f3544b0e04427b65910d7ac8e62e | |||
v1.0 | complete | Data_Structure | Data_Structure_18123_C | from typing import List
def find_power_sum_numbers(low: int, high: int) -> List[int]:
""" Find all integers in the range [low, high] such that the sum of its digits,
each raised to the power of their positions (1-based indexing), equals the number itself.
>>> find_power_sum_numbers(1, 10)
[1, ... | from typing import List
def sum_of_digits_powered(number: int) -> int:
digits = str(number)
return sum(int(digit) ** (index + 1) for index, digit in enumerate(digits))
def find_power_sum_numbers(low: int, high: int) -> List[int]:
result = []
for num in range(low, high + 1):
if num == sum_of_di... | from solution import find_power_sum_numbers
def test_basic_range():
assert find_power_sum_numbers(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_range_with_large_numbers():
assert find_power_sum_numbers(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
def test_single_result():
assert find_power_sum_numbers... | [
{
"docstring": null,
"function_declaration": "def sum_of_digits_powered(number):",
"function_name": "sum_of_digits_powered",
"parameter_list": "(number)"
},
{
"docstring": null,
"function_declaration": "def find_power_sum_numbers(low, high):",
"function_name": "find_power_sum_numbers... | [
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef find_power_sum_numbers(low: int, high: int) -> List[int]:\n def is_power_sum_number(n: int) -> bool:\n digits = str(n... | trial_gpt4o_3 | {
"original_instruction": "Given a range of integers `[low, high]`, write a function named `find_power_sum_numbers` that finds all integers in this range such that the sum of its digits, each raised to the power of their positions (1-based indexing), equals the number itself.\n\n### Function Signature\n```python\ndef... | 0.616121 | Data_Structure_18123 | C | [
"sum_of_digits_powered",
"find_power_sum_numbers"
] | 2 | [
[
"find_power_sum_numbers",
"sum_of_digits_powered"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e22618b7d58fc2c1330f2917481c17a340bd2f26 | 5b6fdf9207301928e5a73c2a3b34b8cf4704b6c0 | |||
v1.0 | complete | Data_Structure | Data_Structure_25212_C | def rsa_key_gen_and_crypto(k: int, data: int, seed: int = None) -> tuple:
"""
Generate RSA keys of a specified bit length, encrypt a given data using the generated public key,
decrypt the encrypted data using the generated private key, and verify that the decrypted data matches
the original data.
... | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(bits):
""" Generate an odd integer randomly """
p = random.getrandbits(bits)
while p % 2 == 0:
p = random.getrandbits(bits)
return p
def generate_prime_number(bits):
""" Generate a prime number of bit length ... | from solution import rsa_key_gen_and_crypto
def test_valid_key_and_data():
k = 16
data = 20
result = rsa_key_gen_and_crypto(k, data, seed=42)
n, e, d, encrypted_data, decrypted_data = result
assert decrypted_data == data
def test_minimum_bit_length():
k = 16
data = 15
result = rsa_key_... | [
{
"docstring": "Generate an odd integer randomly ",
"function_declaration": "def generate_prime_candidate(bits):",
"function_name": "generate_prime_candidate",
"parameter_list": "(bits)"
},
{
"docstring": "Generate a prime number of bit length bits ",
"function_declaration": "def generat... | [
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 gcd(a, b):\n while b != 0:\n a, b = b, a % b\n return a\n\ndef modinv(a, m):\n m0, x0, x1 = m, 0, 1\n if m == 1:\n ... | trial_gpt4o_1 | {
"original_instruction": "### RSA Key Generation and Encryption/Decryption\n\nYou are tasked with building an encryption and decryption system based on the RSA algorithm. The provided implementation details for the RSA key generation algorithm, encryption, and decryption have been shared. Your task is to implement t... | 0.715349 | Data_Structure_25212 | C | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt",
"rsa_key_gen_and_crypto"
] | 6 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
],
[
"rsa_key_gen_and_crypto",
"decrypt"
],
[
"rsa_key_gen_and_crypto",
"encrypt"
],
[
"rsa_key_gen_and_crypto",
"generate_key"
]
] | 5 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 8e24042e1e02351a3fdcec59b5ecdaff02832f53 | 4e4bbbbce44262b7e49302c21f2509ca4d616a76 | |||
v1.0 | complete | Data_Structure | Data_Structure_17192_C | from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big: Optional[TreeNode], small: Optional[TreeNode]) -> bool:
""" Determine if the smaller binary tree `small` is a subtree of ... | from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big: Optional[TreeNode], small: Optional[TreeNode]) -> bool:
if not small:
return True
if not big:
return ... | import pytest
from solution import TreeNode, is_subtree
def test_example_1():
big = TreeNode(3)
big.left = TreeNode(4)
big.right = TreeNode(5)
big.left.left = TreeNode(1)
big.left.right = TreeNode(2)
small = TreeNode(4)
small.left = TreeNode(1)
small.right = TreeNode(2)
as... | [] | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Optional\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n ... | trial_gpt4o_0 | {
"original_instruction": "### Binary Tree Subtree Check\n\n#### Scenario:\n\nYou are working on a software that needs to determine structural similarities between different hierarchical data. One of the application scenarios is to detect if a certain subset of a large dataset matches another smaller dataset in struc... | 0.595702 | Data_Structure_17192 | C | [
"is_subtree",
"is_identical"
] | 2 | [
[
"is_subtree",
"is_identical"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 22c6262c0a9476a0b07308d9d152b900b043806d | 6bd415c68083167801182fb38337357c0450f00d | |||
v1.0 | complete | Data_Structure | Data_Structure_14850_C | def bitwise_sum(a: int, b: int) -> int:
""" Computes the sum of the Hamming weights of two numbers.
>>> bitwise_sum(11, 15)
7
>>> bitwise_sum(0, 0)
0
>>> bitwise_sum(1, 1)
2
>>> bitwise_sum(2**31 - 1, 0)
31
>>> bitwise_sum(2**31 - 1, 2**31 - 1)
62
"""
pass
def hammin... | def hamming_weight_recur(n: int) -> int:
"""
Computes the Hamming weight of a number using recursion.
"""
if n == 0:
return 0
else:
# Turn off the rightmost 1-bit and count the number of operations
return 1 + hamming_weight_recur(n & (n - 1))
def hamming_weight_iter(n: int) ... | from solution import bitwise_sum, hamming_weight_recur, hamming_weight_iter
def test_hamming_weight_recur():
assert hamming_weight_recur(11) == 3 # binary: 1011
assert hamming_weight_recur(15) == 4 # binary: 1111
assert hamming_weight_recur(0) == 0 # binary: 0
assert hamming_weight_recur(1) == 1 ... | [
{
"docstring": "Computes the Hamming weight of a number using recursion.",
"function_declaration": "def hamming_weight_recur(n):",
"function_name": "hamming_weight_recur",
"parameter_list": "(n)"
},
{
"docstring": "Computes the Hamming weight of a number using iteration.",
"function_decl... | [
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 bitwise_sum(a: int, b: int) -> int:\n return hamming_weight_iter(a) + hamming_weight_iter(b)\n\ndef hamming_weight_recur(n: int) -> int:\n if n == 0... | trial_gpt4o_1 | {
"original_instruction": "### Question\n\nWrite a function `bitwise_sum` that takes two unsigned integers and returns the sum of their Hamming weights. The Hamming weight of an integer is the number of '1' bits in its binary representation.\n\nWrite both a recursive and an iterative function to compute the Hamming w... | 0.578965 | Data_Structure_14850 | C | [
"hamming_weight_recur",
"hamming_weight_iter",
"bitwise_sum"
] | 3 | [
[
"bitwise_sum",
"hamming_weight_recur"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 79c3d661c338aeb084d79ad0ea09093370f140cb | a8eb7eb319d64e1981771f0a22740d9c3ea50c6f | |||
v1.0 | complete | Data_Structure | Data_Structure_16677_C | from typing import List
def bitonic_sort(arr: List[int], reverse: bool = False) -> List[int]:
""" Bitonic sort implementation that sorts an array of integers in either increasing or decreasing order.
Ensure that the input array size is always a power of two.
If the size of the input array is not a power of... | from typing import List
def bitonic_compare(arr: List[int], i: int, j: int, direction: bool) -> None:
if (direction and arr[i] > arr[j]) or (not direction and arr[i] < arr[j]):
arr[i], arr[j] = arr[j], arr[i]
def bitonic_merge(arr: List[int], low: int, cnt: int, direction: bool) -> None:
if cnt > 1:
... | import pytest
from solution import bitonic_sort
def test_bitonic_sort_increasing():
assert bitonic_sort([3, 7, 4, 8, 6, 2, 1, 5], reverse=True) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_bitonic_sort_decreasing():
assert bitonic_sort([3, 7, 4, 8, 6, 2, 1, 5], reverse=False) == [8, 7, 6, 5, 4, 3, 2, 1]
def test_bit... | [
{
"docstring": null,
"function_declaration": "def bitonic_compare(arr, i, j, direction):",
"function_name": "bitonic_compare",
"parameter_list": "(arr, i, j, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, low, cnt, direction):",
"function_name": "... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bitonic_sort(arr: List[int], reverse: bool = False) -> List[int]:\n def compare_and_swap(arr, i, j, direction):\n if ... | trial_gpt4o_9 | {
"original_instruction": "### Bitonic Sort Implementation with Edge Case Handling\n\n#### Problem Description:\nYou are required to implement the bitonic sort algorithm to sort an array of integers in either increasing or decreasing order. Ensure that the input array size is always a power of two. If the size of the... | 0.711661 | Data_Structure_16677 | C | [
"bitonic_compare",
"bitonic_merge",
"bitonic_sort_rec",
"bitonic_sort"
] | 4 | [
[
"bitonic_merge",
"bitonic_compare"
],
[
"bitonic_sort",
"bitonic_sort_rec"
],
[
"bitonic_sort_rec",
"bitonic_merge"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 4e08ad2a3981c05de8cd6e08b63df1ddc2b9efda | d170d75523296207e4fd52a108b5d9949a73f4b6 | |||
v1.0 | complete | Data_Structure | Data_Structure_17988_C | def combination(n: int, k: int, mod: int = None) -> int:
""" Calculate the number of combinations (C(n, k)) with an optional modulo.
Calculate the number of ways to choose `k` elements from a set of `n` elements,
optionally modulo a given number.
Args:
- n: A non-negative integer representing... | def factorial(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
def combination(n, k, mod=None):
if k < 0 or k > n:
raise ValueError("k must be between 0 and n.")
if k == 0 or k == n:
return 1
num = factorial(n)
denom = factorial(k) * factorial(n -... | from solution import combination
def test_combination_basic():
assert combination(5, 2) == 10
def test_combination_with_mod():
assert combination(5, 2, 1000) == 10
assert combination(20, 10, 1000) == 184756 % 1000
def test_combination_large_inputs():
assert combination(50, 5, 100000) == 2118760 % 100... | [
{
"docstring": null,
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def combination(n, k, mod=None):",
"function_name": "combination",
"parameter_list": "(n, k, mod=None)"
}
] | [
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 combination(n: int, k: int, mod: int = None) -> int:\n \"\"\"\n Calculate the number of combinations C(n, k), which is the number of ways to choose\... | trial_gpt4o_2 | {
"original_instruction": "### Context\nYou have been tasked with developing a new approach for calculating combinations in statistics. The factorial function, which is fundamental for combinations, is often computed multiple times with high values of `n`. To ensure reliability and performance, you'll enhance it with... | 0.666561 | Data_Structure_17988 | C | [
"factorial",
"combination"
] | 2 | [
[
"combination",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8c231bad23a839bb23e9b8d428226fcc45bdbca2 | 2eb6e57362c0d851c771f4b7f0bfbeeaf796b6ac | |||
v1.0 | complete | Data_Structure | Data_Structure_15196_C | class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_traversal(root: Node, method: str = 'recursive') -> list:
"""
Returns the in-order traversal of the binary tree rooted at 'root'.
Parameters:
- r... | class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_traversal(root: Node, method: str = 'recursive') -> list:
"""
Returns the in-order traversal of the binary tree rooted at 'root'.
Parameters:
- r... | from solution import inorder_traversal, Node
def test_example_tree_recursive():
# Creating the tree from the example
n1 = Node(100)
n2 = Node(50)
n3 = Node(150)
n4 = Node(25)
n5 = Node(75)
n6 = Node(125)
n7 = Node(175)
n1.left, n1.right = n2, n3
n2.left, n2.right = n4, n5
n3... | [] | [
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, Optional\n\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None):\n self.val = val\n ... | trial_gpt4o_1 | {
"original_instruction": "### Problem Description\n\nYou are given a binary tree and you need to implement an in-order traversal algorithm. The task is to create a function that takes the root node of a binary tree and returns a list of node values in in-order sequence.\n\n### Function Signature\n\n```python\ndef in... | 0.557334 | Data_Structure_15196 | C | [
"inorder_traversal",
"inorder_traversal_recursive",
"inorder_traversal_iterative"
] | 3 | [
[
"inorder_traversal",
"inorder_traversal_iterative"
],
[
"inorder_traversal",
"inorder_traversal_recursive"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | true | [] | true | c176b219c952ab2b0fd4a36ad7c68e08f00e0166 | b2e06638aef7a64ca35bba04b576d7618c23542b | |||
v1.0 | complete | Data_Structure | Data_Structure_15309_C | import random
from typing import Tuple
from sympy import isprime, mod_inverse
def generate_key(k: int, seed: int = None) -> Tuple[int, int, int]:
"""
Generate RSA key pair (n, e, d) with modulus bit length k.
:param k: Bit length of the modulus n.
:param seed: Optional seed for random number generator... | import random
from sympy import isprime, mod_inverse
def miller_rabin(n, k=40):
"""Test if n is a prime number using the Miller-Rabin primality test"""
if n == 2 or n == 3:
return True
if n <= 1 or n % 2 == 0:
return False
r, s = 0, n - 1
while s % 2 == 0:
r += 1
... | from solution import generate_key, sign, verify
def test_generate_key():
n, e, d = generate_key(16, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert n > 0
assert e > 1
assert d > 1
assert e != d
def test_sign_verify():
n, e, d = generate... | [
{
"docstring": "Test if n is a prime number using the Miller-Rabin primality test",
"function_declaration": "def miller_rabin(n, k=40):",
"function_name": "miller_rabin",
"parameter_list": "(n, k=40)"
},
{
"docstring": "Generate a prime number of specified bit length",
"function_declarat... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom math import gcd\n\ndef miller_rabin(n, k=40):\n if n == 2 or n == 3:\n return True\n if n <= 1 or n % 2 == 0:\n return... | trial_gpt4o_1 | {
"original_instruction": "You have been given the task of improving the RSA key generation function to enhance its efficiency by incorporating probabilistic primality tests and optimizing the modular inverse calculation. Additionally, you should extend the RSA encryption scheme by implementing a signature verificati... | 0.682867 | Data_Structure_15309 | C | [
"miller_rabin",
"generate_large_prime",
"generate_key",
"sign",
"verify"
] | 5 | [
[
"generate_key",
"generate_large_prime"
],
[
"generate_large_prime",
"miller_rabin"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 4b10b89c5d216ef0ba4e8ecbb0655eacb8bf84ed | 2e8f3bf76c77970fd45c73c4f5f49518e2009649 | |||
v1.0 | complete | Data_Structure | Data_Structure_17803_C | from random import randint
from sympy import isprime, primitive_root
def prime_check(num: int) -> bool:
"""Check if a number is a prime number."""
pass
def find_primitive_root(n: int) -> list:
"""Find the primitive root of a given number."""
pass
def alice_private_key(p: int) -> int:
"""Generate ... | from random import randint
from sympy import isprime, primitive_root
def prime_check(num: int) -> bool:
return isprime(num)
def find_primitive_root(n: int) -> list:
try:
return [primitive_root(n)]
except ValueError:
return []
def alice_private_key(p: int) -> int:
return randint(2, p-1... | from solution import diffie_hellman_key_exchange
def test_valid_diffie_hellman():
assert diffie_hellman_key_exchange(2, 11) == True
def test_invalid_prime_p():
assert diffie_hellman_key_exchange(2, 10) == False
def test_invalid_primitive_root_a():
assert diffie_hellman_key_exchange(5, 11) == False
def t... | [
{
"docstring": null,
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def find_primitive_root(n):",
"function_name": "find_primitive_root",
"parameter_list": "(n)"
},
{
... | [
0,
0,
0,
0,
0,
1,
0,
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": "from sympy import isprime, primitive_root\nimport random\n\ndef prime_check(num: int) -> bool:\n return isprime(num)\n\ndef find_primitive_root(n: int) -> ... | trial_gpt4o_8 | {
"original_instruction": "You are tasked with implementing a secure communication channel using the Diffie-Hellman key exchange algorithm. This algorithm allows two parties, Alice and Bob, to establish a shared secret over an unsecured channel by leveraging properties of prime numbers and primitive roots.\n\n### Obj... | 0.536242 | Data_Structure_17803 | C | [
"prime_check",
"find_primitive_root",
"alice_private_key",
"alice_public_key",
"bob_private_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"diffie_hellman_key_exchange"
] | 9 | [
[
"diffie_hellman_key_exchange",
"alice_private_key"
],
[
"diffie_hellman_key_exchange",
"alice_public_key"
],
[
"diffie_hellman_key_exchange",
"alice_shared_key"
],
[
"diffie_hellman_key_exchange",
"bob_private_key"
],
[
"diffie_hellman_key_exchange",
"bob_pu... | 8 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | aaee3137657992d9cd25268eb367e6f0f65b5ae6 | 98163a4af2ab9f84e966829b008149c7da7d880f | |||
v1.0 | complete | Data_Structure | Data_Structure_25416_C | from typing import List, Tuple
def minimum_spanning_tree(n: int, edges: List[Tuple[int, int, int]]) -> int:
""" Compute the Minimum Spanning Tree (MST) of a weighted, undirected graph using Kruskal's Algorithm.
The function should return the sum of the weights of the edges in the MST.
If the graph is disco... | from typing import List, Tuple
def find(parent, i):
if parent[i] == i:
return i
else:
return find(parent, parent[i])
def union(parent, rank, x, y):
rootX = find(parent, x)
rootY = find(parent, y)
if rootX != rootY:
if rank[rootX] > rank[rootY]:
parent[rootY] = r... | from solution import minimum_spanning_tree
def test_example_case():
edges = [(0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4)]
assert minimum_spanning_tree(4, edges) == 19
def test_disconnected_graph():
edges = [(0, 1, 1), (2, 3, 2)]
assert minimum_spanning_tree(4, edges) == -1
def test_single... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\nclass DisjointSet:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [0] * n\n \n ... | trial_gpt4o_1 | {
"original_instruction": "### Question: Optimal Network Wiring with Minimum Spanning Tree\n\nYou are tasked with designing the most cost-effective way to lay down electrical wires to connect a set of buildings. The connections between buildings are represented as a weighted, undirected graph where nodes represent bu... | 0.736051 | Data_Structure_25416 | C | [
"find",
"union",
"minimum_spanning_tree"
] | 3 | [
[
"minimum_spanning_tree",
"find"
],
[
"minimum_spanning_tree",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 3ee2a53846ce612edabe5f8f2e14c1c11029457a | 522acfa94c541e4789a4cd62d24c1dfc8a611aa3 | |||
v1.0 | complete | Data_Structure | Data_Structure_37726_C | from typing import List
def knuth_morris_pratt(text: str, pattern: str) -> List[int]:
""" Find all occurrences of a pattern within a given text using the Knuth-Morris-Pratt (KMP) algorithm.
>>> knuth_morris_pratt('hello there hero!', 'he')
[0, 7, 12]
>>> knuth_morris_pratt('abcd', 'e')
[]
>>> k... | from typing import List
def compute_lps(pattern: str) -> List[int]:
"""
Compute the longest prefix which is also suffix array (LPS array) for the pattern.
"""
lps = [0] * len(pattern)
length = 0 # length of the previous longest prefix suffix
i = 1
while i < len(pattern):
if pa... | from solution import knuth_morris_pratt
def test_knuth_morris_pratt():
assert knuth_morris_pratt('hello there hero!', 'he') == [0, 7, 12]
assert knuth_morris_pratt('abcd', 'e') == []
assert knuth_morris_pratt('abababab', 'ab') == [0, 2, 4, 6]
assert knuth_morris_pratt('aaaaa', 'aa') == [0, 1, 2, 3]
... | [
{
"docstring": "Compute the longest prefix which is also suffix array (LPS array) for the pattern.",
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": "Find all occurrences of the pattern in the given text usi... | [
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 knuth_morris_pratt(text: str, pattern: str) -> List[int]:\n if not pattern:\n return []\n\n def compute_lps(patter... | trial_gpt4o_2 | {
"original_instruction": "### Programming Exercise\n\n#### Scenario\nYou have been hired by a software company to work on their text editing tool's \"find\" functionality. The current implementation is too slow for large documents, and they have decided to use the Knuth-Morris-Pratt string matching algorithm to impr... | 0.595982 | Data_Structure_37726 | C | [
"compute_lps",
"knuth_morris_pratt"
] | 2 | [
[
"knuth_morris_pratt",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a2e7244a7d2add6944cbaea136016e991cc6bf08 | d0e03b8640ccded592dab126fd289e97fe867c9d | |||
v1.0 | complete | Data_Structure | Data_Structure_34352_C | def segmented_sieve(n: int) -> List[int]:
""" Generates all prime numbers less than the given number n using a segmented sieve approach.
>>> segmented_sieve(2)
[]
>>> segmented_sieve(3)
[2]
>>> segmented_sieve(10)
[2, 3, 5, 7]
>>> segmented_sieve(30)
[2, 3, 5, 7, 11, 13, 17, 19, 23, ... | from math import isqrt
from typing import List
def simple_sieve(limit: int) -> List[int]:
"""Generates all prime numbers up to limit using the simple Sieve of Eratosthenes"""
sieve = [True] * (limit + 1)
sieve[0] = sieve[1] = False
for start in range(2, isqrt(limit) + 1):
if sieve[start]:
... | from solution import segmented_sieve
def test_segmented_sieve_small():
assert segmented_sieve(2) == []
assert segmented_sieve(3) == [2]
assert segmented_sieve(10) == [2, 3, 5, 7]
assert segmented_sieve(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
def test_segmented_sieve_large():
assert segmented_s... | [
{
"docstring": "Generates all prime numbers up to limit using the simple Sieve of Eratosthenes",
"function_declaration": "def simple_sieve(limit):",
"function_name": "simple_sieve",
"parameter_list": "(limit)"
},
{
"docstring": "Generates all prime numbers less than n using the segmented sie... | [
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 segmented_sieve(n: int):\n \"\"\"\n Generates all prime numbers less than n using a segmented sieve approach.\n \"\"\"\n import math\n \n ... | trial_gpt4o_2 | {
"original_instruction": "### Problem Description\nIn this task, you are required to extend and optimize the Sieve of Eratosthenes for generating prime numbers. Particularly, your task is to further reduce the space complexity by implementing a segmented sieve approach.\n\n### Task\nExtend the `get_primes` function ... | 0.713675 | Data_Structure_34352 | C | [
"simple_sieve",
"segmented_sieve"
] | 2 | [
[
"segmented_sieve",
"simple_sieve"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ba89501285de97a468db46a3ce622d9a7b1cc288 | 776c39f2cededac47efcbc82e4d13173ca456509 | |||
v1.0 | complete | Data_Structure | Data_Structure_25430_C | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr, simulation=False):
""" Sort the list using Bogo Sort algorithm.
Checks if the giv... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr, simulation=False):
"""
Function to sort the array using Bogo Sort.
"""
it... | from solution import bogo_sort
import pytest
def test_bogo_sort_sorted_array():
assert bogo_sort([1, 2, 3]) == [1, 2, 3]
def test_bogo_sort_unsorted_array():
assert bogo_sort([3, 1, 2]) == [1, 2, 3]
def test_bogo_sort_single_element():
assert bogo_sort([1]) == [1]
def test_bogo_sort_empty_array():
a... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Function to sort the array using Bogo Sort.",
"function_declaration": "def bogo_sort(arr, simulatio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if an array is sorted.\n \"\"\"\n for i in range(len(arr) - 1):\n ... | trial_gpt4o_2 | {
"original_instruction": "### Bogo Sort Implementation and Analysis\n\n#### Problem Statement\nYou are tasked to implement the Bogo Sort algorithm as described in the analysis above. The Bogo Sort algorithm checks if the given array is sorted, and if not, it shuffles the array randomly until it is sorted.\n\nYour im... | 0.629601 | Data_Structure_25430 | C | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 52abead5d0273d93a1087c42f615edcb5546ae0a | 559fd1d5da122579743429c1886a444c99e982fd | |||
v1.0 | complete | Data_Structure | Data_Structure_38255_C | def extended_gcd(a: int, b: int) -> [int, int, int]:
"""
Given two integers a and b, return a tuple (s, t, g) such that a*s + b*t = g, where g is the GCD of a and b.
>>> extended_gcd(30, 20)
(1, -1, 10) or (-1, 2, 10)
>>> extended_gcd(48, 18)
(1, -2, 6) or (-1, 3, 6)
"""
pass
def modula... | def extended_gcd(a: int, b: int):
"""
Given two integers a and b, return a tuple (s, t, g) such that a*s + b*t = g, where g is the GCD of a and b.
"""
if b == 0:
return (1, 0, a)
else:
s, t, g = extended_gcd(b, a % b)
return (t, s - (a // b) * t, g)
def modular_inverse(a: in... | from solution import extended_gcd, modular_inverse
def test_extended_gcd():
assert extended_gcd(30, 20) == (1, -1, 10) or extended_gcd(30, 20) == (-1, 2, 10)
assert extended_gcd(48, 18) == (1, -2, 6) or extended_gcd(48, 18) == (-1, 3, 6)
assert extended_gcd(7, 5) == (-2, 3, 1) or extended_gcd(7, 5) == (3, ... | [
{
"docstring": "Given two integers a and b, return a tuple (s, t, g) such that a*s + b*t = g, where g is the GCD of a and b.",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Given two integers a and m, return ... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def extended_gcd(a: int, b: int):\n \"\"\"\n Given two integers a and b, return a tuple (s, t, g) such that a*s + b*t = g, where g is the GCD of a and b... | trial_gpt4o_0 | {
"original_instruction": "**Problem Statement:**\n\nYou are a member of a cryptography team working on implementing a secure communication system. One of the tasks is to compute modular inverses to encode and decode messages securely. Your job is to implement two crucial functions: `extended_gcd` and `modular_invers... | 0.667058 | Data_Structure_38255 | C | [
"extended_gcd",
"modular_inverse"
] | 2 | [
[
"modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4903c291692098141df54b42094ddcfddb5a3c84 | 4f6070563ce0f95844aebdb55597a2c130bed7f2 | |||
v1.0 | complete | Data_Structure | Data_Structure_34402_C | from typing import List
def modified_bitonic_sort(arr: List[int], reverse: bool = False, pad_value: int = float('inf')) -> List[int]:
"""
Sorts an array using the Bitonic Sort algorithm, modified to handle arrays of any size.
Parameters:
arr (List[int]): The array to sort.
reverse (bool): If True,... | from typing import List
import math
def bitonic_compare_and_swap(arr: List[int], i: int, j: int, direction: bool):
if direction == (arr[i] > arr[j]):
arr[i], arr[j] = arr[j], arr[i]
def bitonic_merge(arr: List[int], low: int, cnt: int, direction: bool):
if cnt > 1:
k = cnt // 2
for i i... | from solution import modified_bitonic_sort
def test_sorted_array():
assert modified_bitonic_sort([3, 1, 5, 7, 2]) == [1, 2, 3, 5, 7]
assert modified_bitonic_sort([3, 1, 5, 7, 2], reverse=True) == [7, 5, 3, 2, 1]
def test_single_element():
assert modified_bitonic_sort([1]) == [1]
assert modified_bitoni... | [
{
"docstring": null,
"function_declaration": "def bitonic_compare_and_swap(arr, i, j, direction):",
"function_name": "bitonic_compare_and_swap",
"parameter_list": "(arr, i, j, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, low, cnt, direction):",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport math\n\ndef bitonic_compare_and_swap(arr: List[int], i: int, j: int, direction: bool):\n if direction == (arr[i] > arr[j]):... | trial_gpt4o_0 | {
"original_instruction": "Bitonic Sort Implementation\n\n#### Objective\nYour task is to implement a modified version of the `bitonic_sort` function. This modified version should handle arrays of any size by padding the array to the next power of two with a specified padding value before sorting and then removing th... | 0.713213 | Data_Structure_34402 | C | [
"bitonic_compare_and_swap",
"bitonic_merge",
"bitonic_sort_rec",
"next_power_of_two",
"modified_bitonic_sort"
] | 5 | [
[
"bitonic_merge",
"bitonic_compare_and_swap"
],
[
"bitonic_sort_rec",
"bitonic_merge"
],
[
"modified_bitonic_sort",
"bitonic_sort_rec"
],
[
"modified_bitonic_sort",
"next_power_of_two"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 443aa7d59e7a1bbd020214744f328e30aa5bbd19 | 65d0ad5b7067981bdf580d2cf40b5e0f8c32b45b | |||
v1.0 | complete | Data_Structure | Data_Structure_31279_C | def encode_file(input_filename: str, encoded_filename: str) -> None:
"""
Encodes the content of the input file using Huffman Coding and stores the encoded result
in a binary file along with the Huffman tree structure.
:param input_filename: The name of the file to be encoded
:param encoded_fil... | import heapq
import os
from collections import defaultdict, Counter
import pickle
class Node:
def __init__(self, char=None, freq=None, left=None, right=None):
self.char = char
self.freq = freq
self.left = left
self.right = right
def __lt__(self, other):
return s... | import os
from solution import encode_file, decode_file
def test_huffman_coding():
input_content = "hello huffman"
input_filename = "test_input.txt"
encoded_filename = "test_encoded.bin"
decoded_filename = "test_decoded.txt"
with open(input_filename, "w") as file:
file.write(input_cont... | [] | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nfrom collections import Counter, defaultdict\nimport pickle\n\nclass HuffmanNode:\n def __init__(self, symbol=None, freq=0):\n self.sy... | trial_gpt4o_8 | {
"original_instruction": "### Question: Implement Huffman Coding for Data Compression\n\nGiven an input file, implement the Huffman Coding algorithm to encode the file's content and then decode the file back to its original content to verify that the lossless compression works correctly. The main tasks are to:\n1. C... | 0.582416 | Data_Structure_31279 | C | [
"build_huffman_tree",
"build_codes",
"encode_text",
"pad_encoded_text",
"to_bytearray",
"encode_file",
"remove_padding",
"decode_text",
"decode_file"
] | 9 | [
[
"decode_file",
"decode_text"
],
[
"decode_file",
"remove_padding"
],
[
"encode_file",
"build_codes"
],
[
"encode_file",
"build_huffman_tree"
],
[
"encode_file",
"encode_text"
],
[
"encode_file",
"pad_encoded_text"
],
[
"encode_file",
... | 7 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 0fa48dfe0e2e60f974d6155f2c6cc1b9317b25b8 | 4805c2d4dd74d490095851e1731663dd4366e0d2 | |||
v1.0 | complete | Data_Structure | Data_Structure_43882_C | def diffie_hellman_secure_exchange(p: int, g: int) -> Union[int, bool]:
""" Perform Diffie-Hellman Key Exchange securely.
>>> diffie_hellman_secure_exchange(23, 5)
Shared key (e.g., 2) or False
>>> diffie_hellman_secure_exchange(20, 5)
False
"""
def is_prime(n: int) -> bool:
""" Check if a ... | import random
def is_prime(n):
"""Check if a number is prime using a simple method."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import diffie_hellman_secure_exchange, is_prime, is_primitive_root
def test_diffie_hellman_basic():
p = 23
g = 5
shared_key = diffie_hellman_secure_exchange(p, g)
assert isinstance(shared_key, int) or shared_key == False
def test_diffie_hellman_large_prime():
p = 7919
g = 7
s... | [
{
"docstring": "Check if a number is prime using a simple method.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Check if g is a primitive root modulo p.",
"function_declaration": "def is_primitive_root(g, p):",
"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(n):\n \"\"\"Check if a number is prime using a simple method.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ... | trial_gpt4o_0 | {
"original_instruction": "### Secure Communication Using Diffie-Hellman Key Exchange\n\nIn modern secure communication systems, two parties need to exchange cryptographic keys securely over an insecure channel. The Diffie-Hellman Key Exchange algorithm allows two parties to generate a shared secret key over such a c... | 0.548965 | Data_Structure_43882 | C | [
"is_prime",
"is_primitive_root",
"diffie_hellman_secure_exchange",
"gcd"
] | 4 | [
[
"diffie_hellman_secure_exchange",
"is_prime"
],
[
"diffie_hellman_secure_exchange",
"is_primitive_root"
],
[
"is_primitive_root",
"gcd"
],
[
"is_primitive_root",
"is_prime"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | f6a3d04b782fb565674d0088269d198269fe91db | 325c0b69d5d2c7dc3138c76c37009783eada89fe | |||
v1.0 | complete | Data_Structure | Data_Structure_16586_C | def matrix_exponentiation_kth_power(matrix: list, k: int) -> list:
"""
Compute the k-th power of a given square matrix using matrix exponentiation by squaring.
Args:
- matrix (list of lists of ints): square matrix of size n x n.
- k (int): the exponent to raise the matrix to.
Returns:
- li... | def matrix_multiply(A, B):
"""
Multiplies two matrices A and B.
"""
n = len(A)
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += A[i][k] * B[k][j]
return result
def matrix_exponentiation_kth... | from solution import matrix_exponentiation_kth_power
def test_identity_matrix_power():
matrix = [
[1, 0],
[0, 1]
]
k = 5
result = matrix_exponentiation_kth_power(matrix, k)
expected = [
[1, 0],
[0, 1]
]
assert result == expected
def test_zero_power():
ma... | [
{
"docstring": "Multiplies two matrices A and B.",
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": "Compute the k-th power of a given square matrix using exponentiation by squaring.",
"function_declara... | [
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_multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B.\n \"\"\"\n n = len(A)\n result = [[0] * n for _ in range(n)]\n \n ... | trial_gpt4o_0 | {
"original_instruction": "### Matrix Exponentiation Coding Challenge\n\n#### Context\nIn graph theory, the k-th power of the adjacency matrix of a graph gives information about the number of paths of length k between vertices. In cryptographic algorithms, matrix exponentiation is widely used for key generation and t... | 0.568506 | Data_Structure_16586 | C | [
"matrix_multiply",
"matrix_exponentiation_kth_power"
] | 2 | [
[
"matrix_exponentiation_kth_power",
"matrix_multiply"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8028f50038e3fdf039ef0053335313a45d27d149 | 905a745faf8fa1a8128579b94c905a2c7871f00e | |||
v1.0 | complete | Data_Structure | Data_Structure_44745_C | import random
def next_state(chain: dict, current_state: str) -> str:
"""
Returns the next state given the current state based on the Markov chain transition probabilities.
Parameters:
- chain: Dictionary representing the Markov chain.
- current_state: String representing the current state.
... | import random
def next_state(chain: dict, current_state: str) -> str:
"""
Returns the next state given the current state based on the Markov chain transition probabilities.
Parameters:
- chain: Dictionary representing the Markov chain.
- current_state: String representing the current state.
... | from solution import next_state, generate_sequence
def test_next_state():
chain = {
'start': {'call': 0.5, 'meet': 0.5},
'call': {'end': 1.0},
'meet': {'talk': 0.8, 'end': 0.2},
'talk': {'end': 1.0},
'end': {}
}
random.seed(0) # Ensure reproducibility
resul... | [
{
"docstring": "Returns the next state given the current state based on the Markov chain transition probabilities.\n\nParameters:\n- chain: Dictionary representing the Markov chain.\n- current_state: String representing the current state.\n\nReturns:\n- String representing the next state.",
"function_declar... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef next_state(chain: dict, current_state: str) -> str:\n \"\"\"\n Returns the next state given the current state based on the Markov c... | trial_gpt4o_2 | {
"original_instruction": "**Context**: You work for a tech company that is developing a predictive text feature for a messaging app. To accurately predict the next word a user will type, you need to model the typing behavior using a Markov chain. You have a record of user behavior which reveals the probabilities of ... | 0.562837 | Data_Structure_44745 | C | [
"next_state",
"generate_sequence"
] | 2 | [
[
"generate_sequence",
"next_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0963b4590611fb2506814a13acc55ee40c8924ca | 087f949f406ff0f8da1d6c1a30070600533da01a | |||
v1.0 | complete | Data_Structure | Data_Structure_16697_C | def radix_sort(arr: list[int], simulation: bool = False) -> list[int]:
"""
Perform radix sort on a list of non-negative integers.
:param arr: List of non-negative integers that needs to be sorted.
:param simulation: Bool, if True, the function prints the array's state at each iteration.
:return: So... | def counting_sort(arr, exp, simulation, iter_num):
n = len(arr)
output = [0] * n
count = [0] * 10
# Store count of occurrences in count[]
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
# Change count[i] so that it contains the actual
# position of this digi... | from solution import radix_sort
def test_radix_sort_basic_cases():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_empty_list():
assert radix_sort([]) == []
def test_radix_sort_single_element_list():
assert radix_sort([5]) == [5]
def test_rad... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation, iter_num):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation, iter_num)"
},
{
"docstring": "Perform radix sort on a list of non-negative integers.\n\n:param arr: List of non-negat... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp, simulation, iter_num):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # Store count of occurrences in count[... | trial_gpt4o_0 | {
"original_instruction": "### Radix Sort Implementation\n\nImplement the `radix_sort` function for sorting a list of non-negative integers. Your implementation should be able to handle a list of integers and sort them in non-decreasing order using the radix sort algorithm specified above.\n\n#### Function Signature\... | 0.651727 | Data_Structure_16697 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | afb51a04f079ac813823004aa62cfda6dbd8193d | fae8c5e257e3e40add3077895aa1682dc4358cf3 | |||
v1.0 | complete | Data_Structure | Data_Structure_17915_C | from typing import List
def radix_sort(arr: List[int]) -> List[int]:
"""Sort a list of non-negative integers using radix sort algorithm.
Args:
arr (List[int]): A list of non-negative integers to be sorted.
Returns:
List[int]: Sorted list of integers in ascending order.
Exampl... | from typing import List
def radix_sort(arr: List[int]) -> List[int]:
if len(arr) == 0:
return arr
max_num = max(arr)
exp = 1
while max_num // exp > 0:
arr = counting_sort(arr, exp)
exp *= 10
return arr
def counting_sort(arr: List[int], exp: int) -> List[int]:
n = len(a... | from solution import radix_sort
def test_radix_sort_basic():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_empty():
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort([1]) == [1]
def test_radix_sort_all_same... | [
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \n for i in range(n):\n index = arr[i] // exp\n ... | trial_gpt4o_2 | {
"original_instruction": "### Radix Sort Implementation and Testing\n\nGiven the radix sort algorithm provided, you are required to implement and test a modified version that can handle a list of non-negative integers. Your function should also handle cases where the list might be empty. Moreover, you need to develo... | 0.694126 | Data_Structure_17915 | C | [
"radix_sort",
"counting_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 67a67096502148edec5804423d2047bc9fe7ec47 | 4c5d602837a4182926979fd3ee2462538e1abe12 | |||
v1.0 | complete | Data_Structure | Data_Structure_37609_C | def compute_gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor of a and b using Euclid's algorithm.
>>> compute_gcd(48, 18) == 6
>>> compute_gcd(101, 103) == 1
>>> compute_gcd(0, 10) == 10
"""
pass
def compute_lcm(a: int, b: int) -> int:
"""
Computes the least comm... | def compute_gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor of a and b using Euclid's algorithm.
"""
while b:
a, b = b, a % b
return a
def compute_lcm(a: int, b: int) -> int:
"""
Computes the least common multiple of a and b.
"""
if a == 0 or b == 0:
... | import pytest
from solution import compute_gcd, compute_lcm, count_trailing_zeros, compute_gcd_bitwise
def test_compute_gcd():
assert compute_gcd(48, 18) == 6
assert compute_gcd(101, 103) == 1
assert compute_gcd(0, 0) == 0
assert compute_gcd(0, 10) == 10
assert compute_gcd(50, 0) == 50
def test_co... | [
{
"docstring": "Computes the greatest common divisor of a and b using Euclid's algorithm.",
"function_declaration": "def compute_gcd(a, b):",
"function_name": "compute_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the least common multiple of a and b.",
"function_declarati... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def compute_gcd(a: int, b: int) -> int:\n \"\"\"\n Returns the greatest common divisor (GCD) of two non-negative integers using the Euclidean algorithm.... | trial_gpt4o_2 | {
"original_instruction": "## Coding Assessment Question\n\n### Objective\nWrite a function to compute the greatest common divisor (GCD) of two non-negative integers using the Euclidean algorithm, another function for the least common multiple (LCM), a function to count trailing zeros in an integer's binary represent... | 0.730029 | Data_Structure_37609 | C | [
"compute_gcd",
"compute_lcm",
"count_trailing_zeros",
"compute_gcd_bitwise"
] | 4 | [
[
"compute_lcm",
"compute_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5bb95f6861fc654a2ae7a0032a155b704ec51bb1 | a074ce5f0e98b290be15c6e41c33a22ab1e2ea2a | |||
v1.0 | complete | Data_Structure | Data_Structure_31484_C | def merge_sort(arr):
"""
Sorts the array using the merge sort algorithm.
>>> merge_sort([38, 27, 43, 3, 9, 82, 10])
[3, 9, 10, 27, 38, 43, 82]
>>> merge_sort([17, 3, 44, 25, 1])
[1, 3, 17, 25, 44]
>>> merge_sort([])
[]
>>> merge_sort([1])
[1]
"""
def merge(left, right, merg... | def merge_sort(arr):
"""
Sorts the array using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
merged = []
merge(left_half, right_half, merged)
return merged... | from solution import merge_sort, merge
def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
assert merge_sort([5]) == [5]
def test_merge_sort_sorted_array():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_m... | [
{
"docstring": "Sorts the array using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted arrays into a single sorted array.",
"function_declaration": "def merge(left, ri... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array of integers using the merge sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n \... | trial_gpt4o_2 | {
"original_instruction": "### Context\nMerge Sort is a popular sorting algorithm known for its efficiency and simplicity. In this task, you are required to implement the Merge Sort algorithm to sort an array of integers in ascending order. \n\n### Problem Statement\nYou need to implement the following functions:\n\n... | 0.674358 | Data_Structure_31484 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aba31c613ee5947db260cb5bb99023ed5a82833b | ca0f44ee221cee8683eef710de137bbead9785d3 | |||
v1.0 | complete | Data_Structure | Data_Structure_18148_C | def validate_input(arr):
"""
Validate if the length of the list is a power of two.
"""
pass
def bitonic_sort(arr):
"""
Perform the bitonic sort on the input array.
If the input is invalid, raise a ValueError with the message "Input size must be a power of two".
"""
pass
def compare... | def validate_input(arr):
"""
Validate if the length of the list is a power of two.
"""
n = len(arr)
return (n & (n - 1) == 0) and n != 0
def bitonic_sort(arr):
"""
Perform the bitonic sort on the input array.
"""
if not validate_input(arr):
raise ValueError("Input size must ... | from solution import validate_input, bitonic_sort
def test_validate_input():
assert validate_input([1]) == True
assert validate_input([1, 2]) == True
assert validate_input([1, 2, 3, 4]) == True
assert validate_input([1, 2, 3]) == False
assert validate_input([]) == False
def test_bitonic_sort_valid... | [
{
"docstring": "Validate if the length of the list is a power of two.",
"function_declaration": "def validate_input(arr):",
"function_name": "validate_input",
"parameter_list": "(arr)"
},
{
"docstring": "Perform the bitonic sort on the input array.",
"function_declaration": "def bitonic_... | [
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 validate_input(arr):\n \"\"\"\n Checks if the length of the input array is a power of two.\n \n Parameters:\n arr (list): The input list of... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with ensuring all input arrays provided to the `bitonic_sort` function are valid for the sorting algorithm. To do this, you need to write a helper function `validate_input` that checks whether the input size is a power of two. Additionally, modify the original `bitonic_sort` ... | 0.658261 | Data_Structure_18148 | C | [
"validate_input",
"bitonic_sort"
] | 2 | [
[
"bitonic_sort",
"validate_input"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 936b03b5417b7bbff53b0519c25db02c60a9f9d2 | 3abd227eae1ad043464e0985d45e1fad7da2bca8 | |||
v1.0 | complete | Data_Structure | Data_Structure_17588_C | def insert(arr, key):
"""Inserts a key into the priority queue.
Args:
arr (List[int]): The current max priority queue.
key (int): The key to be inserted.
Returns:
List[int]: The updated max priority queue.
"""
pass
def extract_max(arr):
"""Extracts the maximum key from the priorit... | def insert(arr, key):
"""
Inserts a key into the priority queue.
"""
arr.append(key)
_sift_up(arr, len(arr) - 1)
return arr
def extract_max(arr):
"""
Extracts the maximum key from the priority queue.
"""
if len(arr) == 0:
return arr, None
max_element = arr[0]
ar... | from solution import insert, extract_max, get_max
def test_insert():
arr = []
arr = insert(arr, 10)
assert arr == [10]
arr = insert(arr, 5)
assert arr == [10, 5]
arr = insert(arr, 30)
assert arr == [30, 5, 10]
def test_extract_max():
arr = [30, 5, 10]
arr, max_element = extract_max... | [
{
"docstring": "Inserts a key into the priority queue.",
"function_declaration": "def insert(arr, key):",
"function_name": "insert",
"parameter_list": "(arr, key)"
},
{
"docstring": "Extracts the maximum key from the priority queue.",
"function_declaration": "def extract_max(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 insert(arr, key):\n \"\"\"\n Inserts a new key into the max priority queue.\n \"\"\"\n arr.append(key)\n _heapify_up(arr, len(arr) - 1)\n ... | trial_gpt4o_1 | {
"original_instruction": "### Question:\nYou are given an array of integers. Your task is to implement a Max Priority Queue with the following operations using max heap: `insert`, `extract_max`, and `get_max` which must all run in O(log n) time complexity. \n\n#### Function Specifications:\n- **insert(arr, key)**: T... | 0.53921 | Data_Structure_17588 | C | [
"insert",
"extract_max",
"get_max",
"_sift_up",
"_sift_down"
] | 5 | [
[
"extract_max",
"_sift_down"
],
[
"insert",
"_sift_up"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5457c1a88d70e47834970512886f9d434753e3a0 | 9509ced9d990a91c88d5fcbe0d69fe696ec4b1b8 | |||
v1.0 | complete | Data_Structure | Data_Structure_25671_C | from typing import List
import random
def optimized_bogo_sort(arr: List[int], limit: int) -> List[int]:
"""
Sorts the array using an optimized bogo sort method.
Parameters:
arr (List[int]): The array of integers to be sorted.
limit (int): Maximum number of shuffles before switching to determin... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""Helper function to check if the array is sorted"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def shuffle_array(arr: List[int]) -> None:
"""Helper function to randomly shuffle the array in place"""
rando... | from solution import optimized_bogo_sort
def test_sorted_array():
assert optimized_bogo_sort([1, 2, 3], 1000) == [1, 2, 3]
def test_reverse_sorted_array():
assert optimized_bogo_sort([3, 2, 1], 1000) == [1, 2, 3]
def test_random_unsorted_array():
assert optimized_bogo_sort([3, 1, 2], 1000) == [1, 2, 3]
... | [
{
"docstring": "Helper function to check if the array is sorted",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Helper function to randomly shuffle the array in place",
"function_declaration": "def shuffle_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": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Check if the array is sorted.\n \"\"\"\n for i in rang... | trial_gpt4o_2 | {
"original_instruction": "### Bogo Sort Simulation and Optimization\n\nYou are given a theoretical and inefficient sorting algorithm named **Bogo Sort**. This algorithm randomly shuffles the elements of the array until it happens to be sorted. While this algorithm is impractical for general use, it provides an inter... | 0.639837 | Data_Structure_25671 | C | [
"is_sorted",
"shuffle_array",
"optimized_bogo_sort"
] | 3 | [
[
"optimized_bogo_sort",
"is_sorted"
],
[
"optimized_bogo_sort",
"shuffle_array"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 02addb99f2c750ea7a3d430ab0361de57a832be5 | 25441446cb97f5af8eee17a90d3f3b6088d757a0 | |||
v1.0 | complete | Data_Structure | Data_Structure_44399_C | import random
def __choose_state(state_map: dict) -> str:
"""
Helper function that randomly selects the next state based on given probabilities.
>>> state_map = {'A': 0.7, 'B': 0.3}
>>> result = __choose_state(state_map)
"""
pass
def next_state(chain: dict, current_state: str) -> str:
"""
... | import random
def __choose_state(state_map):
"""
Helper function that randomly selects the next state based on given probabilities.
"""
states = list(state_map.keys())
probabilities = list(state_map.values())
next_state = random.choices(states, probabilities)[0]
return next_state
def next_... | from solution import __choose_state, next_state, predictive_typing
def test__choose_state():
state_map = {'A': 0.7, 'B': 0.3}
a_count = b_count = 0
for _ in range(1000):
result = __choose_state(state_map)
if result == 'A':
a_count += 1
elif result == 'B':
b_c... | [
{
"docstring": "Helper function that randomly selects the next state based on given probabilities.",
"function_declaration": "def __choose_state(state_map):",
"function_name": "__choose_state",
"parameter_list": "(state_map)"
},
{
"docstring": "Retrieves the next state using the chain and th... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef __choose_state(state_map: dict) -> str:\n \"\"\"\n Helper function to randomly select the next state based on given probabilities.\... | trial_gpt4o_2 | {
"original_instruction": "### Context\nA company is developing a predictive typing feature where, based on the last word typed by a user, the system suggests the next word. The predictive typing algorithm employs a Markov Chain model. You have been tasked to expand this functionality by allowing the system to genera... | 0.579727 | Data_Structure_44399 | C | [
"__choose_state",
"next_state",
"predictive_typing"
] | 3 | [
[
"next_state",
"__choose_state"
],
[
"predictive_typing",
"next_state"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e404cbffc150cd670467c58c136cba1c45a2c280 | eff5bc33045eea23b3ad3823c02a25ba96d7c51d | |||
v1.0 | complete | Data_Structure | Data_Structure_18122_C | from typing import List
def solve_sudoku(board: List[List[str]]) -> None:
""" Solve the given Sudoku puzzle by filling the empty cells.
The input is a 9x9 grid partially filled with digits 1-9 and empty cells denoted by '.'.
The function modifies the board in-place to a valid Sudoku solution.
Args:
... | from typing import List
def is_valid(board: List[List[str]], row: int, col: int, num: str) -> bool:
"""
Helper function to check whether placing a number in a specific cell is valid.
"""
# Check the row
for j in range(9):
if board[row][j] == num:
return False
# ... | from solution import solve_sudoku
def test_sudoku_solver():
board = [
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["... | [
{
"docstring": "Helper function to check whether placing a number in a specific cell is valid.",
"function_declaration": "def is_valid(board, row, col, num):",
"function_name": "is_valid",
"parameter_list": "(board, row, col, num)"
},
{
"docstring": "Backtracking approach to solve the Sudoku... | [
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 solve_sudoku(board):\n def is_valid(board, row, col, num):\n # Check if num is not in the current row\n for x in range(9):\n i... | trial_gpt4o_2 | {
"original_instruction": "### Sudoku Solver Challenge\n\nYou are given a partially filled 9x9 Sudoku board. Each cell can contain a digit from 1 to 9 or be empty (denoted by '.'). The objective is to fill the empty cells such that every row, column, and 3x3 subgrid contains the digits 1 to 9 without repetition.\n\nW... | 0.551938 | Data_Structure_18122 | C | [
"is_valid",
"solve_sudoku"
] | 2 | [
[
"solve_sudoku",
"is_valid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d0b07a5f2f282c4d0abcae840dd09539d3aa559a | 938dec4c9918b46f555b0809d56df369324c16a1 | |||
v1.0 | complete | Data_Structure | Data_Structure_17401_C | from typing import List
def custom_bitonic_sort(arr: List[int], ascending: bool=True) -> List[int]:
"""
Sorts the array using Bitonic Sort algorithm.
:param arr: List[int] - List of integers to be sorted
:param ascending: bool - Flag to indicate if array should be sorted in ascending order (defaul... | from typing import List
def bitonic_compare_and_swap(arr: List[int], direction: bool, start: int, length: int):
half = length // 2
for i in range(start, start + half):
if (arr[i] > arr[i + half]) == direction:
arr[i], arr[i + half] = arr[i + half], arr[i]
def bitonic_merge(arr: List[int], ... | import pytest
from solution import custom_bitonic_sort
def test_bitonic_sort_ascending():
arr = [3, 7, 4, 8, 6, 2, 1, 5]
sorted_arr = custom_bitonic_sort(arr, True)
assert sorted_arr == [1, 2, 3, 4, 5, 6, 7, 8]
def test_bitonic_sort_descending():
arr = [3, 7, 4, 8, 6, 2, 1, 5]
sorted_arr = custom_... | [
{
"docstring": null,
"function_declaration": "def bitonic_compare_and_swap(arr, direction, start, length):",
"function_name": "bitonic_compare_and_swap",
"parameter_list": "(arr, direction, start, length)"
},
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, direction,... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bitonic_compare_and_swap(arr: List[int], i: int, j: int, ascending: bool):\n if (arr[i] > arr[j]) == ascending:\n arr... | trial_gpt4o_1 | {
"original_instruction": "#### Background\nBitonic Sort is a fast, parallelizable sorting algorithm that works efficiently on arrays of sizes which are a power of two. The main idea is to divide the array into sub-arrays, sort them in opposing orders, and then merge them to form a bitonic sequence that can be recurs... | 0.710351 | Data_Structure_17401 | C | [
"bitonic_compare_and_swap",
"bitonic_merge",
"bitonic_sort_recursive",
"custom_bitonic_sort"
] | 4 | [
[
"bitonic_merge",
"bitonic_compare_and_swap"
],
[
"bitonic_sort_recursive",
"bitonic_merge"
],
[
"custom_bitonic_sort",
"bitonic_sort_recursive"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 2a44994435ea0f65c48de9ddd8ff2a83d50b111a | 588a96a603ebfc719e95200284a9ef7d9e91e8a8 | |||
v1.0 | complete | Data_Structure | Data_Structure_47535_C | from typing import List, Tuple
def max_flow_bottleneck(capacity: List[List[int]], source: int, sink: int) -> Tuple[int, int]:
"""
Compute the maximum flow and bottleneck capacity from source to sink using the Ford-Fulkerson algorithm
enhanced to track and return the bottleneck capacity.
:param capaci... | from typing import List, Tuple
def dfs_find_path(capacity: List[List[int]], flow: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:
visited = [False] * len(capacity)
stack = [source]
visited[source] = True
while stack:
u = stack.pop()
for v in range(len(capacity)):
... | from solution import max_flow_bottleneck
def test_example_case():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert max_flow_bottlenec... | [
{
"docstring": null,
"function_declaration": "def dfs_find_path(capacity, flow, source, sink, parent):",
"function_name": "dfs_find_path",
"parameter_list": "(capacity, flow, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def max_flow_bottleneck(capacity, source,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef max_flow_bottleneck(capacity: List[List[int]], source: int, sink: int) -> Tuple[int, int]:\n def bfs(source: int, sin... | trial_gpt4o_9 | {
"original_instruction": "**Max Flow Problem: BottleNeck Capacity Calculation**\n\n**Scenario:**\nA company is analyzing their transportation network to find out the maximum flow of goods from a main warehouse (source) to retail stores (sink). This network can be represented as a directed graph where nodes represent... | 0.565867 | Data_Structure_47535 | C | [
"dfs_find_path",
"max_flow_bottleneck"
] | 2 | [
[
"max_flow_bottleneck",
"dfs_find_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ea12c39372370f8b2c36afe3052680f82f194b7d | 1efc8031326349f8b138efbc9108e859b518f2ef | |||
v1.0 | complete | Data_Structure | Data_Structure_31607_C | import random
from sympy import isprime, mod_inverse
def generate_prime(bits):
while True:
prime_candidate = random.getrandbits(bits)
if isprime(prime_candidate):
return prime_candidate
def generate_key(bits):
"""
Generate RSA key pair.
Parameters:
bits (int): number o... | import random
from sympy import isprime, mod_inverse
def generate_prime(bits):
while True:
prime_candidate = random.getrandbits(bits)
if isprime(prime_candidate):
return prime_candidate
def generate_key(bits):
"""
Generate RSA key pair.
Parameters:
bits (int): numb... | from solution import generate_key, encrypt, decrypt
def test_key_generation():
n, e, d = generate_key(16)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert e != d
def test_encrypt_decrypt():
n, e, d = generate_key(16)
data = 20
encrypted = encrypt(dat... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bits):",
"function_name": "generate_prime",
"parameter_list": "(bits)"
},
{
"docstring": "Generate RSA key pair.\n\nParameters:\nbits (int): number of bits in modulus n\n\nReturns:\ntuple: (n, e, d) where n is the modulus, e is... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime_candidate(bits):\n p = random.getrandbits(bits)\n # Make sure p is odd\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question:\n\nYou are tasked with implementing your version of RSA key generation and encrypt/decrypt operations. Using the information provided, complete the functions to meet the following requirements:\n\n#### Part 1: Generate Key\nImplement the `generate_key(bits)` function.\n- **Inp... | 0.674193 | Data_Structure_31607 | C | [
"generate_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | f2ecb5dbea325c171c1529c7f8caf55cd59a6ec7 | 2e7a472aff0ab4016fdf885f5f609a8d7f944c81 | |||
v1.0 | complete | Data_Structure | Data_Structure_16624_C | from typing import Tuple, Dict, Any
def k_nearest_neighbors(x: Tuple, tSet: Dict[Tuple, Any], k: int) -> Any:
"""
Find the majority class among the k-nearest neighbors of the point x.
Args:
x (Tuple): A query vector.
tSet (Dict): Training dataset where keys are tuples representing points in the ve... | from collections import Counter
import math
def euclidean_distance(p1, p2):
"""
Computes the Euclidean distance between two points p1 and p2.
p1 and p2 are tuples of the same length.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(p1, p2)))
def k_nearest_neighbors(x: tuple, tSet: dict, k: in... | from solution import k_nearest_neighbors
# Utility function for unit tests
def test_k_nearest_neighbors():
assert k_nearest_neighbors((1, 2), {(0, 0): 'A', (0, 1): 'A', (1, 1): 'B', (2, 3): 'B'}, 2) == 'B'
def test_query_identical_to_point():
assert k_nearest_neighbors((1, 2), {(1, 2): 'A', (2, 3): 'B', (3, 4... | [] | [
0,
0,
0,
1,
0,
1,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import Counter\nimport math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points i... | trial_gpt4o_7 | {
"original_instruction": "### Coding Assessment: Improving the Nearest Neighbor Algorithm\n\n#### Problem Statement\nYou are provided with an implementation of the nearest neighbor classification algorithm. Your task is to improve and extend the provided code in the following ways:\n1. **Optimize Distance Calculatio... | 0.605723 | Data_Structure_16624 | C | [
"euclidean_distance",
"k_nearest_neighbors"
] | 2 | [
[
"k_nearest_neighbors",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0ab1549d0d3ddec71eadd4ddf1daa285a3a1a595 | d3bd1f5dc480c3f3275c25f8d9d65eae546474ae | |||
v1.0 | complete | Data_Structure | Data_Structure_38187_C | from typing import List
def bucket_sort(arr: List[float]) -> List[float]:
"""
Sorts a list of floating-point numbers using the bucket sort algorithm.
>>> bucket_sort([0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51])
[0.23, 0.25, 0.32, 0.42, 0.47, 0.51, 0.52]
>>> bucket_sort([])
[]
... | from typing import List
def insertion_sort(arr: List[float]) -> List[float]:
"""
A simple implementation of insertion sort that will sort the elements in a list.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j... | from solution import bucket_sort
def test_bucket_sort_with_uniform_distribution():
data = [0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51]
assert bucket_sort(data) == [0.23, 0.25, 0.32, 0.42, 0.47, 0.51, 0.52]
def test_bucket_sort_with_empty_array():
assert bucket_sort([]) == []
def test_bucket_sort_with_singl... | [
{
"docstring": "A simple implementation of insertion sort that will sort the elements in a list.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts a list of floating-point numbers using the bucket sort ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport math\n\ndef insertion_sort(arr: List[float]) -> List[float]:\n for i in range(1, len(arr)):\n key = arr[i]\n ... | trial_gpt4o_2 | {
"original_instruction": "**Question: Implement and Optimize Bucket Sort**\n\n### Scenario\nYou are working to improve a data analysis pipeline where large datasets of floating-point numbers need to be sorted efficiently. The data tends to be uniformly distributed across a range, but you also want the solution to gr... | 0.628936 | Data_Structure_38187 | C | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1193f326154069a4fa5d8a10d0895d0be996ae51 | b0812a5431e51451fae17b4d7bb306e244d84dbe | |||
v1.0 | complete | Data_Structure | Data_Structure_28091_C | from typing import List, Tuple
def get_bit(num: int, pos: int) -> int:
"""
Return 1 if the bit at 'pos' is set (1), otherwise return 0.
"""
return (num >> pos) & 1
def set_bit(num: int, pos: int) -> int:
"""
Return an integer with the bit at 'pos' set to 1.
"""
return num | (1 << pos)
... | def get_bit(num, pos):
"""
Return 1 if the bit at 'pos' is set (1), otherwise return 0.
"""
return (num >> pos) & 1
def set_bit(num, pos):
"""
Return an integer with the bit at 'pos' set to 1.
"""
return num | (1 << pos)
def clear_bit(num, pos):
"""
Return an integer with the b... | def test_get_operations():
num = 29 # Binary: 11101
operations = [
('get', 0, 0), # Should return 1
('get', 2, 0), # Should return 1
('get', 3, 0), # Should return 1
('get', 4, 0), # Should return 1
('get', 5, 0) # Should return 0 (out of range but logically 0... | [
{
"docstring": "Return 1 if the bit at 'pos' is set (1), otherwise return 0.",
"function_declaration": "def get_bit(num, pos):",
"function_name": "get_bit",
"parameter_list": "(num, pos)"
},
{
"docstring": "Return an integer with the bit at 'pos' set to 1.",
"function_declaration": "def ... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def process_bits(num: int, operations: list[tuple[str, int, int]]) -> list[int]:\n def get_bit(num, bit_position):\n return (num >> bit_position) & ... | trial_gpt4o_2 | {
"original_instruction": "### Bit Manipulation Enhanced Function\nIn this task, you will use the basic bit manipulation operations to create a more complex function. This function should take an integer `num` and a list of tuples `operations`, where each tuple contains three values indicating the type of operation (... | 0.660832 | Data_Structure_28091 | C | [
"get_bit",
"set_bit",
"clear_bit",
"update_bit",
"process_bits"
] | 5 | [
[
"process_bits",
"clear_bit"
],
[
"process_bits",
"get_bit"
],
[
"process_bits",
"set_bit"
],
[
"process_bits",
"update_bit"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | fcd953865895b57a557c68cbcd902114c73f915d | d1d30a70860ced5b72ae6df5e8ae0c33e260d2aa | |||
v1.0 | complete | Data_Structure | Data_Structure_43936_C | from typing import List
def cosine_similarity_calculator(vec1: List[float], vec2: List[float]) -> float:
pass # To be implemented
def enhanced_cosine_similarity(vec1: list, vec2s: list) -> list:
""" Enhance cosine similarity to handle edge cases and compare multiple vectors.
Args:
vec1: A single ref... | from typing import List
import math
def dot_product(vec1, vec2):
return sum(x * y for x, y in zip(vec1, vec2))
def magnitude(vec):
return math.sqrt(sum(x * x for x in vec))
def cosine_similarity_calculator(vec1, vec2):
mag1 = magnitude(vec1)
mag2 = magnitude(vec2)
if mag1 == 0:
raise... | from solution import enhanced_cosine_similarity, cosine_similarity_calculator
import pytest
def test_enhanced_cosine_similarity_normal_case():
vec1 = [1, 1, 1]
vec2s = [[1, 2, -1], [0, 0, 0], [3, 3, 3]]
result = enhanced_cosine_similarity(vec1, vec2s)
assert result == [0.47140452079103173, None, 1.0]
... | [
{
"docstring": null,
"function_declaration": "def dot_product(vec1, vec2):",
"function_name": "dot_product",
"parameter_list": "(vec1, vec2)"
},
{
"docstring": null,
"function_declaration": "def magnitude(vec):",
"function_name": "magnitude",
"parameter_list": "(vec)"
},
{
... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef enhanced_cosine_similarity(vec1: list, vec2s: list) -> list:\n def vector_norm(vec):\n return math.sqrt(sum(x ** 2 for x in vec))... | trial_gpt4o_8 | {
"original_instruction": "### Coding Challenge: Cosine Similarity Extension\n\n**Objective**:\nGiven the function `cosine_similarity` that calculates the cosine similarity between two vectors, enhance it to handle edge cases more gracefully and to add the capability to compare multiple vectors against a single refer... | 0.545883 | Data_Structure_43936 | C | [
"dot_product",
"magnitude",
"cosine_similarity_calculator",
"enhanced_cosine_similarity"
] | 4 | [
[
"cosine_similarity_calculator",
"dot_product"
],
[
"cosine_similarity_calculator",
"magnitude"
],
[
"enhanced_cosine_similarity",
"cosine_similarity_calculator"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 5e82b31c49310d6a0dbca2868532140256dcbde9 | d0eec7110530cf7b29c63ac3dd02afb72f9fd4a0 | |||
v1.0 | complete | Data_Structure | Data_Structure_31553_C | def merge_sort_optimized(arr: list) -> list:
""" Implements optimized merge sort to sort a list in ascending order.
>>> merge_sort_optimized([12, 4, 5, 6, 7, 3, 1, 15])
[1, 3, 4, 5, 6, 7, 12, 15]
>>> merge_sort_optimized([5, 9, 2, 6, 4, 0, -1, 11])
[-1, 0, 2, 4, 5, 6, 9, 11]
"""
pass
def t... | def merge_sort_optimized(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort_optimized(arr[:mid])
right = merge_sort_optimized(arr[mid:])
return merge(left, right)
def merge(left, right):
merged_array = []
left_index, right_index = 0, 0
while left_index <... | from solution import merge_sort_optimized
def test_empty_list():
assert merge_sort_optimized([]) == []
def test_single_element_list():
assert merge_sort_optimized([5]) == [5]
def test_sorted_list():
assert merge_sort_optimized([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list():
asser... | [
{
"docstring": null,
"function_declaration": "def merge_sort_optimized(arr):",
"function_name": "merge_sort_optimized",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort_optimized(arr: list) -> list:\n \"\"\"\n Perform a memory-optimized merge sort on the input list.\n \"\"\"\n if len(arr) <= 1:\n ... | trial_gpt4o_1 | {
"original_instruction": "Implementing Improved Merge Sort\n\n#### Scenario:\nYou are tasked with optimizing an e-commerce platform's backend system for efficiently sorting large lists of products based on their prices. The platform often needs to handle sorting jobs that involve millions of entries. To achieve this... | 0.569317 | Data_Structure_31553 | C | [
"merge_sort_optimized",
"merge"
] | 2 | [
[
"merge_sort_optimized",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2c58342b3a652ec49881ea6f460eb45d3cfa3f6b | 3b5ebad9f2d2dea1a47b0b88471fef03b0cfdc24 | |||
v1.0 | complete | Data_Structure | Data_Structure_34689_C | def generate_key(k):
"""
Securely generate RSA keys.
This function will generate a modulus, a public exponent, and a private exponent.
Parameters:
k (int): The number of bits in the modulus n.
Returns:
tuple: A tuple (n, e, d) where:
n (int): The modulus.
e (int): The ... | import random
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def modinv(a, m):
m0, x0, x1 = m, 0, 1
if m == 1:
return 0
while a > 1:
q = a // m
m, a = a % m, m
x0, x1 = x1 - q * x0, x0
if x1 < 0:
x1 += m0
return x1
def is_prime(num):
... | from solution import generate_key, encrypt, decrypt
def test_rsa_key_generation():
n, e, d = generate_key(16)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert n > 0
assert e > 0
assert d > 0
def test_rsa_encryption_decryption():
n, e, d = generate_ke... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def modinv(a, m):",
"function_name": "modinv",
"parameter_list": "(a, m)"
},
{
"docstring": null,
"functi... | [
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 gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef modinv(a, m):\n m0, x0, x1 = m, 0, 1\n if m == 1:\n r... | trial_gpt4o_2 | {
"original_instruction": "### RSA Encryption Algorithm Implementation\n\nYou are required to implement a function to securely generate RSA keys and to encrypt/decrypt messages using these keys. The RSA key generation involves selecting two large prime numbers, computing the modulus, and finding modular inverses. You... | 0.773478 | Data_Structure_34689 | C | [
"gcd",
"modinv",
"is_prime",
"get_random_prime",
"generate_key",
"encrypt",
"decrypt"
] | 7 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"get_random_prime"
],
[
"generate_key",
"modinv"
],
[
"get_random_prime",
"is_prime"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 90d4aa969de674f87ce45ef79d35d9f1d5b0a1b0 | 00cf881914bc6198a9d07b518a1c26413d4c8735 | |||
v1.0 | complete | Data_Structure | Data_Structure_47361_C | def find_words(board: List[List[str]], words: List[str]) -> List[str]:
""" Search for words in a given 2D board of characters and returns a list of the words that can be found within the board.
The path can only move horizontally or vertically.
Args:
board (List[List[str]]): A 2D list represen... | from typing import List, Set, Dict, Tuple
class TrieNode:
def __init__(self):
self.children: Dict[str, TrieNode] = {}
self.word: str = None
def build_trie(words: List[str]) -> TrieNode:
root = TrieNode()
for word in words:
node = root
for char in word:
if char n... | from solution import find_words
def test_find_words_example():
board = [
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath", "pea", "eat", "rain"]
result = find_words(board, words)
assert set(result) == {"oath", "eat"}
def t... | [] | [
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": "from typing import List\n\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.is_end_of_word = False\n\nclass Trie:\n def _... | trial_gpt4o_9 | {
"original_instruction": "### Word Search Algorithm Implementation\n\n#### Context\nYou are tasked with developing a system that can find specific words within a matrix of characters, akin to solving a word search puzzle. This involves checking horizontal, vertical paths to find any of the given words. To accomplish... | 0.59843 | Data_Structure_47361 | C | [
"build_trie",
"find_words"
] | 2 | [
[
"find_words",
"build_trie"
]
] | 1 | [] | false | [
"TrieNode"
] | true | pytest | true | [] | true | aed9208c21e2220c60787f66e4a008e13315785a | 51f1be4b07f12d7077f23f08f0265381f26c05b4 | |||
v1.0 | complete | Data_Structure | Data_Structure_43474_C | import random
from sympy import mod_inverse
def generate_key(k: int) -> tuple:
"""
Generate an RSA key pair (n, e, d) based on the provided bit length k.
Parameters:
k (int): The bit length for the modulus n.
Returns:
tuple: A tuple containing n (modulus), e (public exponent), and d (... | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(k):
""" Generate an odd integer randomly """
p = random.getrandbits(k)
# Apply a mask to set MSB and LSB to 1
p |= (1 << k - 1) | 1
return p
def generate_prime_number(k):
""" Generate a prime number of k bits """... | from solution import generate_key, encrypt, decrypt, rsa_operations
def test_generate_key():
n, e, d = generate_key(8)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_encrypt_decrypt():
n, e, d = generate_key(8)
original_data = 45
encrypted_data = enc... | [
{
"docstring": "Generate an odd integer randomly ",
"function_declaration": "def generate_prime_candidate(k):",
"function_name": "generate_prime_candidate",
"parameter_list": "(k)"
},
{
"docstring": "Generate a prime number of k bits ",
"function_declaration": "def generate_prime_number(... | [
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 sympy import isprime, mod_inverse\n\ndef generate_prime_candidate(k):\n \"\"\" Generate an odd integer randomly \"\"\"\n p = random.... | trial_gpt4o_0 | {
"original_instruction": "### RSA Key Generation and Encryption/Decryption Implementation\n\nUsing the principles of the RSA algorithm, implement a solution to generate an RSA key pair based on provided bit length `k`. Then, develop functions to encrypt and decrypt messages.\n\n#### Input:\n1. `k` (int): The bit len... | 0.705957 | Data_Structure_43474 | C | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt",
"rsa_operations"
] | 6 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
],
[
"rsa_operations",
"decrypt"
],
[
"rsa_operations",
"encrypt"
],
[
"rsa_operations",
"generate_key"
]
] | 5 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | a6be0a21f0207960f9c771a4002ce40ec382e56a | d0cad3096ca82c2c9b8f9c7cb31cfef21d295709 | |||
v1.0 | complete | Data_Structure | Data_Structure_37865_C | def mod_exponentiation(a: int, n: int, mod: int = None) -> int:
"""
Computes the power of a given integer with an optional modulo in an optimized manner.
If `mod` is not provided, returns the computed value of a^n.
If `mod` is provided, returns the computed value of a^n % mod.
Args:
a... | def mod_exponentiation(a: int, n: int, mod: int = None) -> int:
"""
Computes a^n efficiently. If `mod` is provided, computes a^n % mod.
"""
if mod is None:
return _mod_exponentiation(a, n)
else:
return _mod_exponentiation_with_mod(a, n, mod)
def _mod_exponentiation(a: int, n: in... | from solution import mod_exponentiation
def test_mod_exponentiation_no_mod():
assert mod_exponentiation(2, 10) == 1024
def test_mod_exponentiation_with_mod():
assert mod_exponentiation(2, 10, 1000) == 24
def test_mod_exponentiation_larger_base():
assert mod_exponentiation(3, 18) == 387420489
def test_mo... | [
{
"docstring": "Computes a^n efficiently. If `mod` is provided, computes a^n % mod.",
"function_declaration": "def mod_exponentiation(a, n, mod=None):",
"function_name": "mod_exponentiation",
"parameter_list": "(a, n, mod=None)"
},
{
"docstring": "Computes a^n using binary exponentiation.",
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def mod_exponentiation(a: int, n: int, mod: int = None) -> int:\n if n == 0:\n return 1 if mod is None else 1 % mod\n\n result = 1\n base = a\... | trial_gpt4o_2 | {
"original_instruction": "### Context\nTo verify the understanding of binary exponentiation and its applications, especially in contexts involving large numbers, you'll implement an advanced function. This function should compute a value efficiently using properties of exponentiation and modular arithmetic.\n\n### P... | 0.665761 | Data_Structure_37865 | C | [
"mod_exponentiation",
"_mod_exponentiation",
"_mod_exponentiation_with_mod"
] | 3 | [
[
"mod_exponentiation",
"_mod_exponentiation"
],
[
"mod_exponentiation",
"_mod_exponentiation_with_mod"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2703bcfb4e747b988e738c3798d5cd903795cbdb | 5e287d96d45aaa4722eadcbc11efb0febcb326d2 | |||
v1.0 | complete | Data_Structure | Data_Structure_41540_C | from typing import List, Callable
def enhanced_merge_sort(arr: List[int], compare: Callable[[int, int], int]) -> List[int]:
"""
Iterative bottom-up merge sort that uses a custom comparator function.
Example:
>>> def comparator(a, b):
... return b - a
>>> arr = [3, 1, 4, 1, 5, 9, 2, 6, ... | from typing import List, Callable
def enhanced_merge_sort(arr: List[int], compare: Callable[[int, int], int]) -> List[int]:
"""
Iterative bottom-up merge sort that uses a custom comparator function.
"""
n = len(arr)
width = 1
temp = arr[:]
while width < n:
for i in range(0, n, ... | from solution import enhanced_merge_sort
def comparator_ascending(a, b):
return a - b
def comparator_descending(a, b):
return b - a
def test_enhanced_merge_sort_ascending():
arr = [4, 2, 7, 1, 9, 3]
sorted_arr = enhanced_merge_sort(arr, comparator_ascending)
assert sorted_arr == [1, 2, 3, 4, 7, 9... | [
{
"docstring": "Iterative bottom-up merge sort that uses a custom comparator function.",
"function_declaration": "def enhanced_merge_sort(arr, compare):",
"function_name": "enhanced_merge_sort",
"parameter_list": "(arr, compare)"
},
{
"docstring": null,
"function_declaration": "def merge... | [
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, Callable\n\ndef merge(arr: List[int], aux: List[int], left: int, mid: int, right: int, compare: Callable[[int, int], int]) -> None:\n... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement an Enhanced Merge Sort\n\nMerge Sort is a classic divide-and-conquer algorithm for sorting an array of numbers. We have provided a simplified version of the Merge Sort algorithm that sorts an array in ascending order. For this task, you are required to enhance and im... | 0.573673 | Data_Structure_41540 | C | [
"enhanced_merge_sort",
"merge"
] | 2 | [
[
"enhanced_merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7b8c43b83c168f84eb04e2f590cb186e984f832f | 1b7ee6ba3b4ce266951ced39be981179eb528d1f | |||
v1.0 | complete | Docs | Docs: Scikit_3_C | import pandas as pd
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def stream_data(file_path, chunk_size):
"""
A generator function to read the CSV file in chunks of size `chunk_size`.
Args:
... | import pandas as pd
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def stream_data(file_path, chunk_size):
"""
A generator function to read the CSV file in chunks of size `chunk_size`.
"""
for chunk... | import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
from io import StringIO
import pytest
def stream_data(file_path, chunk_size):
for chunk in pd.read_csv(file_path, chunksize=... | [
{
"docstring": "A generator function to read the CSV file in chunks of size `chunk_size`.",
"function_declaration": "def stream_data(file_path, chunk_size):",
"function_name": "stream_data",
"parameter_list": "(file_path, chunk_size)"
},
{
"docstring": "Train the classifier incrementally on ... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy... | trial_gpt4o_0 | {
"original_instruction": "You are tasked with building an out-of-core learning system to classify a large dataset that cannot fit into memory. The dataset is in CSV format and is stored on disk. Implement a solution that uses out-of-core learning to read the data in chunks, process it, and train an incremental class... | 0.690545 | Docs: Scikit_3 | C | [
"stream_data",
"train_incremental_classifier"
] | 2 | [
[
"train_incremental_classifier",
"stream_data"
]
] | 1 | [] | false | [] | false | pytest | false | [
"numpy",
"pandas",
"sklearn"
] | false | ca4ed834dfb4423c17692184c0cc7b37e48c8d4b | cc93e301243f184da0ea8e491730cfae07cf577a | |||
v1.0 | complete | Docs | Docs: Python310_63_C | import tracemalloc
import linecache
import runpy
def profile_memory(file_path: str) -> None:
"""
Use the tracemalloc module to profile memory usage in a Python script and identify potential memory leaks or inefficiencies.
Prints the top 10 lines in the script that allocate the most memory and the top 10 di... | import tracemalloc
import linecache
import runpy
def display_top(snapshot, key_type='lineno', limit=10):
snapshot = snapshot.filter_traces((
tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
tracemalloc.Filter(False, "<unknown>"),
))
top_stats = snapshot.statistics(key_type)
... | import pytest
import os
def test_profile_memory_output():
# Create a sample script for testing
script_content = """\
def main():
some_variable = [i for i in range(1000000)]
another_variable = [j for j in range(500000)]
if __name__ == "__main__":
main()
"""
script_path = "memory_hog_test.py... | [
{
"docstring": null,
"function_declaration": "def display_top(snapshot, key_type='lineno', limit=10):",
"function_name": "display_top",
"parameter_list": "(snapshot, key_type='lineno', limit=10)"
},
{
"docstring": null,
"function_declaration": "def profile_memory(file_path):",
"funct... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import tracemalloc\nimport runpy\n\ndef profile_memory(file_path: str) -> None:\n tracemalloc.start(10)\n \n # Snapshot before running the script\n snapshot... | trial_gpt4o_2 | {
"original_instruction": "**Advanced Memory Profiling with `tracemalloc`**\n\n### Objective:\nUse Python's `tracemalloc` module to profile memory usage in a Python script and identify potential memory leaks or inefficiencies.\n\n### Problem Statement:\nYou are given a Python script `memory_hog.py` which you suspect ... | 0.550413 | Docs: Python310_63 | C | [
"display_top",
"profile_memory"
] | 2 | [
[
"profile_memory",
"display_top"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 955666828d75ee283dd504f34c0c8198611810f9 | 1a63d104c6d122e4d87ac1159156c45deabfd1ee | |||
v1.0 | complete | Docs | Docs: Python310_86_C | import argparse
import sys
def read_numbers(filename):
""" Read numbers from a file. Each line of the file contains one number.
Args:
filename (str): The name of the file to read.
Returns:
list: A list of numbers.
"""
def calculate_mean(numbers):
""" Calculate the mean of a list of... | import argparse
import sys
def read_numbers(filename):
try:
with open(filename, 'r') as file:
numbers = [float(line.strip()) for line in file.readlines()]
return numbers
except FileNotFoundError:
print(f"Error: File {filename} not found.")
sys.exit(1)
except Valu... | import pytest
from solution import *
def test_calculate_mean():
numbers = [1, 2, 3, 4, 5]
assert calculate_mean(numbers) == 3.0
def test_calculate_median():
numbers = [1, 2, 3, 4, 5]
assert calculate_median(numbers) == 3.0
numbers = [1, 2, 3, 4, 5, 6]
assert calculate_median(numbers) == 3.5
d... | [
{
"docstring": null,
"function_declaration": "def read_numbers(filename):",
"function_name": "read_numbers",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def calculate_mean(numbers):",
"function_name": "calculate_mean",
"parameter_list": "(numbe... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import argparse\nimport sys\n\ndef read_numbers(filename):\n try:\n with open(filename, 'r') as file:\n numbers = [float(line.strip()) for line in ... | trial_gpt4o_1 | {
"original_instruction": "### Command-Line Data Analysis Tool\n\nIn this task, you are required to implement a command-line data analysis tool using Python. Your task is to use the `argparse` module to create a script that accepts several command-line arguments to perform basic data analysis on a dataset of numbers ... | 0.699059 | Docs: Python310_86 | C | [
"read_numbers",
"calculate_mean",
"calculate_median",
"calculate_mode",
"calculate_variance",
"main"
] | 6 | [
[
"calculate_variance",
"calculate_mean"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 87141ea4e3dffc4eec1ca9d8c26b06e06407b223 | d265bb999de9c026fe6a2e1ca4272dd3fc071efe | |||
v1.0 | complete | Docs | Docs: Python310_127_C | import threading
import queue
from typing import List, Tuple, Any
def enqueue_tasks(task_data: List[Tuple[int, Any]], task_queue: queue.PriorityQueue) -> None:
"""
Enqueues all tasks from task_data into task_queue.
"""
for task in task_data:
task_queue.put(task)
def worker(task_queue: queue.Pr... | import threading
import queue
from typing import List, Tuple, Any
def enqueue_tasks(task_data: List[Tuple[int, Any]], task_queue: queue.PriorityQueue) -> None:
"""
Enqueues all tasks from task_data into task_queue.
"""
for task in task_data:
task_queue.put(task)
def worker(task_queue: queue.Pr... | import queue
import threading
from solution import enqueue_tasks, worker, start_task_manager
def test_enqueue_tasks():
task_data = [(1, "Task 1"), (3, "Task 3"), (2, "Task 2")]
task_queue = queue.PriorityQueue()
enqueue_tasks(task_data, task_queue)
assert not task_queue.empty()
assert task_que... | [
{
"docstring": "Enqueues all tasks from task_data into task_queue.",
"function_declaration": "def enqueue_tasks(task_data, task_queue):",
"function_name": "enqueue_tasks",
"parameter_list": "(task_data, task_queue)"
},
{
"docstring": "Worker thread function that processes tasks from task_que... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import threading\nimport queue\nfrom typing import List, Tuple, Any\n\ndef enqueue_tasks(task_data: List[Tuple[int, Any]], task_queue: queue.PriorityQueue) -> None:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Multi-Threaded Task Manager using Python `queue` Module\n\nYou are tasked to create a multi-threaded task manager simulation using the `queue` module. The task manager will handle tasks with different priorities and ensure they are processed correctly by worker threads. You wi... | 0.681642 | Docs: Python310_127 | C | [
"enqueue_tasks",
"worker",
"start_task_manager"
] | 3 | [
[
"start_task_manager",
"enqueue_tasks"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ca183ae23d8c26c70538622bf937b5fdab848aa2 | 000eb4e8558b399a6f8401f2854c9add4f075e8c | |||
v1.0 | complete | Docs | Docs: Python310_143_C | import traceback
import sys
def log_exception(file_path: str, limit: int = None) -> None:
"""
Logs the current exception's stack trace and details to the specified file.
Parameters:
file_path (str): The path to the log file where the exception details will be written.
limit (int, optional): The ma... | import traceback
import sys
def log_exception(file_path: str, limit: int = None) -> None:
"""
Logs the current exception's stack trace and details to the specified file.
Parameters:
file_path (str): The path to the log file where the exception details will be written.
limit (int, optional): The ma... | import os
import pytest
from solution import log_exception, exception_logger
def test_log_exception():
log_file = 'test_log_exception.txt'
try:
1 / 0
except ZeroDivisionError:
log_exception(log_file)
with open(log_file, 'r') as f:
log_contents = f.read()
assert "ZeroDi... | [
{
"docstring": "Logs the current exception's stack trace and details to the specified file.\n\nParameters:\nfile_path (str): The path to the log file where the exception details will be written.\nlimit (int, optional): The maximum number of stack trace entries to include.",
"function_declaration": "def log_... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import traceback\nimport sys\n\ndef log_exception(file_path: str, limit: int = None) -> None:\n \"\"\"\n Logs the current exception to the specified file path.\n ... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with creating a custom error-handling and logging system using Python's `traceback` module. The goal is to capture exceptions, format the stack trace, and log the formatted trace to a file for later analysis.\n\n#### Requirements\n\n1. **Function Implementation**:\n - Impl... | 0.528337 | Docs: Python310_143 | C | [
"log_exception",
"exception_logger"
] | 2 | [
[
"exception_logger",
"log_exception"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5722ad193f7e7357e9f0768ef6937bce8e02ffbb | 42efd5beb30c67b4ff9cdd98460bcb8fa48be836 | |||
v1.0 | complete | Docs | Docs: Python310_247_C | import tkinter as tk
from tkinter import filedialog, simpledialog, messagebox
def save_string_to_file(directory, input_string):
"""
Saves the given input string to a text file within the specified directory.
"""
if not directory or not input_string:
raise ValueError("Both directory and input st... | import tkinter as tk
from tkinter import filedialog, simpledialog, messagebox
import os
def save_string_to_file(directory, input_string):
"""
Saves the given input string to a text file within the specified directory.
"""
if not directory or not input_string:
raise ValueError("Both directory an... | import pytest
import os
import tempfile
from solution import save_string_to_file
def test_save_string_to_file_success():
# Create a temporary directory
with tempfile.TemporaryDirectory() as tempdir:
# Test data
input_string = "Hello, World!"
file_path = save_string_to_file(tempdir, inpu... | [
{
"docstring": "Saves the given input string to a text file within the specified directory.",
"function_declaration": "def save_string_to_file(directory, input_string):",
"function_name": "save_string_to_file",
"parameter_list": "(directory, input_string)"
},
{
"docstring": "Initializes the ... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import tkinter as tk\nfrom tkinter import filedialog, simpledialog, messagebox\n\ndef save_input_to_file(directory, input_string):\n \"\"\"\n Saves the input stri... | trial_gpt4o_7 | {
"original_instruction": "## Coding Assessment Question\n\n### Objective\nCreate a Python program using the `tkinter` package to develop a GUI application that allows the user to:\n1. Select a directory.\n2. Input a string value.\n3. Save the input string to a text file within the selected directory.\n\n### Requirem... | 0.44067 | Docs: Python310_247 | C | [
"save_string_to_file",
"create_gui"
] | 2 | [
[
"create_gui",
"save_string_to_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9c4c7e030b5ffae64196b456ddbf362cf238ae1b | 086a9bc3a48e0b944b409c1532aa9c86b6ffaf5e | |||
v1.0 | complete | Docs | Docs: Python310_162_C | import asyncio
import sys
async def cross_platform_asyncio_support(host: str, port: int) -> str:
""" Demonstrates cross-platform asyncio support by performing a network operation using a TCP socket.
Handles platform-specific event loop constraints for both Windows and macOS.
Args:
host (str): The ... | import asyncio
import sys
async def cross_platform_asyncio_support(host: str, port: int) -> str:
# Check the platform and set the appropriate event loop policy
if sys.platform.startswith('win'):
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
else:
loop = asyncio.get... | import asyncio
import pytest
import sys
from solution import cross_platform_asyncio_support
@pytest.mark.asyncio
async def test_cross_platform_asyncio_support_success():
result = await cross_platform_asyncio_support('example.com', 80)
assert "Successfully performed network operation." in result or "Operation f... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport sys\n\nasync def cross_platform_asyncio_support(host: str, port: int) -> str:\n try:\n # Handle platform-specific event loop policy\n ... | trial_gpt4o_1 | {
"original_instruction": "### Advanced Python Coding Assessment: `asyncio` Platform Compatibility\n\n**Objective:** To evaluate your understanding of the `asyncio` package and its platform-specific limitations. You are required to write code demonstrating comprehension and handling of these constraints.\n\n#### Prob... | 0.477743 | Docs: Python310_162 | C | [
"cross_platform_asyncio_support",
"main_test"
] | 2 | [
[
"main_test",
"cross_platform_asyncio_support"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 630f3ec341e40d5c157119826e61054cd9bff029 | 45f559ebc6da52cd0b4d66f51bc53e0d4bea101a | |||
v1.0 | complete | Docs | Docs: Seaborn_142_C | import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
import matplotlib as mpl
def generate_custom_palette(cmap_name: str, n_colors: int, as_cmap: bool) -> any:
""" Generates and returns a matplotlib colormap or a list of colors based on the given parameters.
Paramet... | import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
import matplotlib as mpl
def generate_custom_palette(cmap_name: str, n_colors: int, as_cmap: bool) -> any:
"""
Generates and returns a matplotlib colormap or a list of colors based on the given parameters.
Par... | from solution import generate_custom_palette
import seaborn as sns
import matplotlib as mpl
def test_generate_custom_palette_as_list():
palette = generate_custom_palette("viridis", 5, False)
assert isinstance(palette, list)
assert len(palette) == 5
def test_generate_custom_palette_as_cmap():
colormap ... | [
{
"docstring": "Generates and returns a matplotlib colormap or a list of colors based on the given parameters.\n\nParameters:\n- cmap_name (str): Name of the colormap.\n- n_colors (int): Number of colors to sample from the colormap.\n- as_cmap (bool): If True, return the colormap as a continuous colormap, other... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef generate_custom_palette(cmap_name: str, n_colors: int, as_cmap: bool):\n \"\"\"\n Generates a custom... | trial_gpt4o_1 | {
"original_instruction": "#### Objective:\nDemonstrate your understanding of seaborn color palettes and plot customization using the `sns.mpl_palette` function.\n\n#### Task:\n1. Write a function `generate_custom_palette` that generates and returns a matplotlib colormap based on the parameters given.\n2. Create a sc... | 0.722905 | Docs: Seaborn_142 | C | [
"generate_custom_palette",
"plot_with_custom_palette"
] | 2 | [
[
"plot_with_custom_palette",
"generate_custom_palette"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"seaborn",
"sklearn"
] | false | 0d4705ca0c3b2154e58b801ff1d25963fb850e30 | 5b8934f45549302c851e796c672993df5ae8bc94 | |||
v1.0 | complete | Docs | Docs: Python310_358_C | import asyncio
import random
async def simulate_multiple_requests(num_requests: int) -> list:
""" Use the asyncio module to coordinate multiple asynchronous tasks to simulate a scenario where multiple clients request data from a server simultaneously.
Args:
num_requests (int): The number of client req... | import asyncio
import random
async def get_server_response() -> int:
await asyncio.sleep(random.randint(1, 3))
return random.randint(1, 100)
async def process_response(response: int) -> int:
await asyncio.sleep(0) # Simulate processing time
return response * 2
async def simulate_multiple_requests(nu... | import asyncio
from solution import simulate_multiple_requests
async def test_simulate_multiple_requests_single():
results = await simulate_multiple_requests(1)
assert len(results) == 1
assert all(isinstance(result, int) for result in results)
assert all(2 <= result <= 200 for result in results)
async... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\n\nasync def get_server_response() -> int:\n await asyncio.sleep(random.randint(1, 3))\n return random.randint(1, 100)\n\nasync def ... | trial_gpt4o_1 | {
"original_instruction": "**Asynchronous Task Coordination using `asyncio`**\n\n**Objective:**\nImplement a function that coordinates multiple asynchronous tasks using the `asyncio` module to simulate a scenario where multiple clients request data from a server simultaneously.\n\n**Problem Statement:**\nYou are requ... | 0.549161 | Docs: Python310_358 | C | [
"get_server_response",
"process_response",
"simulate_multiple_requests"
] | 3 | [
[
"simulate_multiple_requests",
"get_server_response"
],
[
"simulate_multiple_requests",
"process_response"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 01929b1c58906557157da3cd47ff4b4d34f89452 | d42cabdb3278cbfceb2fd2e615556a8c9096f4e7 | |||
v1.0 | complete | Docs | Docs: Python310_336_C | import os
import pwd
import grp
import resource
import syslog
def create_user_with_limits(username: str, groupname: str, cpu_limit: int, memory_limit: int) -> None:
"""
Creates a new user on a Unix system, assigns this user to a new group,
and logs this activity using the Unix syslog facility. Additionally... | import os
import pwd
import grp
import resource
import syslog
def create_user_with_limits(username, groupname, cpu_limit, memory_limit):
try:
# Create a new group
if not group_exists(groupname):
os.system(f"groupadd {groupname}")
else:
raise Exception(f"Group {groupn... | import pytest
from unittest.mock import patch, call
from solution import create_user_with_limits, group_exists, user_exists
def test_group_exists():
with patch('grp.getgrnam') as mock_getgrnam:
mock_getgrnam.side_effect = lambda x: x
assert group_exists('existinggroup')
mock_getgrnam.assert... | [
{
"docstring": null,
"function_declaration": "def create_user_with_limits(username, groupname, cpu_limit, memory_limit):",
"function_name": "create_user_with_limits",
"parameter_list": "(username, groupname, cpu_limit, memory_limit)"
},
{
"docstring": null,
"function_declaration": "def g... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport syslog\nimport pwd\nimport grp\nimport subprocess\n\ndef create_user_with_limits(username, groupname, cpu_limit, memory_limit):\n try:\n # C... | trial_gpt4o_2 | {
"original_instruction": "#### Problem Description\n\nYou are required to implement a function that creates a new user on a Unix system, assigns this user to a new group, and logs this activity using the Unix syslog facility. Additionally, the function should set resource limits for the newly created user to restric... | 0.430897 | Docs: Python310_336 | C | [
"create_user_with_limits",
"group_exists",
"user_exists"
] | 3 | [
[
"create_user_with_limits",
"group_exists"
],
[
"create_user_with_limits",
"user_exists"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cadae68b5768dd066a85e093980ec70b25566b72 | ae875cf46d85612285a71b67e1c2614e250a81ef | |||
v1.0 | complete | Docs | Docs: Pytorch_347_C | import torch
from typing import List, Tuple
def async_task_simulation(task_id: int, delay: float) -> torch.futures.Future:
"""Simulate an asynchronous task that waits for a given amount of time before returning a result.
Args:
task_id (int): An identifier for the task.
delay (float): The time in s... | import torch
import time
import threading
def async_task_simulation(task_id, delay):
future = torch.futures.Future()
def task():
time.sleep(delay)
future.set_result((task_id, f'Result from task {task_id}'))
threading.Thread(target=task).start()
return future
def process_all_t... | from solution import async_task_simulation, process_all_tasks
import torch
import time
def test_async_task_simulation():
future = async_task_simulation(1, 0.1)
result = future.wait()
assert result == (1, 'Result from task 1')
def test_process_all_tasks():
n = 3
delays = [0.1, 0.2, 0.3]
results... | [
{
"docstring": null,
"function_declaration": "def async_task_simulation(task_id, delay):",
"function_name": "async_task_simulation",
"parameter_list": "(task_id, delay)"
},
{
"docstring": null,
"function_declaration": "def process_all_tasks(n, delays):",
"function_name": "process_all... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport time\nimport concurrent.futures\nfrom typing import List, Tuple\n\ndef async_task_simulation(task_id, delay):\n future = torch.futures.Future()\... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with implementing a function that simulates a set of asynchronous tasks using the `torch.futures.Future` class, and processes their results once all tasks are completed.\n\nFirstly, you need to write a function `async_task_simulation` that creates `n` asynchronous tasks. Each... | 0.668767 | Docs: Pytorch_347 | C | [
"async_task_simulation",
"process_all_tasks"
] | 2 | [
[
"process_all_tasks",
"async_task_simulation"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | fb9230f0b9da07975c5fad7ef8a98cbd0ed80859 | 570c014c2a913c630ff3e74d50567f93fc235bed | |||
v1.0 | complete | Docs | Docs: Python310_333_C | import codecs
class CaesarCodec(codecs.Codec):
def encode(self, input, errors='strict'):
"""Encode the input string using the Caesar cipher with shift of 3"""
pass
def decode(self, input, errors='strict'):
"""Decode the input string using the Caesar cipher with shift of 3"""
pa... | import codecs
class CaesarCodec(codecs.Codec):
def encode(self, input, errors='strict'):
output = []
for char in input:
if 'a' <= char <= 'z':
output.append(chr((ord(char) - ord('a') + 3) % 26 + ord('a')))
elif 'A' <= char <= 'Z':
output.appen... | def test_custom_encode_simple():
assert custom_encode("abc") == "def"
assert custom_encode("xyz") == "abc"
assert custom_encode("ABC") == "DEF"
assert custom_encode("XYZ") == "ABC"
def test_custom_encode_with_non_alpha_chars():
assert custom_encode("Hello, World!") == "Khoor, Zruog!"
assert cus... | [] | [
0,
1,
0,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import codecs\n\nclass CaesarCodec(codecs.Codec):\n def encode(self, input, errors='strict'):\n output = []\n for char in inpu... | trial_gpt4o_8 | {
"original_instruction": "### Custom Codec Implementation and Error Handling in Python\n\n#### Objective:\nDemonstrate your understanding of custom codec implementation, error handling, and the use of the `codecs` module in Python.\n\n#### Problem Statement:\nYou are to implement a custom codec to encode and decode ... | 0.542787 | Docs: Python310_333 | C | [
"rot13_error_handler",
"caesar_shift",
"custom_encode",
"custom_decode"
] | 4 | [
[
"rot13_error_handler",
"caesar_shift"
]
] | 1 | [] | false | [
"CaesarCodec"
] | true | pytest | false | [] | true | 05b19365c92a453a1430d962de8562eaf64c5038 | 511dedf85f5b58633f6495f07845a89cb75fef5f | |||
v1.0 | complete | Docs | Docs: Python310_512_C | class Cell:
"""
Class representing a cell object, which holds a single value.
"""
def __init__(self, value):
self.value = value
def is_cell(obj):
"""
Checks if the provided object is an instance of the Cell class.
"""
pass
def new_cell(value):
"""
Creates a new Cell obj... | class Cell:
"""
Class representing a cell object, which holds a single value.
"""
def __init__(self, value):
self.value = value
def is_cell(obj):
"""
Checks if the provided object is an instance of the Cell class.
"""
return isinstance(obj, Cell)
def new_cell(value):
"""
... | from solution import Cell, is_cell, new_cell, get_cell_value, set_cell_value
def test_is_cell():
cell = new_cell(10)
assert is_cell(cell) == True
assert is_cell(10) == False
assert is_cell("not a cell") == False
def test_new_cell():
cell = new_cell(42)
assert is_cell(cell) == True
assert c... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Cell:\n \"\"\"\n A class representing a cell object, which can store a single value.\n \"\"\"\n def __init__(self, value):\n self._value = valu... | trial_gpt4o_2 | {
"original_instruction": "### Cell Object Operations in Python\n\n**Objective**:\nImplement a few function simulations for manipulating cell objects, reflecting the documented C-API behavior in Python.\n\n**Problem Statement**:\nYou are required to emulate the behavior of \"cell\" objects and provide functions to ma... | 0.433254 | Docs: Python310_512 | C | [
"is_cell",
"new_cell",
"get_cell_value",
"set_cell_value"
] | 4 | [
[
"get_cell_value",
"is_cell"
],
[
"set_cell_value",
"is_cell"
]
] | 2 | [] | false | [
"Cell"
] | true | pytest | true | [] | true | a5021e3600c4a7d85e426295264143019c567e6a | 4772c962bf1e8ae3f014698a27284f832fac4d7b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.