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_47089_C | def matrix_transform(matrix, operation):
"""
Perform the specified transformation on a 2D matrix.
The operation parameter can be one of the following:
- "rotate_clockwise": Rotate the matrix 90 degrees clockwise.
- "rotate_counterclockwise": Rotate the matrix 90 degrees counterclockwise.
... | def rotate_clockwise(matrix):
n = len(matrix)
new_matrix = [[0]*n for _ in range(n)]
for i in range(n):
for j in range(n):
new_matrix[j][n-1-i] = matrix[i][j]
return new_matrix
def rotate_counterclockwise(matrix):
n = len(matrix)
new_matrix = [[0]*n for _ in range(n)]
fo... | from solution import matrix_transform
def test_rotate_clockwise():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
expected = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3],
]
assert matrix_transform(matrix, "rotate_clockwise") == expected
def test_rotate_countercl... | [
{
"docstring": null,
"function_declaration": "def rotate_clockwise(matrix):",
"function_name": "rotate_clockwise",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def rotate_counterclockwise(matrix):",
"function_name": "rotate_counterclockwise",
"par... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_transform(matrix, operation):\n def rotate_clockwise(mat):\n return [list(reversed(col)) for col in zip(*mat)]\n\n def rotate_counterc... | trial_gpt4o_2 | {
"original_instruction": "You are given four matrix transformation functions: `rotate_clockwise`, `rotate_counterclockwise`, `top_left_invert`, and `bottom_left_invert`. These functions perform various 2D matrix manipulations either by rotating or inverting the matrix.\n\nYour task is to write a function:\n\n```pyth... | 0.521309 | Data_Structure_47089 | C | [
"rotate_clockwise",
"rotate_counterclockwise",
"top_left_invert",
"bottom_left_invert",
"matrix_transform"
] | 5 | [
[
"matrix_transform",
"bottom_left_invert"
],
[
"matrix_transform",
"rotate_clockwise"
],
[
"matrix_transform",
"rotate_counterclockwise"
],
[
"matrix_transform",
"top_left_invert"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | fe7f547f6b77ea060fdc9b52b63d409feb996413 | 11c57d845a6f6189fab67aeeb0ed0da035deafeb | |||
v1.0 | complete | Data_Structure | Data_Structure_47678_C | def dynamic_gnome_sort(initial_list, new_elements):
""" Adds elements from new_elements to initial_list one by one,
sorting the list using Gnome Sort after each addition.
Args:
initial_list (List[int]): A list of integers pre-sorted in ascending order.
new_elements (List[int]): A list of intege... | def gnome_sort(arr):
"""
Performs Gnome Sort on the list.
"""
index = 0
while index < len(arr):
if index == 0 or arr[index] >= arr[index - 1]:
index += 1
else:
arr[index], arr[index - 1] = arr[index - 1], arr[index]
index -= 1
return arr
def d... | from solution import dynamic_gnome_sort
def test_already_sorted():
assert dynamic_gnome_sort([1, 2, 3], [4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_ordered_inserts():
assert dynamic_gnome_sort([1, 2, 3], [6, 5, 4]) == [1, 2, 3, 4, 5, 6]
def test_inserts_causing_shuffles():
assert dynamic_gnome_sort([1, 3... | [
{
"docstring": "Performs Gnome Sort on the list.",
"function_declaration": "def gnome_sort(arr):",
"function_name": "gnome_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Adds elements from new_elements to initial_list one by one,\nsorting the list using Gnome Sort after each addition.",... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gnome_sort(arr):\n index = 0\n while index < len(arr):\n if index == 0:\n index += 1\n if arr[index] >= arr[index - 1]:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Gnome Sort in a Dynamic List Scenario\n\nYou are given the task of implementing a sorting function using the Gnome Sort algorithm. As a part of this, you need to ensure the function can handle being given in a dynamic list scenario: elements might be frequently added to the list, and yo... | 0.642019 | Data_Structure_47678 | C | [
"gnome_sort",
"dynamic_gnome_sort"
] | 2 | [
[
"dynamic_gnome_sort",
"gnome_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 40a697a7a691efaaacdd67541d6e43ba6711663b | 9d7b34911ff4bba20801d26af1a2134c59166640 | |||
v1.0 | complete | Data_Structure | Data_Structure_47440_C | def vector_to_index_value_list(vector):
"""
Converts a vector into an efficient storage structure by keeping index-value pairs of non-zero elements.
"""
pass
def sparse_vector_dot_product(vector1, vector2):
"""
Computes the dot product of two sparse vectors represented by lists of floating-poin... | def vector_to_index_value_list(vector):
"""
Converts a vector into an efficient storage structure by keeping index-value pairs of non-zero elements.
"""
return [(i, v) for i, v in enumerate(vector) if v != 0.0]
def sparse_vector_dot_product(vector1, vector2):
"""
Computes the dot product of two... | from solution import sparse_vector_dot_product
def test_example_cases():
assert sparse_vector_dot_product([1.0, 2.0, 3.0], [0.0, 2.0, 2.0]) == 10.0
assert sparse_vector_dot_product([], [0.0, 2.0, 0.0]) == 0.0
assert sparse_vector_dot_product([0.0, 0.0, 0.0], [0.0, 0.0, 0.0]) == 0.0
assert sparse_vector... | [
{
"docstring": "Converts a vector into an efficient storage structure by keeping index-value pairs of non-zero elements.",
"function_declaration": "def vector_to_index_value_list(vector):",
"function_name": "vector_to_index_value_list",
"parameter_list": "(vector)"
},
{
"docstring": "Compute... | [
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 vector_to_index_value_list(vector):\n \"\"\"\n Converts a sparse vector to list of tuples containing index and value of non-zero elements.\n \"\"... | trial_gpt4o_2 | {
"original_instruction": "You are given two lists representing large sparse vectors of possibly different lengths. Each list contains floating-point numbers where most of the elements are zeros.\n\nYou need to write a function that:\n1. Converts these sparse vectors into a more efficient storage structure that only ... | 0.486905 | Data_Structure_47440 | C | [
"vector_to_index_value_list",
"sparse_vector_dot_product"
] | 2 | [
[
"sparse_vector_dot_product",
"vector_to_index_value_list"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6e45f5665b7b785fe999d3f98424145df383936d | dd55fd28f249dd0eef101e69fcf10f9cde1dc11a | |||
v1.0 | complete | Data_Structure | Data_Structure_46862_C | def merge_sort(arr):
""" Given an array of integers, implement the Merge Sort algorithm.
The implementation should handle the array efficiently and work correctly for all edge cases.
Args:
arr (List[int]): Input array of integers.
Returns:
List[int]: Sorted array.
Examples:
... | def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:])
# Perform in-place merging
merge(left, right, arr)
return arr
def merge(left, right, merged):
left_cursor, right_cursor = 0, 0
while left_cursor < le... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted():
assert merge_sort([5,... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right, merged):",
"function_name": "merge",
"parameter_list": "(left, right, merged)"
}... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n if len(arr) <= 1:\n return arr\n mid = len(arr) // 2\n left = merge_sort(arr[:mid])\n right = merge_sort(arr[mid:])\... | trial_gpt4o_2 | {
"original_instruction": "### Coding Challenge: Implement and Optimize Merge Sort\n\n**Objective**:\nGiven an array of integers, you are required to implement the Merge Sort algorithm. Your implementation should handle the array in an efficient manner and should work correctly for all edge cases.\n\n**Requirements**... | 0.661796 | Data_Structure_46862 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b10af24c29ef86280f98a1d6bbce7a46d3682c5b | 72ab11ccc9bc7d7cb01e330485a24f504ff5aa48 | |||
v1.0 | complete | Data_Structure | Data_Structure_46949_C | from typing import Tuple
def generate_key(k: int, seed: int = None) -> Tuple[int, int, int]:
"""Generate a pair of RSA keys with bit length `k`.
Args:
k (int): number of bits in the modulus `n`.
seed (int, optional): integer for seeding the random number generator. Defaults to None.
Returns:
... | import random
from typing import Tuple
from sympy import isprime, mod_inverse
def generate_prime(bits, seed=None):
if seed:
random.seed(seed)
while True:
p = random.getrandbits(bits)
if isprime(p):
return p
def generate_key(k: int, seed: int = None) -> Tuple[int, int, int]:... | import pytest
from solution import generate_key, encrypt, decrypt
def test_generate_key_valid():
k = 16
n, e, d = generate_key(k)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_generate_key_invalid_k():
with pytest.raises(ValueError):
generate_ke... | [
{
"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... | [
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 typing import Tuple\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime(bits, seed=None):\n if seed:\n random.seed(see... | trial_gpt4o_0 | {
"original_instruction": "### Question\n**RSA Key Generation and Encryption/Decryption**\n\nThe RSA algorithm is widely used for secure data transmission. This question tasks you with implementing the RSA key generation, encryption, and decryption process. The RSA algorithm involves generating three numbers \\(n\\),... | 0.744656 | Data_Structure_46949 | C | [
"generate_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | db325b51f6f4c1626efafded0e3387193923fd7d | 2a86ba517f9609cd127f2dd58af814f60665b144 | |||
v1.0 | complete | Data_Structure | Data_Structure_47693_C | def enhanced_gcd(x: int, y: int) -> int:
""" Calculates the greatest common divisor (GCD) of x and y using an optimized algorithm.
>>> enhanced_gcd(18, 24)
6
>>> enhanced_gcd(48, 18)
6
>>> enhanced_gcd(7, 3)
1
>>> enhanced_gcd(54, 24)
6
>>> enhanced_gcd(0, 0)
0
>>> enhanc... | def enhanced_gcd(x, y):
"""
Calculates the greatest common divisor (GCD) of x and y using the Euclidean algorithm.
"""
while y != 0:
x, y = y, x % y
return x
def enhanced_lcm(x, y):
"""
Calculates the least common multiple (LCM) of x and y using the GCD.
"""
if x == 0 or y =... | from solution import enhanced_gcd, enhanced_lcm
def test_enhanced_gcd_with_non_zero_numbers():
assert enhanced_gcd(18, 24) == 6
assert enhanced_gcd(48, 18) == 6
assert enhanced_gcd(7, 3) == 1
assert enhanced_gcd(54, 24) == 6
def test_enhanced_gcd_with_zero():
assert enhanced_gcd(0, 0) == 0
ass... | [
{
"docstring": "Calculates the greatest common divisor (GCD) of x and y using the Euclidean algorithm.",
"function_declaration": "def enhanced_gcd(x, y):",
"function_name": "enhanced_gcd",
"parameter_list": "(x, y)"
},
{
"docstring": "Calculates the least common multiple (LCM) of x and y 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": "def enhanced_gcd(x, y):\n \"\"\"\n Optimized function to calculate GCD using a combination of Euclidean and Binary GCD algorithms.\n \"\"\"\n # Ba... | trial_gpt4o_2 | {
"original_instruction": "### Problem: Enhanced GCD and LCM Calculator\nGiven two non-negative integers x and y, your task is to write two functions:\n\n1. **`enhanced_gcd(x, y)`** that calculates the greatest common divisor by intelligently combining the properties of the standard Euclidean algorithm with the binar... | 0.756764 | Data_Structure_47693 | C | [
"enhanced_gcd",
"enhanced_lcm"
] | 2 | [
[
"enhanced_lcm",
"enhanced_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3ed75c6201fffd3e9fa8a443093ef9f02f18f06c | 83b73e676cff56ca8c16f7e80be20f471f86aed2 | |||
v1.0 | complete | Data_Structure | Data_Structure_46544_C | def compare_flow_algorithms(capacity, source, sink):
""" Compare the maximum flow values computed by three network flow algorithms: Ford-Fulkerson, Edmonds-Karp, and Dinic.
Args:
capacity (List[List[int]]): A 2D list representing the capacities of the edges in the graph.
source (int): The i... | from collections import deque
# Helper function to perform BFS for Edmonds-Karp
def bfs(C, F, source, sink, parent):
visited = [False] * len(C)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v in range(len(C)):
if not visited[v] and C[u... | from solution import compare_flow_algorithms
def test_compare_flow_algorithms():
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
result = c... | [
{
"docstring": null,
"function_declaration": "def bfs(C, F, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(C, F, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def ford_fulkerson(C, source, sink):",
"function_name": "ford_fulkerson",
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\n# Ford-Fulkerson Algorithm using DFS\ndef ford_fulkerson(capacity, source, sink):\n n = len(capacity)\n residual_capaci... | trial_gpt4o_1 | {
"original_instruction": "#### Context\nYou were recently hired by a company that manages oil pipelines. They need a program to compute the maximum flow of oil from the main reservoir (source) to the base station (sink) through a complex network of pipes. Each pipe has a certain capacity, and you need to use network... | 0.512578 | Data_Structure_46544 | C | [
"bfs",
"ford_fulkerson",
"edmonds_karp",
"bfs_dinic",
"dfs_dinic",
"dinic",
"compare_flow_algorithms"
] | 7 | [
[
"compare_flow_algorithms",
"dinic"
],
[
"compare_flow_algorithms",
"edmonds_karp"
],
[
"compare_flow_algorithms",
"ford_fulkerson"
],
[
"dinic",
"bfs_dinic"
],
[
"dinic",
"dfs_dinic"
],
[
"edmonds_karp",
"ford_fulkerson"
],
[
"ford_fulker... | 7 | [] | false | [] | false | pytest | true | [] | true | 9b98d3d4585ec234f3eab58bb2ff06f3cac624ed | 03c0f4a6a61f628a367c5fe926d8b532105365c2 | |||
v1.0 | complete | Data_Structure | Data_Structure_47785_C | from typing import List, Tuple
def compute_gcd_and_trailing_zeros(arr: List[int]) -> Tuple[int, int]:
"""
Given a list of non-negative integers 'arr', returns a tuple where the first
element is the GCD of all the integers in the list calculated using bitwise operations,
and the second element is the nu... | from typing import List, Tuple
from functools import reduce
def gcd(a, b):
"""
Helper function to calculate GCD using bitwise operations.
"""
while b:
a, b = b, a % b
return a
def compute_gcd_and_trailing_zeros(arr: List[int]) -> Tuple[int, int]:
"""
Given a list of non-negative in... | from solution import compute_gcd_and_trailing_zeros
def test_example1():
assert compute_gcd_and_trailing_zeros([40, 60, 80]) == (20, 2)
def test_example2():
assert compute_gcd_and_trailing_zeros([7, 14, 28]) == (7, 0)
def test_single_element():
assert compute_gcd_and_trailing_zeros([15]) == (15, 0)
def ... | [
{
"docstring": "Helper function to calculate GCD using bitwise operations.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Given a list of non-negative integers 'arr', returns a tuple where the first\nelement is the GCD of all... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nfrom functools import reduce\n\ndef gcd(a, b):\n \"\"\"\n Helper function to calculate GCD using bitwise operations.\n ... | trial_gpt4o_0 | {
"original_instruction": "### GCD and Trailing Zeros Combined Assessment\n\nYou are tasked with solving a problem that requires advanced understanding and manipulation of integers using bitwise operations and GCD algorithms.\n\n#### Problem Statement\n\nGiven an array of non-negative integers, your task is to comput... | 0.667172 | Data_Structure_47785 | C | [
"gcd",
"compute_gcd_and_trailing_zeros"
] | 2 | [
[
"compute_gcd_and_trailing_zeros",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c8799621a17d8827d6623ebdfad61b56662fe7e6 | 3c85094e9bb9361684a4396a91f85eccae9c5c72 | |||
v1.0 | complete | Data_Structure | Data_Structure_46876_C | import random
def is_sorted(arr):
"""
Checks if the array is sorted in non-decreasing order.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr, max_iter=10000):
"""
Sorts an array using Bogo Sort algorithm and returns t... | import random
def is_sorted(arr):
"""
Checks if the array is sorted in non-decreasing order.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr, max_iter=10000):
"""
Sorts an array using Bogo Sort algorithm and returns t... | from solution import bogo_sort, evaluate_performance
def test_is_sorted():
assert is_sorted([1, 2, 3, 4, 5]) == True
assert is_sorted([5, 4, 3, 2, 1]) == False
assert is_sorted([1, 1, 2, 2, 3]) == True
def test_bogo_sort():
sorted_arr, iterations = bogo_sort([1, 2, 3])
assert sorted_arr == [1, 2, ... | [
{
"docstring": "Checks if the array is sorted in non-decreasing order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts an array using Bogo Sort algorithm and returns the sorted array along with\nthe number of i... | [
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 bogo_sort(arr, max_iter=10000):\n \"\"\"\n Sorts the array using Bogo Sort and returns the number of iterations it took.\n Args:... | trial_gpt4o_2 | {
"original_instruction": "### Bogo Sort Simulation and Analysis\n\n#### Objective\nGiven a sorting algorithm, Bogo Sort, which sorts an array by repeatedly shuffling it until it is sorted, your task is to implement a function that evaluates its performance and analyze the iterations it takes to sort arrays of differ... | 0.590836 | Data_Structure_46876 | C | [
"is_sorted",
"bogo_sort",
"evaluate_performance"
] | 3 | [
[
"bogo_sort",
"is_sorted"
],
[
"evaluate_performance",
"bogo_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9e96ad2c9f22359fc8fb5c9ffce198e73eec6528 | 0bd8834a76d3750ef283b845c27050fb4c00216e | |||
v1.0 | complete | Data_Structure | Data_Structure_47797_C | def is_krishnamurthy_number(n: int) -> bool:
""" Determine if the given number is a Krishnamurthy number.
>>> is_krishnamurthy_number(145)
True
>>> is_krishnamurthy_number(40585)
True
>>> is_krishnamurthy_number(357)
False
""" | def factorial(n):
"""
Return the factorial of a given number n.
"""
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result
def is_krishnamurthy_number(n):
"""
Return True if the given number n is a Krishnamurthy number, else Fals... | from solution import is_krishnamurthy_number
def test_is_krishnamurthy_number_true_cases():
assert is_krishnamurthy_number(1) == True
assert is_krishnamurthy_number(2) == True
assert is_krishnamurthy_number(145) == True
assert is_krishnamurthy_number(40585) == True
def test_is_krishnamurthy_number_fal... | [
{
"docstring": "Return the factorial of a given number n.",
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
},
{
"docstring": "Return True if the given number n is a Krishnamurthy number, else False.",
"function_declaration": "def is_kri... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def factorial(n):\n \"\"\"\n Returns the factorial of a given number n.\n \"\"\"\n if n == 0 or n == 1:\n return 1\n result = 1\n for... | trial_gpt4o_7 | {
"original_instruction": "### Krishnamurthy Number Detection\n\n#### Scenario:\nYou are tasked with creating an efficient function to detect if a given number is a Krishnamurthy number. This will help in a mathematical exploration module to identify special numbers automatically.\n\n#### Function Details:\n**Functio... | 0.625605 | Data_Structure_47797 | C | [
"factorial",
"is_krishnamurthy_number"
] | 2 | [
[
"is_krishnamurthy_number",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 98b8af5755b3822d35afdaa5fd392bc7e63b06b4 | 405534565ed490b9a72c33359c3543f918865f9e | |||
v1.0 | complete | Data_Structure | Data_Structure_47099_C | def search_insert(array, val):
"""
Params:
array (List[int]): A sorted list of integers
val (int): The target value to find the insertion index for
Returns:
int: Index at which the val should be inserted to maintain sorted order
Example:
>>> search_insert([1, 3, 5, 6], 5)
... | def search_insert(array, val):
"""
Params:
array (List[int]): A sorted list of integers
val (int): The target value to find the insertion index for
Returns:
int: Index at which the val should be inserted to maintain sorted order
"""
left, right = 0, len(array) - 1
w... | from solution import search_insert, insertion_sort
def test_search_insert():
assert search_insert([1, 3, 5, 6], 5) == 2
assert search_insert([1, 3, 5, 6], 2) == 1
assert search_insert([1, 3, 5, 6], 0) == 0
assert search_insert([1, 3, 5, 6], 7) == 4
assert search_insert([1, 3, 5, 5, 6, 6], 5) == 2
... | [
{
"docstring": "Params:\n array (List[int]): A sorted list of integers\n val (int): The target value to find the insertion index for\n\nReturns:\n int: Index at which the val should be inserted to maintain sorted order",
"function_declaration": "def search_insert(array, val):",
"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": "def search_insert(array, val):\n \"\"\"\n Params:\n array (List[int]): A sorted list of integers\n val (int): The target value to find the... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort with Binary Search\n\n#### Scenario:\n\nYou have been tasked to implement a function for sorting an array of integers. To do this efficiently, you will use the insertion sort algorithm but enhance it using binary search to find the correct insertion position. Using binary... | 0.600501 | Data_Structure_47099 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 00b56c77349db23c5edf7e7f66c2e0f727283501 | 95ad760f6bcd95a84e8061923c9d596d98f7a42e | |||
v1.0 | complete | Data_Structure | Data_Structure_47406_C | def optimized_insertion_sort(arr, simulation=False):
"""
Sort an array using an optimized version of insertion sort.
Parameters:
arr : list[int] : the list of integers to sort
simulation : bool : if True, print the array at each iteration
Returns:
list[int] : the sorted list of integers
... | def binary_search(arr, val, start, end):
"""
Helper function to perform binary search to find the insertion index.
"""
if start == end:
if arr[start] > val:
return start
else:
return start + 1
if start > end:
return start
mid = (start + end) // 2... | from solution import optimized_insertion_sort
def test_single_element_array():
assert optimized_insertion_sort([1]) == [1]
def test_sorted_array():
assert optimized_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert optimized_insertion_sort([5, 4, 3, 2, 1]) == [1, ... | [
{
"docstring": "Helper function to perform binary search to find the insertion index.",
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "Sort an array using an optimized version... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binary_search(arr, val, start, end):\n \"\"\"\n Helper function to perform binary search to find the insertion index.\n \"\"\"\n if start == e... | trial_gpt4o_0 | {
"original_instruction": "You are working as a software engineer tasked with creating an optimized sort function. One of the basic tasks is to work with simple sorting algorithms. Your goal is to implement and enhance a sorting function that uses the insertion sort algorithm.\n\n#### Function Signature\n```python\nd... | 0.543895 | Data_Structure_47406 | C | [
"binary_search",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 71456fb049e881ee9ec85c5bb8dd893284eb3c29 | a448325a4bed0f3550f31160fbb1a12c0ab1384b | |||
v1.0 | complete | Data_Structure | Data_Structure_47227_C | from typing import List
def radix_sort(arr: List[int], simulation: bool=False) -> List[int]:
""" Implement the Radix Sort algorithm to sort an array of non-negative integers.
>>> radix_sort([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66, 75, 90, 170, 802]
>>> radix_sort([3, 3, 3, 3], simulation=True... | from typing import List
def counting_sort_for_radix(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:
... | from solution import radix_sort
def test_radix_sort_typical_case():
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():
assert radix_sort([5]) == [5]
def test_radix_s... | [
{
"docstring": null,
"function_declaration": "def counting_sort_for_radix(arr, exp):",
"function_name": "counting_sort_for_radix",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort",
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort_for_radix(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \n for i in range(n):\... | trial_gpt4o_0 | {
"original_instruction": "### Coding Assessment: Radix Sort Implementation\n\n#### Objective:\nImplement the Radix Sort algorithm to sort an array of non-negative integers.\n\n#### Instructions:\nYou are required to implement a function called `radix_sort` that sorts an array of non-negative integers in ascending or... | 0.665363 | Data_Structure_47227 | C | [
"counting_sort_for_radix",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort_for_radix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 484bc16f0c90d3b5fcf5832d0b2d4cdd7addef4e | fc1ecdd08d00b5fdc6e4cbf214176cfa024963cd | |||
v1.0 | complete | Data_Structure | Data_Structure_47666_C | def search_insert(arr, target):
"""
Binary search to find the index where target should be inserted to keep arr sorted.
>>> search_insert([1, 2, 4, 5], 3) == 2
>>> search_insert([1, 3, 5, 6], 2) == 1
"""
left, right = 0, len(arr)
while left < right:
mid = (left + right) // 2
... | def search_insert(arr, target):
"""
Binary search to find the index where target should be inserted to keep arr sorted.
"""
left, right = 0, len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid] < target:
left = mid + 1
else:
right = mid
... | from solution import insertion_sort_with_binary_search
def test_empty_list():
assert insertion_sort_with_binary_search([]) == []
def test_single_element():
assert insertion_sort_with_binary_search([5]) == [5]
def test_sorted_list():
assert insertion_sort_with_binary_search([1, 2, 3, 4, 5]) == [1, 2, 3, 4... | [
{
"docstring": "Binary search to find the index where target should be inserted to keep arr sorted.",
"function_declaration": "def search_insert(arr, target):",
"function_name": "search_insert",
"parameter_list": "(arr, target)"
},
{
"docstring": "Sorts a list of integers using insertion sor... | [
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 bisect import bisect_left\n\ndef search_insert(sorted_sublist, value):\n \"\"\"\n Utilizes binary search to find the index at which 'value' should ... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort with Binary Search Insertion\nIn this task, you are required to implement an insertion sort algorithm using binary search to find the correct insertion point.\n\n**Scenario**:\nGiven an unsorted array of integers, the goal is to sort the array using an optimized insertion... | 0.617563 | Data_Structure_47666 | C | [
"search_insert",
"insertion_sort_with_binary_search"
] | 2 | [
[
"insertion_sort_with_binary_search",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c8eda2ef15a17bc2bcec309536baa64f59e05d76 | 0e643d81ac7cd17faad1076469cf852d51a1e20f | |||
v1.0 | complete | Data_Structure | Data_Structure_47358_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
""" Sorts an array of integers in ascending order using the Merge Sort algorithm.
>>> merge_sort([38, 27, 43, 3, 9, 82, 10])
[3, 9, 10, 27, 38, 43, 82]
>>> merge_sort([])
[]
""" | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers in ascending order 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:])
retu... | from solution import merge_sort
def test_merge_sort_with_normal_case():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_with_empty_array():
assert merge_sort([]) == []
def test_merge_sort_with_single_element_array():
assert merge_sort([1]) == [1]
def test_... | [
{
"docstring": "Sorts an array of integers in ascending order using the Merge Sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted input lists into a single sorted list.",
"function... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array of integers in ascending order using the Merge Sort al... | trial_gpt4o_2 | {
"original_instruction": "### Question: Efficient Sorting for a Record Management System\n\n#### Context:\nYou are developing a record management system where performance is critical. The system handles sorting of user records based on their ages. Due to performance constraints, you need to replace your current inef... | 0.67895 | Data_Structure_47358 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a1396d467716f3f8877ba1a3258e6f6760a66e05 | 654e3207e55962aabe1ae49ca438c956b57cf1ce | |||
v1.0 | complete | Data_Structure | Data_Structure_47894_C | import random
from typing import List, Tuple
def is_sorted(arr: List[int]) -> bool:
"""
Checks if the array is sorted in ascending order.
Parameters:
arr (list): List of integers to check.
Returns:
bool: True if the list is sorted in ascending order, False otherwise.
>>> is_s... | import random
def is_sorted(arr):
"""
Checks if the array is sorted in ascending order.
Parameters:
arr (list): List of integers to check.
Returns:
bool: True if the list is sorted in ascending order, False otherwise.
"""
return all(arr[i] <= arr[i+1] for i in range(len(arr) -... | from solution import is_sorted, improved_bogo_sort
def test_is_sorted():
assert is_sorted([1, 2, 3, 4, 5]) == True
assert is_sorted([5, 4, 3, 2, 1]) == False
assert is_sorted([1, 3, 2, 4, 5]) == False
assert is_sorted([10]) == True
assert is_sorted([]) == True
def test_improved_bogo_sort():
in... | [
{
"docstring": "Checks if the array is sorted in ascending order.\n\nParameters:\narr (list): List of integers to check.\n\nReturns:\nbool: True if the list is sorted in ascending order, False otherwise.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"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": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Check if the array is sorted in ascending order.\n \"\"\"\n for i in range(len(arr) - 1):\n ... | trial_gpt4o_2 | {
"original_instruction": "### Scenario:\nYou have been hired by a company to assess their understanding of sorting algorithms. You decide to present a fun and educational challenge using the notorious Bogo Sort, hoping to illustrate the inefficiency of brute-force algorithms. \n\n### Task:\nImplement a function `is_... | 0.675946 | Data_Structure_47894 | C | [
"is_sorted",
"improved_bogo_sort"
] | 2 | [
[
"improved_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 96e5e590a3e6ed0beaaa2f4abfe0156210d9b98e | 67acd451dad73d3549b56a11ac1209632628c7bc | |||
v1.0 | complete | Data_Structure | Data_Structure_48045_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers in ascending order using the merge sort algorithm.
Parameters:
arr (List[int]): The array of integers to be sorted.
Returns:
List[int]: The sorted array of integers.
>>> merge... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers in ascending order using the merge sort algorithm.
Parameters:
arr (List[int]): The array of integers to be sorted.
Returns:
List[int]: The sorted array of integers.
"""
if... | from solution import merge_sort
def test_empty_array():
assert merge_sort([]) == []
def test_single_element_array():
assert merge_sort([2]) == [2]
def test_all_positive_numbers():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_all_negative_numbers():
assert merg... | [
{
"docstring": "Sorts an array of integers in ascending order using the merge sort algorithm.\n\nParameters:\narr (List[int]): The array of integers to be sorted.\n\nReturns:\nList[int]: The sorted array of integers.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"p... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n def merge(left: List[int], right... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Implementation Challenge\n\n#### Scenario:\nYou are given an array of integers that may contain both negative and positive values. Your task is to sort this array in ascending order using the Merge Sort algorithm. Merge Sort separates the list into halves, recursively sorts e... | 0.652387 | Data_Structure_48045 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a6ea0813e3ff25d68e2919f1c889d456c2aa1316 | 4a451f05f387fd18a2099c791c49cefed254ef80 | |||
v1.0 | complete | Data_Structure | Data_Structure_47682_C | def advanced_gcd_analysis(a: int, b: int) -> tuple:
"""
Given two non-negative integers, `a` and `b`, this function calculates:
1. The GCD using the efficient bitwise method.
2. The LCM of the two integers.
3. The number of trailing zeros in the binary representation of the LCM.
Returns all thr... | def gcd_bitwise(a, b):
"""
Computes the GCD using the efficient bitwise method.
"""
if a == 0:
return b
if b == 0:
return a
# Finding common factors of 2
shift = 0
while ((a | b) & 1) == 0:
a >>= 1
b >>= 1
shift += 1
while (a & 1) == 0:
... | from solution import advanced_gcd_analysis
def test_advanced_gcd_analysis_case_1():
assert advanced_gcd_analysis(34, 40) == (2, 680, 3)
def test_advanced_gcd_analysis_case_2():
assert advanced_gcd_analysis(10, 15) == (5, 30, 1)
def test_advanced_gcd_analysis_case_3():
assert advanced_gcd_analysis(0, 5) =... | [
{
"docstring": "Computes the GCD using the efficient bitwise method.",
"function_declaration": "def gcd_bitwise(a, b):",
"function_name": "gcd_bitwise",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the LCM using the relationship between GCD and LCM.",
"function_declaration": "d... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def advanced_gcd_analysis(a: int, b: int) -> tuple:\n def gcd(a: int, b: int) -> int:\n if a == 0:\n return b\n if b == 0:\n ... | trial_gpt4o_1 | {
"original_instruction": "### Question: Advanced GCD Analysis and Application\n\nYou have been provided with two different implementations of the greatest common divisor (GCD) - one using Euclid's division-based algorithm and the other using bitwise operations. Additionally, you understand the relationship between G... | 0.713782 | Data_Structure_47682 | C | [
"gcd_bitwise",
"lcm",
"count_trailing_zeros",
"advanced_gcd_analysis"
] | 4 | [
[
"advanced_gcd_analysis",
"count_trailing_zeros"
],
[
"advanced_gcd_analysis",
"gcd_bitwise"
],
[
"advanced_gcd_analysis",
"lcm"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | d849b306521089b6377a6eb6c27035e77aadbae9 | d39688a25dcee4af5f3341811b822b859885a281 | |||
v1.0 | complete | Data_Structure | Data_Structure_47357_C | def generate_key_pair(k):
"""
Generates RSA encryption and decryption keys.
Parameters:
k (int): The number of bits in the modulus.
Returns:
Tuple[int, int, int]: (n, e, d) where n is the modulus, e is the encryption exponent,
and d is the decryption exponent.
... | import random
from math import gcd
def is_prime(n, k=128):
"""Test if a number is prime using Miller-Rabin primality test."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
r, d = 0, n - 1
while d % 2 == 0:
r += 1
d //= 2
... | from solution import generate_key_pair, encrypt, decrypt
def test_generate_key_pair():
n, e, d = generate_key_pair(16)
assert n > 0
assert e > 0
assert d > 0
def test_encrypt_decrypt():
n, e, d = generate_key_pair(16)
data = 20
encrypted = encrypt(data, e, n)
decrypted = decrypt(en... | [
{
"docstring": "Test if a number is prime using Miller-Rabin primality test.",
"function_declaration": "def is_prime(n, k=128):",
"function_name": "is_prime",
"parameter_list": "(n, k=128)"
},
{
"docstring": "Generate an odd integer randomly.",
"function_declaration": "def generate_prime... | [
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\n\ndef generate_prime_candidate(length):\n \"\"\" Generate an odd integer randomly \"\"\"\n p = random.getrandb... | trial_gpt4o_1 | {
"original_instruction": "### RSA Key Pair Generation and Encryption\n\n#### Objective\nYour task is to implement the RSA key generation, encryption, and decryption functions. This will test your understanding of modular arithmetic and prime generation, both fundamental concepts in cryptography.\n\n### Problem State... | 0.73616 | Data_Structure_47357 | C | [
"is_prime",
"generate_prime_candidate",
"generate_prime_number",
"modinv",
"generate_key_pair",
"encrypt",
"decrypt"
] | 7 | [
[
"generate_key_pair",
"generate_prime_number"
],
[
"generate_key_pair",
"modinv"
],
[
"generate_prime_number",
"generate_prime_candidate"
],
[
"generate_prime_number",
"is_prime"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 6f94c004b7d3420d667c7acf724c5c5bb9a4cfb5 | ee1731071e2b3659a3e892f90add819611172bb8 | |||
v1.0 | complete | Data_Structure | Data_Structure_47240_C | from typing import List
def max_flow(capacity: List[List[int]], source: int, sink: int) -> int:
""" Computes the maximum flow from a source node to a sink node in a network of pipes using Dinic's Algorithm.
Args:
capacity (List[List[int]]): A 2D list where capacity[i][j] indicates the maximum capacity... | from typing import List
from collections import deque
def dinic_bfs(capacity, flow, level, source, sink):
"""
BFS function for Dinic's algorithm.
Sets level array using a level graph concept.
"""
queue = deque([source])
level[source] = 0
while queue:
u = queue.popleft()
for ... | import pytest
from solution import max_flow
def test_max_flow_small_graph():
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_flo... | [
{
"docstring": "BFS function for Dinic's algorithm.\nSets level array using a level graph concept.",
"function_declaration": "def dinic_bfs(capacity, flow, level, source, sink):",
"function_name": "dinic_bfs",
"parameter_list": "(capacity, flow, level, source, sink)"
},
{
"docstring": "DFS f... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef dinic_bfs(capacity: List[List[int]], flow: List[List[int]], level: List[int], source: int, sink: int) -> bool:\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "You are given a network of pipes represented as a directed graph. Each pipe has a certain maximum capacity for fluid flow. The objective is to determine the maximum amount of fluid that can flow from a designated source node to a designated sink node using one of the maximum flow algorithms... | 0.602253 | Data_Structure_47240 | C | [
"dinic_bfs",
"dinic_dfs",
"max_flow"
] | 3 | [
[
"max_flow",
"dinic_bfs"
],
[
"max_flow",
"dinic_dfs"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 375db8136f77da9734a027a1210efa7df21a0358 | 74b461bb24eb7446bbe6154d6bdbe5850b043111 | |||
v1.0 | complete | Data_Structure | Data_Structure_47573_C | [Completion Task in Python]
def optimized_multiply(matA: list, matB: list) -> list:
"""
Multiplies two square matrices matA and matB using Strassen's algorithm
Time Complexity: Approximately O(n^2.81)
"""
def identity(n: int) -> list:
"""
Returns the Identity matrix of size n x n
Time Compl... | def optimized_multiply(matA: list, matB: list) -> list:
"""
Multiplies two square matrices matA and matB using Strassen's algorithm
Time Complexity: Approximately O(n^2.81)
"""
def add_matrix(A, B):
size = len(A)
return [[A[i][j] + B[i][j] for j in range(size)] for i in range(size)]
... | from solution import optimized_multiply, identity, matrix_exponentiation
def test_optimized_multiply():
matA = [
[1, 2],
[3, 4]
]
matB = [
[2, 0],
[1, 2]
]
assert optimized_multiply(matA, matB) == [[4, 4], [10, 8]]
def test_identity():
assert identity(3) == [
... | [
{
"docstring": "Multiplies two square matrices matA and matB using Strassen's algorithm\nTime Complexity: Approximately O(n^2.81)",
"function_declaration": "def optimized_multiply(matA, matB):",
"function_name": "optimized_multiply",
"parameter_list": "(matA, matB)"
},
{
"docstring": "Return... | [
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_multiply(matA: list, matB: list) -> list:\n \"\"\"\n Multiplies two square matrices matA and matB using Strassen's algorithm\n Time Com... | trial_gpt4o_0 | {
"original_instruction": "### Question: Optimized Matrix Multiplication and Exponentiation\n\nYou are given three operations related to matrix computations: matrix multiplication, identity matrix generation, and matrix exponentiation. Your task is to implement optimized versions of these operations.\n\n**1. Optimize... | 0.504658 | Data_Structure_47573 | C | [
"optimized_multiply",
"identity",
"matrix_exponentiation"
] | 3 | [
[
"matrix_exponentiation",
"identity"
],
[
"matrix_exponentiation",
"optimized_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3b14dd6b7a3789742ae729a88762ae4309725958 | 1184fc97dc1c31845b9c10b3a5b191a0e49429e4 | |||
v1.0 | complete | Data_Structure | Data_Structure_48067_C | def radix_sort_with_negatives(arr):
"""
Sorts an array of integers in ascending order using the radix sort mechanism
and handles both negative and positive integers.
>>> radix_sort_with_negatives([-17, 543, -998, 0, 14, -5, 4000, -4001])
[-4001, -998, -17, -5, 0, 14, 543, 4000]
>>> radix_s... | def counting_sort(arr, exp):
"""
A helper function to perform counting sort on arr based on the
digit at exp (1, 10, 100, ...), suitable for positive integers.
"""
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = abs(arr[i]) // exp
count[inde... | def test_radix_sort_with_negatives():
assert radix_sort_with_negatives([-17, 543, -998, 0, 14, -5, 4000, -4001]) == [-4001, -998, -17, -5, 0, 14, 543, 4000]
def test_radix_sort_with_negatives_all_positive():
assert radix_sort_with_negatives([3, 1, 2, 5, 4]) == [1, 2, 3, 4, 5]
def test_radix_sort_with_negative... | [
{
"docstring": "A helper function to perform counting sort on arr based on the\ndigit at exp (1, 10, 100, ...), suitable for positive integers.",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "A help... | [
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):\n \"\"\"\n A helper function to perform counting sort on arr based on the\n digit at exp (1, 10, 100, ...), suitable for... | trial_gpt4o_0 | {
"original_instruction": "### Question: Implement Radix Sort with Negative Numbers Support\n\nRadix sort as implemented above only handles non-negative integers. Adapt this algorithm to be capable of handling both positive and negative integers within the given list.\n\n#### Task\n\nWrite a function `radix_sort_with... | 0.707038 | Data_Structure_48067 | C | [
"counting_sort",
"radix_sort",
"radix_sort_with_negatives"
] | 3 | [
[
"radix_sort",
"counting_sort"
],
[
"radix_sort_with_negatives",
"radix_sort"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | e83f6bdf3184b353b6da0f4d9096f60c54beadf3 | 0948443e81bb0a42addc436deb8c62b2f067ca17 | |||
v1.0 | complete | Data_Structure | Data_Structure_47502_C | from typing import List
def merge_sort_in_place(arr: List[int]) -> None:
""" Implement an in-place merge sort for an array of integers.
This function sorts the given array in-place in non-decreasing order using the merge sort algorithm without using any additional arrays.
The algorithm runs in O(n log... | from typing import List
def merge_sort_in_place(arr: List[int], left: int = 0, right: int = None) -> None:
if right is None:
right = len(arr) - 1
if left < right:
middle = (left + right) // 2
merge_sort_in_place(arr, left, middle)
merge_sort_in_place(arr, middle + 1, right)
... | from solution import merge_sort_in_place
def test_merge_sort_in_place_with_mixed_numbers():
arr = [38, 27, 43, 3, 9, 82, 10]
merge_sort_in_place(arr)
assert arr == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_in_place_with_sorted_numbers():
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
merge_sort_in_place(a... | [
{
"docstring": null,
"function_declaration": "def merge_sort_in_place(arr, left=0, right=None):",
"function_name": "merge_sort_in_place",
"parameter_list": "(arr, left=0, right=None)"
},
{
"docstring": null,
"function_declaration": "def merge(arr, left, middle, right):",
"function_na... | [
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_in_place(arr: List[int]) -> None:\n def merge(arr, start, mid, end):\n start2 = mid + 1\n # If the ... | trial_gpt4o_2 | {
"original_instruction": "**Question**: Implement an in-place merge sort for an array of integers.\n\n**Scenario**: You are given an array of integers that you need to sort in non-decreasing order using the merge sort algorithm. For this task, you must implement the merge sort algorithm in such a way that it does no... | 0.64831 | Data_Structure_47502 | C | [
"merge_sort_in_place",
"merge"
] | 2 | [
[
"merge_sort_in_place",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 601714195467508c7b29d79f886cd4b8aa7f21ec | df78f6554cf4c7cbc3607231f5ef0c8ccb235c1b | |||
v1.0 | complete | Data_Structure | Data_Structure_47106_C | from typing import List
def batch_prime_check(nums: List[int]) -> List[bool]:
"""
Processes a batch of numbers and returns a list indicating whether each number in the batch is prime or not.
>>> batch_prime_check([2, 3, 4, 5, -1, 0, 17, 18])
[True, True, False, True, False, False, True, False]
... | import math
from typing import List
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return Tr... | from solution import batch_prime_check
def test_batch_prime_check():
assert batch_prime_check([2, 3, 4, 5, -1, 0, 17, 18]) == [True, True, False, True, False, False, True, False]
assert batch_prime_check([37, 41, 43, 47, -2, 1, 53, 60]) == [True, True, True, True, False, False, True, False]
assert batch_pr... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def batch_prime_check(nums):",
"function_name": "batch_prime_check",
"parameter_list": "(nums)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import List\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2... | trial_gpt4o_2 | {
"original_instruction": "**Prime Number Batch Processor**\n\n### Problem Statement\nYou are required to create a function `batch_prime_check` that processes a batch of numbers and returns a list indicating whether each number in the batch is prime or not. The function should leverage the given algorithm for checkin... | 0.71703 | Data_Structure_47106 | C | [
"is_prime",
"batch_prime_check"
] | 2 | [
[
"batch_prime_check",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6f44659f44e38102f65344bce04af918d11ebfd2 | dd0d84ccbd6a4a8676af9f100cb1bfaa4be7254e | |||
v1.0 | complete | Data_Structure | Data_Structure_47160_C | from typing import List
def scalable_bitonic_sort(arr: List[int], reverse: bool = False) -> List[int]:
"""
Sorts an array of integers using the Bitonic Sort algorithm.
:param arr: List[int] - Array of integers to be sorted.
:param reverse: bool - If True, sort in descending order, otherwise ascending o... | from typing import List
def bitonic_merge(arr: List[int], low: int, count: int, direction: bool):
if count > 1:
k = count // 2
for i in range(low, low + k):
if (direction and arr[i] > arr[i + k]) or (not direction and arr[i] < arr[i + k]):
arr[i], arr[i + k] = arr[i + k]... | import pytest
from solution import scalable_bitonic_sort
def test_scalable_bitonic_sort_ascending_simple():
assert scalable_bitonic_sort([3, 7, 4, 8, 6, 2, 1, 5], reverse=False) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_scalable_bitonic_sort_descending_simple():
assert scalable_bitonic_sort([12, 4, 78, 26, 9, 32, ... | [
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, low, count, direction):",
"function_name": "bitonic_merge",
"parameter_list": "(arr, low, count, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_sort(arr, low, count, direction):",
"function... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bitonic_compare_and_swap(arr: List[int], i: int, j: int, direction: bool):\n \"\"\"\n Compare and swap the elements at in... | trial_gpt4o_2 | {
"original_instruction": "Scalable Bitonic Sort Implementation\n\n#### Context\nYou are working as a software engineer tasked with optimizing the performance of a large-scale numeric dataset analysis. For this purpose, you decide to implement the Bitonic Sort algorithm due to its efficiency in parallel processing en... | 0.704267 | Data_Structure_47160 | C | [
"bitonic_merge",
"bitonic_sort",
"scalable_bitonic_sort"
] | 3 | [
[
"bitonic_sort",
"bitonic_merge"
],
[
"scalable_bitonic_sort",
"bitonic_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1ce0c4b08b0351e355d0188b7f12498317dd0aab | e760a058cd78f24336672d9374b4694b232bdc81 | |||
v1.0 | complete | Data_Structure | Data_Structure_47330_C | from typing import List
def hybrid_heap_sort(arr: List[int], simulation: bool = False) -> List[int]:
"""
Sort an input array in ascending order using a hybrid heap sort algorithm that
dynamically chooses between max_heap_sort or min_heap_sort based on the input array.
If the majority of elements are... | def max_heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
max_heap... | from solution import hybrid_heap_sort
def test_hybrid_heap_sort_already_sorted():
assert hybrid_heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_hybrid_heap_sort_reverse_sorted():
assert hybrid_heap_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_hybrid_heap_sort_random_order():
assert hybrid_hea... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": null,
"function_declaration": "def min_heapify(arr, n, i):",
"function_name": "min_heapify",
"parameter_list": "(arr, n, i... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_heapify(arr, n, i, simulation):\n largest = i\n l = 2 * i + 1\n r = 2 * i + 2\n\n if l < n and arr[i] < arr[l]:\n largest = l\n\n ... | trial_gpt4o_7 | {
"original_instruction": "You are provided with two variants of the Heap Sort algorithm: `max_heap_sort` and `min_heap_sort`. Your task is to implement a hybrid heap sort method called `hybrid_heap_sort` that dynamically chooses between max heap sort and min heap sort based on the input array.\n\n### Objective\nWrit... | 0.652991 | Data_Structure_47330 | C | [
"max_heapify",
"min_heapify",
"max_heap_sort",
"min_heap_sort",
"hybrid_heap_sort"
] | 5 | [
[
"hybrid_heap_sort",
"max_heap_sort"
],
[
"hybrid_heap_sort",
"min_heap_sort"
],
[
"max_heap_sort",
"max_heapify"
],
[
"min_heap_sort",
"min_heapify"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | b3ddfabb521122f4ae8f8e3d4b0b603127f2712b | 1df97a6fc34286651b286eccc516399ec98fd3eb | |||
v1.0 | complete | Data_Structure | Data_Structure_48200_C | from typing import List
def search_in_sorted_array(arr: List[int], key: int) -> int:
""" Search for the given key in a sorted array using ternary search.
Args:
arr (List[int]): The array to be searched, sorted in ascending order.
key (int): The element to search for.
Returns:
int: ... | def ternary_search(arr, key, left, right):
if right >= left:
mid1 = left + (right - left) // 3
mid2 = right - (right - left) // 3
if arr[mid1] == key:
return mid1
if arr[mid2] == key:
return mid2
if key < arr[mid1]:
return ternary_search(... | from solution import search_in_sorted_array, is_sorted
def test_is_sorted():
assert is_sorted([1, 2, 3, 4, 5]) == True
assert is_sorted([5, 4, 3, 2, 1]) == False
assert is_sorted([1, 1, 1, 1, 1]) == True
assert is_sorted([]) == True
assert is_sorted([1]) == True
def test_search_in_sorted_array():
... | [
{
"docstring": null,
"function_declaration": "def ternary_search(arr, key, left, right):",
"function_name": "ternary_search",
"parameter_list": "(arr, key, left, right)"
},
{
"docstring": null,
"function_declaration": "def search_in_sorted_array(arr, key):",
"function_name": "search_... | [
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 ternary_search(arr, key, left, right):\n if right >= left:\n mid1 = left + (right - left) // 3\n mid2 = right - (right - left) // 3\n\n ... | trial_gpt4o_0 | {
"original_instruction": "### Ternary Search Implementation\n\nYou are provided with a basic implementation of the Ternary Search algorithm. Your understanding of this algorithm will be assessed through modifications and enhancements.\n\n#### Problem Statement\n1. Implement a revised version of `ternary_search` that... | 0.696776 | Data_Structure_48200 | C | [
"ternary_search",
"search_in_sorted_array",
"is_sorted"
] | 3 | [
[
"search_in_sorted_array",
"ternary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5a2983050aed4aa3ba92044488e69341415895a3 | f54686dcd895936ecfdd591976dda9a846495637 | |||
v1.0 | complete | Data_Structure | Data_Structure_48004_C | def insertion_sort(bucket: list) -> list:
""" Helper function to perform insertion sort on a bucket.
>>> insertion_sort([5, 2, 9, 1, 5, 6]) [1, 2, 5, 5, 6, 9]
>>> insertion_sort([4, 3, 2, 1]) [1, 2, 3, 4]
"""
def bucket_sort(arr: list) -> list:
"""
Sorts an array of floating-point numbers usin... | def insertion_sort(bucket):
"""
Helper function to perform insertion sort on a bucket.
"""
for i in range(1, len(bucket)):
key = bucket[i]
j = i - 1
while j >= 0 and key < bucket[j]:
bucket[j + 1] = bucket[j]
j -= 1
bucket[j + 1] = key
return b... | from solution import insertion_sort, bucket_sort
def test_bucket_sort_example():
assert bucket_sort([78.23, 98.01, 26.78, 34.56, 50.11]) == [26.78, 34.56, 50.11, 78.23, 98.01]
def test_bucket_sort_single_element():
assert bucket_sort([42.0]) == [42.0]
def test_bucket_sort_already_sorted():
assert bucket_... | [
{
"docstring": "Helper function to perform insertion sort on a bucket.",
"function_declaration": "def insertion_sort(bucket):",
"function_name": "insertion_sort",
"parameter_list": "(bucket)"
},
{
"docstring": "Sorts an array of floating-point numbers using Bucket Sort.",
"function_decla... | [
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: list) -> list:\n \"\"\"\n Sorts an array of floating-point numbers using Bucket Sort.\n \"\"\"\n if not arr:\n return ... | trial_gpt4o_2 | {
"original_instruction": "#### Scenario\nYou are tasked with sorting a list of floating-point numbers that represent scores achieved by students in a coding competition. The scores range uniformly from 0 to 100. Given the nature of the scores, a suitable approach for sorting is Bucket Sort, with an efficient seconda... | 0.572607 | Data_Structure_48004 | C | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c99285482a0a44514af231c551578fd60122561b | f12ccec75a56db0759fef2d22f415eaa8aa6f548 | |||
v1.0 | complete | Data_Structure | Data_Structure_48161_C | def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
"""
Returns a tuple (x, y, gcd(a, b)) where x and y satisfy the equation ax + by = gcd(a, b).
>>> extended_gcd(30, 20)
(1, -1, 10)
>>> extended_gcd(20, 30)
(-1, 1, 10)
"""
pass
def modular_inverse(a: int, m: int) -> int:
... | def extended_gcd(a, b):
"""
Returns a tuple (x, y, gcd(a, b)) where x and y satisfy the equation ax + by = gcd(a, b).
"""
if b == 0:
return (1, 0, a)
else:
x1, y1, gcd = extended_gcd(b, a % b)
x = y1
y = x1 - (a // b) * y1
return (x, y, gcd)
def modular_inver... | from solution import extended_gcd, modular_inverse
def test_extended_gcd():
assert extended_gcd(30, 20) == (1, -1, 10)
assert extended_gcd(20, 30) == (-1, 1, 10)
assert extended_gcd(35, 15) == (1, -2, 5)
assert extended_gcd(101, 10) == (1, -10, 1)
assert extended_gcd(10, 101) == (-10, 1, 1)
def te... | [
{
"docstring": "Returns a tuple (x, y, gcd(a, b)) where x and y satisfy the equation ax + by = gcd(a, b).",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the modular inverse of a modulo m.\nIf a and m... | [
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 extended_gcd(a, b):\n \"\"\"\n Computes the coefficients x and y such that ax + by = gcd(a, b) using the extended Euclidean algorithm.\n \n :p... | trial_gpt4o_2 | {
"original_instruction": "## Question: Implement a Secure Communication Protocol Using Modular Arithmetic\n\nYou are working on designing a secure communication protocol that relies on modular arithmetic to encode and decode messages. An essential part of this protocol involves finding modular inverses to decrypt me... | 0.678234 | Data_Structure_48161 | C | [
"extended_gcd",
"modular_inverse"
] | 2 | [
[
"modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e44ae3d2868fd233da905d8790486285d5de85b4 | b9a89ab291fa9c72fdfdaaf225f0e8f2328445fc | |||
v1.0 | complete | Data_Structure | Data_Structure_47460_C | from typing import List
def prime_check(num: int) -> bool:
"""
Efficiently determines if a given number is prime.
Parameters:
num (int): The number to check for primality.
Returns:
bool: True if num is a prime number, False otherwise.
"""
if num <= 1:
return False
... | from typing import List
def prime_check(num: int) -> bool:
if num <= 1:
return False
if num == 2 or num == 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while (i * i) <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
... | from solution import generate_primes
def test_small_range():
assert generate_primes(10) == [2, 3, 5, 7]
assert generate_primes(2) == [2]
assert generate_primes(3) == [2, 3]
assert generate_primes(5) == [2, 3, 5]
def test_up_to_twenty():
assert generate_primes(20) == [2, 3, 5, 7, 11, 13, 17, 19]
d... | [
{
"docstring": null,
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def generate_primes(n):",
"function_name": "generate_primes",
"parameter_list": "(n)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef prime_check(num: int) -> bool:\n if num <= 1:\n return False\n if num == 2 or num == 3:\n return True\n ... | trial_gpt4o_0 | {
"original_instruction": "**Prime Generation with Optimized Prime Check**\n\n### Problem Statement\n\nYou are tasked with writing a function that generates all prime numbers up to a given integer \\( n \\). Your implementation should leverage the provided `prime_check` function to determine primality efficiently.\n\... | 0.758247 | Data_Structure_47460 | C | [
"prime_check",
"generate_primes"
] | 2 | [
[
"generate_primes",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6c2f7600976570721ae8a27d2e7f69bae2846214 | 65ef1b823b93e5b4c50bb92b8a43629a64896923 | |||
v1.0 | complete | Data_Structure | Data_Structure_47097_C | # Import necessary typing
from typing import List
def rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:
"""
Rotate the matrix 90 degrees clockwise.
>>> matrix = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]
... ]
>>> rotate_clockwise(matrix)
[
[7, 4,... | from typing import List
def rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:
"""
Rotate the matrix 90 degrees clockwise.
"""
n = len(matrix)
return [[matrix[n - j - 1][i] for j in range(n)] for i in range(n)]
def rotate_counterclockwise(matrix: List[List[int]]) -> List[List[int]]:
... | from solution import rotate_clockwise, rotate_counterclockwise, invert_top_bottom, composite_transformations
def test_rotate_clockwise():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
result = rotate_clockwise(matrix)
expected = [
[7, 4, 1],
[8, 5, 2],
[9,... | [
{
"docstring": "Rotate the matrix 90 degrees clockwise.",
"function_declaration": "def rotate_clockwise(matrix):",
"function_name": "rotate_clockwise",
"parameter_list": "(matrix)"
},
{
"docstring": "Rotate the matrix 90 degrees counterclockwise.",
"function_declaration": "def rotate_cou... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Rotate the matrix 90 degrees clockwise.\n \"\... | trial_gpt4o_2 | {
"original_instruction": "### Matrix Transformation Challenge\n\nYou are given a square matrix (n x n) containing integers. Your task is to implement three distinct transformations on this matrix and one composite function as follows:\n\n1. **Rotate 90 Degrees Clockwise**: Rotate the matrix elements by 90 degrees in... | 0.560151 | Data_Structure_47097 | C | [
"rotate_clockwise",
"rotate_counterclockwise",
"invert_top_bottom",
"composite_transformations"
] | 4 | [
[
"composite_transformations",
"invert_top_bottom"
],
[
"composite_transformations",
"rotate_clockwise"
],
[
"composite_transformations",
"rotate_counterclockwise"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | b762c8c643f8d5a08af53eeaca9e1c8716068ae7 | 2ac572a28ed6e12778420282f49af794064e5a9d | |||
v1.0 | complete | Data_Structure | Data_Structure_47897_C | def merge_sort(arr: list) -> list:
"""
Sorts the input list using the Merge Sort algorithm.
Args:
arr (list): A list of integers to sort.
Returns:
list: A sorted list of integers in non-decreasing order.
"""
pass
def merge(left: list, right: list, merged: list) -> None:
"""
Me... | def merge_sort(arr: list) -> list:
"""
Sorts the input list using the Merge Sort algorithm.
Args:
arr (list): A list of integers to sort.
Returns:
list: A sorted list of integers in non-decreasing order.
"""
if len(arr) <= 1:
return arr
# Find the mid-point
mid = len(a... | from solution import merge_sort
def test_merge_sort_with_unsorted_array():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_with_sorted_array():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_with_reverse_sorted_array():
assert mer... | [
{
"docstring": "Sorts the input list using the Merge Sort algorithm.\n\nArgs:\narr (list): A list of integers to sort.\n\nReturns:\nlist: A sorted list of integers in non-decreasing order.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts the input list using the Merge Sort algorithm.\n \n Args:\n arr (list): A list of integers to sort.\n ... | trial_gpt4o_2 | {
"original_instruction": "#### Scenario\nAs a software developer in a company that processes large datasets daily, you are tasked with implementing a stable and efficient sorting algorithm. The key requirement is that the algorithm must handle very large arrays efficiently while ensuring that the relative order of e... | 0.6114 | Data_Structure_47897 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | db1093b86b4f8a16482c0f40eb723931cb6c1be0 | c66faa3225343e7da6e5179b2c3ed0ec832a719a | |||
v1.0 | complete | Data_Structure | Data_Structure_47538_C | def safe_diffie_hellman(p: int, a: int) -> bool:
"""Perform Diffie-Hellman Key Exchange.
Args:
p (int): A positive integer (supposedly a large prime number).
a (int): A positive integer (supposedly a primitive root of `p`).
Returns:
bool: True if the key exchange is successful, otherwi... | import sympy
def prime_check(num: int) -> bool:
return sympy.isprime(num)
def find_primitive_root(p: int) -> int:
for g in range(2, p):
if all(pow(g, (p - 1) // q, p) != 1 for q in sympy.factorint(p - 1)):
return g
return -1
def alice_private_key(p: int) -> int:
return 6 # For si... | import pytest
from solution import safe_diffie_hellman, prime_check, find_primitive_root
def test_safe_diffie_hellman_success():
assert safe_diffie_hellman(23, 5) == True
def test_safe_diffie_hellman_fail_non_prime():
assert safe_diffie_hellman(22, 5) == False
def test_safe_diffie_hellman_fail_non_primit... | [
{
"docstring": null,
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def find_primitive_root(p):",
"function_name": "find_primitive_root",
"parameter_list": "(p)"
},
{
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def prime_check(num: int) -> bool:\n \"\"\"Check if a number is prime.\"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True... | trial_gpt4o_9 | {
"original_instruction": "Diffie-Hellman Key Exchange\n\n**Context**: Alice and Bob wish to securely exchange keys over a public channel using the Diffie-Hellman Key Exchange Protocol. To ensure security, they must verify the parameters they use to generate their keys.\n\n#### Question\n\nImplement a function `safe_... | 0.536171 | Data_Structure_47538 | C | [
"prime_check",
"find_primitive_root",
"alice_private_key",
"alice_public_key",
"bob_private_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"safe_diffie_hellman"
] | 9 | [
[
"safe_diffie_hellman",
"alice_private_key"
],
[
"safe_diffie_hellman",
"alice_public_key"
],
[
"safe_diffie_hellman",
"alice_shared_key"
],
[
"safe_diffie_hellman",
"bob_private_key"
],
[
"safe_diffie_hellman",
"bob_public_key"
],
[
"safe_diffie_hell... | 8 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 4f6ed2cac386e5c253ab002b3b723299aa227f66 | 6010da3c664fb34f1b9aa803c7ce0b0958bffae8 | |||
v1.0 | complete | Data_Structure | Data_Structure_48251_C | from typing import List
def search_insert(array: List[int], val: int) -> int:
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def insertion_sort(array: List... | from typing import List
def search_insert(array: List[int], val: int) -> int:
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def insertion_sort(array: List... | from solution import insertion_sort
def test_insertion_sort_example_1():
assert insertion_sort([4, 3, 2, 1]) == [1, 2, 3, 4]
def test_insertion_sort_example_2():
assert insertion_sort([10, 8, 12, 5, 6, 2]) == [2, 5, 6, 8, 10, 12]
def test_insertion_sort_empty():
assert insertion_sort([]) == []
def test_... | [
{
"docstring": null,
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": null,
"function_declaration": "def insertion_sort(array):",
"function_name": "insertion_sort",
"parameter_list": "(a... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n Helper function to determine the insertion index for `val` i... | trial_gpt4o_2 | {
"original_instruction": "### Problem: Insertion Sort with Binary Search Helper\n\nYou are tasked with implementing the `insertion_sort` algorithm, which sorts an array of integers in ascending order. To achieve this efficiently, you will use the provided `search_insert` function to find the appropriate index for ea... | 0.647518 | Data_Structure_48251 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 017cd3b4c638f1b1d9d35a711f4ac2da44da9edd | adba36038dcaf6de9635209c549536fa866f0001 | |||
v1.0 | complete | Data_Structure | Data_Structure_47845_C | def invert_matrix(m):
"""
Implement an optimized matrix inversion function using LU decomposition.
Args:
m (list of list of float): A square matrix represented as a list of lists.
Returns:
list of list of float: The inverse of the input matrix. If the input is invalid or the matrix is... | import numpy as np
def lu_decomposition(matrix):
""" Perform LU decomposition using the Doolittle factorization. """
n = len(matrix)
L = np.zeros((n, n))
U = np.zeros((n, n))
for i in range(n):
L[i][i] = 1.0
for j in range(i, n):
sum = 0.0
for k in range... | from solution import invert_matrix
def test_invert_matrix_2x2():
m = [[4, 3], [3, 2]]
expected = [[-2.0, 3.0], [3.0, -4.0]]
result = invert_matrix(m)
assert np.allclose(result, expected), f"Expected {expected}, got {result}"
def test_invert_matrix_3x3():
m = [
[1, 2, 3],
[0, 1, 4],... | [
{
"docstring": "Perform LU decomposition using the Doolittle factorization. ",
"function_declaration": "def lu_decomposition(matrix):",
"function_name": "lu_decomposition",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def invert_matrix(m):",
"function... | [
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 numpy as np\n\ndef lu_decomposition(matrix):\n \"\"\" Perform LU decomposition using the Doolittle factorization. \"\"\"\n n = len(matrix)\n L... | trial_gpt4o_0 | {
"original_instruction": "### Question: Implement Advanced Matrix Operations\n\nYou are given a task to implement an optimized matrix inversion function. The provided function `invert_matrix(m)` inverts an `n x n` matrix `m`. However, it is inefficient for large matrices due to recursive determinant calculations. Yo... | 0.527215 | Data_Structure_47845 | C | [
"lu_decomposition",
"invert_matrix"
] | 2 | [
[
"invert_matrix",
"lu_decomposition"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 67e92cee73e0c8807eb76b0e1aed5c67fd20902b | 2d58492a91c4cc088d919a938f6b70714eca272d | |||
v1.0 | complete | Data_Structure | Data_Structure_48345_C | from typing import Tuple, Dict, Any
def nearest_neighbor_classify(x: Tuple[float], tSet: Dict[Tuple[float], Any]) -> Any:
"""
Identifies the closest vector in the training set to the input vector using Euclidean distance,
and returns the label associated with that vector.
>>> nearest_neighbor_clas... | from typing import Tuple, Dict, Any
import math
def nearest_neighbor_classify(x: Tuple[float, ...], tSet: Dict[Tuple[float, ...], Any]) -> Any:
"""
Identifies the closest vector in the training set to the input vector using Euclidean distance,
and returns the label associated with that vector.
"""
... | from solution import nearest_neighbor_classify
def test_exact_match():
x = (1.0, 2.0)
tSet = {
(1.0, 2.0): "A",
(0.9, 2.0): "B"
}
assert nearest_neighbor_classify(x, tSet) == "A"
def test_closest_match():
x = (1.0, 2.0)
tSet = {
(1.1, 2.1): "A",
(0.9, 2.0): "C"
... | [
{
"docstring": "Identifies the closest vector in the training set to the input vector using Euclidean distance,\nand returns the label associated with that vector.",
"function_declaration": "def nearest_neighbor_classify(x, tSet):",
"function_name": "nearest_neighbor_classify",
"parameter_list": "(x... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Tuple, Dict, Any\nimport math\n\ndef nearest_neighbor_classify(x: Tuple[float, ...], tSet: Dict[Tuple[float, ...], Any]) -> Any:\n \"\"\... | trial_gpt4o_0 | {
"original_instruction": "You are part of a team developing an intelligent recommendation system. Your task involves implementing the nearest neighbor algorithm to help categorize new data points based on existing labeled data. \n\nImplement a function `nearest_neighbor_classify` that, given an input vector and a la... | 0.627076 | Data_Structure_48345 | C | [
"nearest_neighbor_classify",
"euclidean_distance"
] | 2 | [
[
"nearest_neighbor_classify",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 690a709df8e38aab0e4fdc503d8f8e52c612bd4f | 8982e6fa7b0108294c1f982088583f5ca32b07e4 | |||
v1.0 | complete | Data_Structure | Data_Structure_48383_C | from typing import List
def gcd(a: int, b: int) -> int:
"""
Compute the greatest common divisor of two non-zero integers a and b using the Euclidean algorithm.
>>> gcd(48, 18)
6
>>> gcd(-48, -18)
6
>>> gcd(0, 18)
ValueError
"""
def lcm(a: int, b: int) -> int:
"""
Com... | def gcd(a: int, b: int) -> int:
"""
Returns the greatest common divisor of a and b using the Euclidean algorithm.
"""
if a == 0 or b == 0:
raise ValueError("Inputs must be non-zero integers.")
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
def lcm(a: int, b: in... | from solution import gcd, lcm, trailing_zero, gcd_bit
def test_gcd_basic():
assert gcd(48, 18) == 6
assert gcd(-48, -18) == 6
assert gcd(14, 21) == 7
def test_gcd_edge_cases():
try:
gcd(0, 18)
except ValueError:
assert True
else:
assert False
def test_lcm_basic():
... | [
{
"docstring": "Returns 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": "Returns the least common multiple of a and b.",
"function_declaration": "def lcm... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a: int, b: int) -> int:\n \"\"\"\n Returns the greatest common divisor of a and b using the Euclidean algorithm.\n \"\"\"\n if a == 0 or b... | trial_gpt4o_0 | {
"original_instruction": "#### Context\nYou are working on a project to develop a library of functions related to number theory and integer operations. One of the components that you need to implement involves efficiently determining the greatest common divisor (GCD), least common multiple (LCM), and handling other ... | 0.740059 | Data_Structure_48383 | C | [
"gcd",
"lcm",
"trailing_zero",
"gcd_bit"
] | 4 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 847b024f64940bdb2f25e9d868ff16e055537383 | 24399e6d7c83dc6823d1c9ab5aaac540ac06b0e2 | |||
v1.0 | complete | Data_Structure | Data_Structure_48248_C | def max_flow(capacity: List[List[int]], source: int, sink: int, algorithm: str) -> int:
"""
Determines the maximum flow in the network from source to sink using the specified algorithm.
Args:
capacity: 2D list representing the capacity matrix of the graph (capacity[i][j] is the capacity of edge fro... | from collections import deque
def bfs(C, F, source, sink, P):
visited = [False] * len(C)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, cap in enumerate(C[u]):
if not visited[v] and cap - F[u][v] > 0: # Residual capacity available
... | from solution import max_flow
def test_ford_fulkerson_basic():
capacity = [
[0, 10, 10, 0, 0, 0],
[0, 0, 5, 15, 0, 0],
[0, 0, 0, 10, 10, 0],
[0, 0, 0, 0, 10, 10],
[0, 0, 0, 15, 0, 10],
[0, 0, 0, 0, 0, 0]
]
assert max_flow(capacity, 0, 5, "ford_fulkerson") == ... | [
{
"docstring": null,
"function_declaration": "def bfs(C, F, source, sink, P):",
"function_name": "bfs",
"parameter_list": "(C, F, source, sink, P)"
},
{
"docstring": null,
"function_declaration": "def dfs(C, F, u, sink, P):",
"function_name": "dfs",
"parameter_list": "(C, F, u, s... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(C, F, source, sink, P):\n visited = [False] * len(C)\n queue = deque([source])\n visited[source] = True\n ... | trial_gpt4o_0 | {
"original_instruction": "### Scenario\nYou are tasked with implementing a network routing system for a telecommunication company, ensuring optimal bandwidth utilization without any data loss. The network is modeled as a directed graph where nodes represent network routers/switches and edges represent communication ... | 0.58425 | Data_Structure_48248 | C | [
"bfs",
"dfs",
"ford_fulkerson",
"edmonds_karp",
"dinic_bfs",
"dinic_dfs",
"dinic",
"max_flow"
] | 8 | [
[
"dinic",
"dinic_bfs"
],
[
"dinic",
"dinic_dfs"
],
[
"edmonds_karp",
"bfs"
],
[
"ford_fulkerson",
"dfs"
],
[
"max_flow",
"dinic"
],
[
"max_flow",
"edmonds_karp"
],
[
"max_flow",
"ford_fulkerson"
]
] | 7 | [] | false | [] | false | pytest | true | [] | true | 5b4e2fe7e88462a0ae2b1aac1460e5db00e957f6 | 39d949c1b59cb8d666c3aef6cd809c063125b4dd | |||
v1.0 | complete | Data_Structure | Data_Structure_48464_C | from typing import List
import math
def efficient_bucket_sort(arr: List[int], bucket_size: int) -> List[int]:
"""
Sorts a list of non-negative integers using the bucket sort algorithm.
Parameters:
arr (List[int]): List of non-negative integers to sort.
bucket_size (int): The size of ea... | from typing import List
import math
def efficient_bucket_sort(arr: List[int], bucket_size: int) -> List[int]:
"""
Sorts a list of non-negative integers using the bucket sort algorithm.
Parameters:
arr (List[int]): List of non-negative integers to sort.
bucket_size (int): The size of ea... | from solution import efficient_bucket_sort
def test_empty_array():
assert efficient_bucket_sort([], 5) == []
def test_single_element_array():
assert efficient_bucket_sort([1], 5) == [1]
def test_sorted_array():
assert efficient_bucket_sort([1, 2, 3, 4, 5], 2) == [1, 2, 3, 4, 5]
def test_reverse_sorted_a... | [
{
"docstring": "Sorts a list of non-negative integers using the bucket sort algorithm.\n\nParameters:\n arr (List[int]): List of non-negative integers to sort.\n bucket_size (int): The size of each bucket.\n \nReturns:\n List[int]: Sorted list of integers.",
"function_declaration": "def efficien... | [
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 efficient_bucket_sort(arr, bucket_size):\n \"\"\"\n Sorts an array using an efficient bucket sort algorithm.\n \n Parameters:\n arr (list o... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement an Efficient Bucket Sort Algorithm\n\n#### Background\nBucket Sort is a sorting algorithm that distributes elements of an array into a number of buckets. Each bucket is then sorted individually using a different sorting algorithm. Finally, the sorted buckets are conc... | 0.619145 | Data_Structure_48464 | C | [
"efficient_bucket_sort",
"quicksort"
] | 2 | [
[
"efficient_bucket_sort",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d2a6de87f9fc88e252a57803f204b80b3886ef40 | 5b7a00a95dea49113f46e82fb4dafb53e1e66fe3 | |||
v1.0 | complete | Data_Structure | Data_Structure_48562_C | def rsa_encryption(message: str, k: int) -> tuple:
""" Encrypt the given message using RSA encryption with a key length of `k` bits.
Parameters
----------
message : str
The input message consisting of printable ASCII characters.
k : int
The bit length of the RSA keys (16 <= k <=... | import random
from sympy import isprime, gcd
from sympy.ntheory.generate import randprime
import math
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
return x1 + m0 if x1 < 0 else x1
def generat... | from solution import rsa_encryption
def test_rsa_encryption():
message = "HELLO"
k = 64
n, e, d, encrypted_message = rsa_encryption(message, k)
# Check if n, e, d have been generated properly
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
# Check... | [
{
"docstring": null,
"function_declaration": "def modinv(a, m):",
"function_name": "modinv",
"parameter_list": "(a, m)"
},
{
"docstring": "Generate RSA keys given a bit length `k`.\nReturns (n, e, d) for modulus n, public exponent e, and private exponent d.",
"function_declaration": "def... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime_candidate(bit_length):\n candidate = random.getrandbits(bit_length)\n candid... | trial_gpt4o_1 | {
"original_instruction": "You are given an implementation of the RSA key generation algorithm and the procedures for encryption and decryption. Your task is to complete the function `rsa_encryption` which takes in a string message and a bit length `k`, and returns the encrypted message using RSA encryption. You need... | 0.691367 | Data_Structure_48562 | C | [
"modinv",
"generate_rsa_keys",
"rsa_encrypt",
"rsa_encryption"
] | 4 | [
[
"generate_rsa_keys",
"modinv"
],
[
"rsa_encryption",
"generate_rsa_keys"
],
[
"rsa_encryption",
"rsa_encrypt"
]
] | 3 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 1e1deb83b6779c46b7945a41ea173c3ced3c3d58 | 840e1967f622ccddc0ed963c462beed3d959c39a | |||
v1.0 | complete | Data_Structure | Data_Structure_48088_C | def custom_bitonic_sort(arr, reverse=False):
"""
Sorts the given array using Bitonic Sort, supporting array lengths that are not powers of two.
Parameters:
arr (list): List of comparable elements to be sorted.
reverse (bool): If True, sort the array in ascending order; if False, sort in descend... | def next_power_of_two(n):
""" Returns the next power of two greater than or equal to n """
if n == 0:
return 1
n -= 1
n |= n >> 1
n |= n >> 2
n |= n >> 4
n |= n >> 8
n |= n >> 16
n += 1
return n
def bitonic_merge(arr, low, cnt, direction):
""" Helper function to merg... | from solution import custom_bitonic_sort
def test_custom_bitonic_sort_ascending():
assert custom_bitonic_sort([3, 7, 2, 5, 1], reverse=True) == [1, 2, 3, 5, 7]
assert custom_bitonic_sort([10, 2, 3], reverse=True) == [2, 3, 10]
assert custom_bitonic_sort([], reverse=True) == []
assert custom_bitonic_sor... | [
{
"docstring": "Returns the next power of two greater than or equal to n ",
"function_declaration": "def next_power_of_two(n):",
"function_name": "next_power_of_two",
"parameter_list": "(n)"
},
{
"docstring": "Helper function to merge bitonic sequence ",
"function_declaration": "def bito... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef bitonic_compare_and_swap(arr, i, j, direction):\n if (direction == (arr[i] > arr[j])):\n arr[i], arr[j] = arr[j, arr[i]\n\ndef bi... | trial_gpt4o_9 | {
"original_instruction": "You are given the implementation of Bitonic Sort. Your task is to modify the provided algorithm to handle arrays whose sizes are not powers of two by padding the array with `float('inf')` values to the next power of two, then sorting the padded array, and finally returning the sorted non-in... | 0.710434 | Data_Structure_48088 | C | [
"next_power_of_two",
"bitonic_merge",
"bitonic_sort_recursive",
"bitonic_sort",
"custom_bitonic_sort"
] | 5 | [
[
"bitonic_sort",
"bitonic_sort_recursive"
],
[
"bitonic_sort_recursive",
"bitonic_merge"
],
[
"custom_bitonic_sort",
"bitonic_sort"
],
[
"custom_bitonic_sort",
"next_power_of_two"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | a64376ed1d376c7b90adbf0bcb472c242736abb5 | b3f0c574ed41c70896db5ff47fe96e16d3ff9084 | |||
v1.0 | complete | Data_Structure | Data_Structure_47707_C | def enhanced_stoogesort(arr: List[int], l: int, h: int, threshold: int) -> None:
""" Sorts an array of integers using Stooge Sort with an enhancement
of switching to Insertion Sort for smaller subarrays.
Args:
arr (List[int]): The array of integers to be sorted.
l (int): The starting index ... | def insertion_sort(arr, l, h):
for i in range(l + 1, h + 1):
key = arr[i]
j = i - 1
while j >= l and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def enhanced_stoogesort(arr, l, h, threshold):
if h - l + 1 <= threshold:
insertion_sort... | from solution import enhanced_stoogesort
def test_stooge_sort_small_array():
arr = [9, 1, 4, 7, 3]
enhanced_stoogesort(arr, 0, 4, 2)
assert arr == [1, 3, 4, 7, 9]
def test_stooge_sort_medium_array():
arr = [5, 2, 9, 1, 5, 6]
enhanced_stoogesort(arr, 0, 5, 3)
assert arr == [1, 2, 5, 5, 6, 9]
d... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, l, h):",
"function_name": "insertion_sort",
"parameter_list": "(arr, l, h)"
},
{
"docstring": null,
"function_declaration": "def enhanced_stoogesort(arr, l, h, threshold):",
"function_name": "enhanced_stoogesort",
... | [
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 insertion_sort(arr: List[int], l: int, h: int) -> None:\n for i in range(l + 1, h + 1):\n key = arr[i]\n j = i... | trial_gpt4o_2 | {
"original_instruction": "Implement Stooge Sort with Enhancements\n\n#### Scenario:\nYou are given an array of integers that you need to sort efficiently for academic research purposes. Although Stooge Sort is generally inefficient, this exercise will help you understand recursive algorithms and their characteristic... | 0.627859 | Data_Structure_47707 | C | [
"insertion_sort",
"enhanced_stoogesort"
] | 2 | [
[
"enhanced_stoogesort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 33dd361d5b3f944908c68e0d7084dac114369d59 | 07af2e6503db8982bdc4e9e3b5422b566af3234d | |||
v1.0 | complete | Data_Structure | Data_Structure_48077_C | def sudoku_solver(board: List[List[str]]) -> bool:
"""
Solves the given Sudoku puzzle in-place.
Parameters:
board (List[List[str]]): 2D list representing a partially filled 9x9 Sudoku grid.
Empty cells are represented by '.'.
Returns:
bool: True if the board is su... | from typing import List, Tuple
def find_unassigned_cell(board: List[List[str]]) -> Tuple[int, int]:
min_options = float('inf')
best_cell = (-1, -1)
for r in range(9):
for c in range(9):
if board[r][c] == '.':
options = get_possible_values(board, r, c)
... | from solution import sudoku_solver
def test_sudoku_solver():
board = [
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
[... | [
{
"docstring": null,
"function_declaration": "def find_unassigned_cell(board):",
"function_name": "find_unassigned_cell",
"parameter_list": "(board)"
},
{
"docstring": null,
"function_declaration": "def get_possible_values(board, row, col):",
"function_name": "get_possible_values",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef sudoku_solver(board: List[List[str]]) -> bool:\n def is_valid(board, row, col, num):\n for i in range(9):\n ... | trial_gpt4o_2 | {
"original_instruction": "### Sudoku Solver with Heuristic Backtracking\n\n#### Background\nSudoku is a popular number puzzle that requires filling a 9x9 grid in such a way that each row, column, and each of the 9 3x3 subgrids contains all digits from 1 to 9 exactly once. Given a partially filled grid, we need to fi... | 0.560139 | Data_Structure_48077 | C | [
"find_unassigned_cell",
"get_possible_values",
"sudoku_solver"
] | 3 | [
[
"find_unassigned_cell",
"get_possible_values"
],
[
"sudoku_solver",
"find_unassigned_cell"
],
[
"sudoku_solver",
"get_possible_values"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 0cd6f44d36c23a2107bbe6aa4b881bf31bc3eefa | 2ee625acce4d78c7b5d0d6fa4286e588e19f9089 | |||
v1.0 | complete | Data_Structure | Data_Structure_48015_C | def bezout_and_check(num1: int, num2: int, check_val: int) -> (int, int, bool):
"""
Compute the Bézout coefficients s and t such that for two given integers num1 and num2:
num1 * s + num2 * t = GCD(num1, num2)
Additionally, check if a third integer can be expressed using these coefficients.
>>> be... | def extended_euclidean_algorithm(a, b):
"""
Uses the Extended Euclidean Algorithm to find the integers x and y such that:
ax + by = gcd(a, b)
"""
if a == 0:
return b, 0, 1
else:
gcd, x1, y1 = extended_euclidean_algorithm(b % a, a)
x = y1 - (b // a) * x1
y = x1
... | from solution import bezout_and_check
def test_bezout_and_check_30_20_10():
s, t, result = bezout_and_check(30, 20, 10)
assert result == True
assert 30 * s + 20 * t == 10
def test_bezout_and_check_35_15_5():
s, t, result = bezout_and_check(35, 15, 5)
assert result == True
assert 35 * s + 15 * ... | [
{
"docstring": "Uses the Extended Euclidean Algorithm to find the integers x and y such that:\nax + by = gcd(a, b)",
"function_declaration": "def extended_euclidean_algorithm(a, b):",
"function_name": "extended_euclidean_algorithm",
"parameter_list": "(a, b)"
},
{
"docstring": "Finds the Béz... | [
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 extended_gcd(a, b):\n if b == 0:\n return a, 1, 0\n g, x1, y1 = extended_gcd(b, a % b)\n x = y1\n y = x1 - (a // b) * y1\n return g,... | trial_gpt4o_1 | {
"original_instruction": "### Question: Computing and Using Bézout's Coefficients\n\nYou are tasked with writing a function to compute the Bézout coefficients \\( s \\) and \\( t \\) such that for two given integers `num1` and `num2`:\n\n\\[ num1 \\cdot s + num2 \\cdot t = \\text{GCD}(num1, num2) \\]\n\nUsing the Ex... | 0.645971 | Data_Structure_48015 | C | [
"extended_euclidean_algorithm",
"bezout_and_check"
] | 2 | [
[
"bezout_and_check",
"extended_euclidean_algorithm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5a1a155faec083c3cffc421eb479a56244d24667 | 1cbb8a593c1c4f5029e3792f4c21535e1fb07cf0 | |||
v1.0 | complete | Data_Structure | Data_Structure_48609_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 `small` is a subtree of `big`.
>>> big = TreeNode(3)
>>> big.left = TreeNode(4)
>>> b... | 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
if not big:
return False
if same_tree(big, small):
retu... | import pytest
from solution import TreeNode, is_subtree
def test_is_subtree_case_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,
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, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef are_identical(root1, root2):\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Subtree Validation\n\nGiven two binary trees represented by their root nodes `big` and `small`, write a function `is_subtree(big, small)` to determine if `small` is a subtree of `big`. \n\nA subtree of a node in a binary tree should consist of that node and all its descendants... | 0.572847 | Data_Structure_48609 | C | [
"is_subtree",
"same_tree"
] | 2 | [
[
"is_subtree",
"same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 71095c56dbbe24327364b1297dffe18f84f9ae57 | 018daf43277cdb5dcae8aa6098a5d9d280e3783f | |||
v1.0 | complete | Data_Structure | Data_Structure_47762_C | def validate_initial_state(chain, state):
"""
Validate if the initial state exists in the Markov chain and has outgoing transitions.
:param chain: dict - The Markov chain with state transitions.
:param state: str - The initial state.
:return: bool - True if the state is valid, else False.
>>> ... | import random
def validate_initial_state(chain, state):
"""
Validate if the initial state exists in the Markov chain and has outgoing transitions.
:param chain: dict - The Markov chain with state transitions.
:param state: str - The initial state.
:return: bool - True if the state is valid, el... | from solution import validate_initial_state, validate_chain, markov_chain_simulation
# Test validate_initial_state
def test_validate_initial_state():
chain = {
'A': {'B': 0.5, 'C': 0.5},
'B': {'A': 0.5, 'C': 0.5},
'C': {}
}
assert validate_initial_state(chain, 'A') == True
asser... | [
{
"docstring": "Validate if the initial state exists in the Markov chain and has outgoing transitions.\n\n:param chain: dict - The Markov chain with state transitions.\n:param state: str - The initial state.\n:return: bool - True if the state is valid, else False.",
"function_declaration": "def validate_ini... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef validate_initial_state(chain, state):\n \"\"\"\n Validate if the initial state exists in the Markov chain and has outgoing transiti... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implementing Advanced Markov Chain Mechanisms\n\n#### Context\nYou are tasked to improve and extend the functionality of a Markov Chain simulator that transitions between states based on predefined probabilities. This Markov Chain is represented using dictionaries, and your ta... | 0.426554 | Data_Structure_47762 | C | [
"validate_initial_state",
"validate_chain",
"markov_chain_simulation"
] | 3 | [
[
"markov_chain_simulation",
"validate_initial_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1f80efb6edb5f989f0ecee9a82b9cf64a011e6a8 | 2014a88c4c8b4ad626a48f9fb0814dda5d4687bb | |||
v1.0 | complete | Data_Structure | Data_Structure_48741_C | def find_min_perfect_squares(n: int) -> int:
"""
Given an integer N, find the minimum number of perfect squares whose sum
equals N, where a perfect square is defined as k^2 for some integer k.
Ensure that the solution is efficient with time complexity of O(sqrt(N)).
>>> find_min_perfect_squares(9)
... | import math
def is_square(n):
sq = int(math.sqrt(n))
return sq * sq == n
def find_min_perfect_squares(n):
"""
Returns the minimum number of perfect squares whose sum equals n.
"""
# Check if n is a perfect square
if is_square(n):
return 1
# Check if n can be decomposed int... | from solution import find_min_perfect_squares
def test_example_1():
assert find_min_perfect_squares(9) == 1
def test_example_2():
assert find_min_perfect_squares(10) == 2
def test_example_3():
assert find_min_perfect_squares(12) == 3
def test_example_4():
assert find_min_perfect_squares(31) == 4
de... | [
{
"docstring": null,
"function_declaration": "def is_square(n):",
"function_name": "is_square",
"parameter_list": "(n)"
},
{
"docstring": "Returns the minimum number of perfect squares whose sum equals n.",
"function_declaration": "def find_min_perfect_squares(n):",
"function_name": ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef find_min_perfect_squares(N):\n \"\"\"\n Returns the minimum number of perfect squares whose sum equals N.\n \"\"\"\n # Check fo... | trial_gpt4o_1 | {
"original_instruction": "Given an integer `N`, write a function `find_min_perfect_squares(N)` that finds the minimum number of perfect squares whose sum equals N, where a perfect square is defined as k^2 for some integer k. The function should return an integer between 1 and 4 as guaranteed by Lagrange's four-squar... | 0.808087 | Data_Structure_48741 | C | [
"is_square",
"find_min_perfect_squares"
] | 2 | [
[
"find_min_perfect_squares",
"is_square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 16b67f60ebd56a0fceaed6b358d3f18a31f01f93 | ac355cb7d12bce2d30ce2e2519d62408e589e9c1 | |||
v1.0 | complete | Data_Structure | Data_Structure_48516_C | def search_insert(array: list, value: int) -> int:
""" Find the index where value should be inserted to keep array sorted. """
pass
def optimized_insertion_sort(array: list) -> list:
""" Perform an optimized insertion sort on the input array using binary search.
>>> optimized_insertion_sort([4, 2, 3, 1... | from bisect import bisect_left
def search_insert(array, value):
"""
Find the index where value should be inserted to keep array sorted.
"""
return bisect_left(array, value)
def optimized_insertion_sort(array: list) -> list:
"""
Perform an optimized insertion sort on the input array using binar... | from solution import optimized_insertion_sort
def test_optimized_insertion_sort_basic():
assert optimized_insertion_sort([4, 2, 3, 1]) == [1, 2, 3, 4]
assert optimized_insertion_sort([7, 2, 5, 3, 9]) == [2, 3, 5, 7, 9]
def test_optimized_insertion_sort_already_sorted():
assert optimized_insertion_sort([1,... | [
{
"docstring": "Find the index where value should be inserted to keep array sorted.",
"function_declaration": "def search_insert(array, value):",
"function_name": "search_insert",
"parameter_list": "(array, value)"
},
{
"docstring": "Perform an optimized insertion sort on the input array 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": "def search_insert(arr, val):\n \"\"\"\n A helper function that uses binary search to find the insertion index for val in arr.\n \"\"\"\n low, high... | trial_gpt4o_2 | {
"original_instruction": "#### Scenario\n\nYou have been hired to optimize a warehouse inventory system. The system must keep an ordered list of product prices; however, products arrive in an arbitrary order. You need to implement an optimized insertion sort algorithm that leverages binary search to find the correct... | 0.612611 | Data_Structure_48516 | C | [
"search_insert",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 94d6b1687eedfdb1c0b3768c3259dd4712ea69b7 | cca6732bebf2ea0a98a8ebcc951189f1e7f7e2c1 | |||
v1.0 | complete | Data_Structure | Data_Structure_48443_C | def secure_key_exchange(a: int, p: int) -> bool:
"""Verify if the Diffie-Hellman key exchange process generates the same shared secret key for both parties.
:param a: An integer representing a candidate primitive root.
:param p: An integer representing a candidate prime number.
:return: `True` if b... | import random
def is_prime(n):
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def gcd(a, b):
wh... | from solution import secure_key_exchange
from solution import is_prime, gcd, 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(5) == True
assert is_prime(23) == True
assert is_prime(24) == False
def test_g... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def secure_key_exchange(a: int, p: int) -> bool:\n import random\n \n def is_prime(n):\n \"\"\"Return True if n is a prime number, else False.... | trial_gpt4o_4 | {
"original_instruction": "You are tasked with implementing a secure key exchange protocol between two parties, Alice and Bob. Specifically, you will use the Diffie-Hellman key exchange algorithm, while ensuring the primality and suitability of the given numbers.\n\n#### Problem Statement\nImplement the function `sec... | 0.559483 | Data_Structure_48443 | C | [
"is_prime",
"gcd",
"find_primitive_root",
"secure_key_exchange"
] | 4 | [
[
"find_primitive_root",
"is_prime"
],
[
"secure_key_exchange",
"find_primitive_root"
],
[
"secure_key_exchange",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 86221765ac57fabab8911b07fe10fa580778d561 | 01b0e974df69589e63073e430b9d0e042ab3eb4b | |||
v1.0 | complete | Data_Structure | Data_Structure_48773_C | def find_power_sum_numbers(low: int, high: int) -> List[int]:
"""
Find power sum numbers within the specified range [low, high] inclusive.
A power sum number is a number where the sum of its digits each raised to a consecutive power starting from 1 equals the original number.
>>> find_power_sum_numbers(... | def is_power_sum_number(n):
"""
Check if a number n is a power sum number.
"""
digits = list(map(int, str(n)))
sum_of_powers = sum(d ** (i + 1) for i, d in enumerate(digits))
return sum_of_powers == n
def find_power_sum_numbers(low, high):
"""
Find all power sum numbers in the range [lo... | from solution import find_power_sum_numbers
def test_find_power_sum_numbers_basic_range():
assert find_power_sum_numbers(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_find_power_sum_numbers_example_range():
assert find_power_sum_numbers(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
def test_find_power_sum_numb... | [
{
"docstring": "Check if a number n is a power sum number.",
"function_declaration": "def is_power_sum_number(n):",
"function_name": "is_power_sum_number",
"parameter_list": "(n)"
},
{
"docstring": "Find all power sum numbers in the range [low, high] inclusive.",
"function_declaration": ... | [
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_power_sum_number(n):\n \"\"\"\n Check if a number n is a power sum number.\n \"\"\"\n digits = list(map(int, str(n)))\n sum_of_powers = ... | trial_gpt4o_0 | {
"original_instruction": "#### Scenario\nYou are given a special class of numbers called \"power sum numbers.\" These numbers possess a unique property where the sum of their digits, each raised to a consecutive power starting from 1, equals the original number. For example, 89 satisfies this property because 8^1 +... | 0.607134 | Data_Structure_48773 | C | [
"is_power_sum_number",
"find_power_sum_numbers"
] | 2 | [
[
"find_power_sum_numbers",
"is_power_sum_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f8a8cf465cb24327aad200bfdc330c40a590449f | ed2677e0b0a51c5a9e0763c38d090973ef686aa9 | |||
v1.0 | complete | Data_Structure | Data_Structure_48678_C | def power_matrix(mat: list, p: int) -> list:
"""Raised the given square matrix to the power p.
Args:
mat (List[List[int]]): A square matrix of integers (d x d dimensions where 1 <= d <= 50).
p (int): A non-negative integer (0 <= p <= 10^9).
Returns:
List[List[int]]: The matrix ... | def matrix_multiply(mat1, mat2):
size = len(mat1)
result = [[0] * size for _ in range(size)]
for i in range(size):
for j in range(size):
for k in range(size):
result[i][j] += mat1[i][k] * mat2[k][j]
return result
def identity_matrix(size):
return [[1 if... | from solution import power_matrix, matrix_multiply
def test_power_matrix_example1():
mat = [
[1, 2],
[3, 4]
]
p = 2
expected = [
[7, 10],
[15, 22]
]
assert power_matrix(mat, p) == expected
def test_power_matrix_example2():
mat = [
[1, 0],
[0,... | [
{
"docstring": null,
"function_declaration": "def matrix_multiply(mat1, mat2):",
"function_name": "matrix_multiply",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": null,
"function_declaration": "def identity_matrix(size):",
"function_name": "identity_matrix",
"parameter_list"... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def identity_matrix(size):\n \"\"\"\n Returns the identity matrix of given size.\n \"\"\"\n return [[1 if i == j else 0 for j in range(size)] for ... | trial_gpt4o_1 | {
"original_instruction": "### Matrix Exponentiation Programming Assessment\n\n#### Context:\n\nMatrix exponentiation is a fundamental technique used in various applications ranging from computer graphics to solving linear recurrence relations efficiently. The core algorithm leverages repeated squaring to achieve log... | 0.561255 | Data_Structure_48678 | C | [
"matrix_multiply",
"identity_matrix",
"power_matrix"
] | 3 | [
[
"power_matrix",
"identity_matrix"
],
[
"power_matrix",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | aa357048290d763985a59ee764f877112c778857 | dd028d4675942089a252398c644f0516cfe0f784 | |||
v1.0 | complete | Data_Structure | Data_Structure_48078_C | from typing import List
def maximum_flow(capacity: List[List[int]], source: int, sink: int) -> int:
""" Calculate the maximum number of vehicles that can be transported from source to sink
based on the capacity of the roads between intersections.
:param capacity: A 2D list of integers where capacity[i][j]... | from collections import deque
from typing import List
def bfs(capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:
visited = [False] * len(capacity)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, cap in enumerate(capacit... | from solution import maximum_flow
def test_simple_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 maximum_flow(capacity, sou... | [
{
"docstring": null,
"function_declaration": "def bfs(capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow(capacity, source, sink):",
"function_name": "maximum... | [
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 maximum_flow(capacity: list[list[int]], source: int, sink: int) -> int:\n from collections import deque\n \n n = len(capacity)\n residual_capa... | trial_gpt4o_2 | {
"original_instruction": "Maximum Flow in Transportation Network\n\n**Context**:\nIn a city transportation network, various intersections are linked by roads with a certain capacity representing the maximum number of vehicles that can pass through per unit time. The goal is to determine the maximum number of vehicle... | 0.634707 | Data_Structure_48078 | C | [
"bfs",
"maximum_flow"
] | 2 | [
[
"maximum_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9a00ac7597a25ccafb7ee71b01efea903660b5e8 | ee509907f02deba2ab97635ec1b4aa24fd684cc1 | |||
v1.0 | complete | Data_Structure | Data_Structure_48700_C | def binary_injection_sort(arr: List[int]) -> List[int]:
"""Sort an array using a modified Insertion Sort algorithm that uses binary search
to find the correct insertion point for each element.
>>> binary_injection_sort([4, 2, 8, 5, 7])
[2, 4, 5, 7, 8]
>>> binary_injection_sort([5, 4, 3, 2, 1])
... | def binary_search(arr, val, start, end):
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
start = mid + 1
else:
end = mid
return start
def binary_injection_sort(arr):
for i in range(1, len(arr)):
val = arr[i]
pos = binary_search(... | from solution import binary_injection_sort
def test_binary_injection_sort_unsorted():
assert binary_injection_sort([4, 2, 8, 5, 7]) == [2, 4, 5, 7, 8]
def test_binary_injection_sort_reverse_sorted():
assert binary_injection_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_binary_injection_sort_already_sorte... | [
{
"docstring": null,
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": null,
"function_declaration": "def binary_injection_sort(arr):",
"function_name": "binary_injection_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binary_search(arr, val, start, end):\n \"\"\"\n Helper function to perform binary search.\n It returns the index where the value should be insert... | trial_gpt4o_2 | {
"original_instruction": "#### Context\nYou are tasked with implementing a more efficient variant of the Insertion Sort algorithm to handle larger datasets. You will modify the traditional Insertion Sort to use binary search to locate the position where the current element should be inserted.\n\n#### Task\nWrite a f... | 0.671117 | Data_Structure_48700 | C | [
"binary_search",
"binary_injection_sort"
] | 2 | [
[
"binary_injection_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ea6c268bd2a4ab2e6027014c324fb5ea8fabcdc | 2e07b3cb2513d32b486a6ab6123adfd8d33ef533 | |||
v1.0 | complete | Data_Structure | Data_Structure_48615_C | def rsa_generate_keys(bit_length):
"""
Generates RSA keys of the specified bit length.
Parameters:
bit_length (int): An integer representing the bit length of the RSA modulus `n`.
Returns:
tuple: Returns a tuple `(public_key, private_key, modulus)`:
- `public_key`: A tuple `(... | import random
from sympy import isprime, gcd, mod_inverse
def generate_prime(bit_length):
while True:
p = random.getrandbits(bit_length)
if isprime(p):
return p
def rsa_generate_keys(bit_length):
"""
Generates RSA keys of the specified bit length.
"""
e = 65537 # commo... | from solution import rsa_generate_keys, rsa_encrypt, rsa_decrypt
def test_rsa_generate_keys_bit_length_16():
public_key, private_key, modulus = rsa_generate_keys(16)
assert type(public_key) == tuple
assert type(private_key) == int
assert type(modulus) == int
def test_rsa_generate_keys_bit_length_32()... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bit_length):",
"function_name": "generate_prime",
"parameter_list": "(bit_length)"
},
{
"docstring": "Generates RSA keys of the specified bit length.",
"function_declaration": "def rsa_generate_keys(bit_length):",
"func... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef rsa_generate_keys(bit_length):\n def generate_large_prime(bits):\n while True:\n ... | trial_gpt4o_1 | {
"original_instruction": "### RSA Encryption/Decryption Implementation\n\nYou are tasked with securing a communication channel using RSA encryption. You need to create functions to securely transmit numeric data using RSA. Below is the RSA key generation and encryption code provided for your reference. You need to i... | 0.769953 | Data_Structure_48615 | C | [
"generate_prime",
"rsa_generate_keys",
"rsa_encrypt",
"rsa_decrypt"
] | 4 | [
[
"rsa_generate_keys",
"generate_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 6668f2f5d74c539f0421459d085c36ba89e97bb4 | dc7c9347e95648ea28397bdf1280b62e51231778 | |||
v1.0 | complete | Data_Structure | Data_Structure_48553_C | from typing import List
def ladder_length(begin_word: str, end_word: str, word_list: List[str]) -> int:
"""
Finds the shortest transformation sequence from begin_word to end_word,
changing only one letter at a time, using words from word_list.
:param begin_word: Starting word for the transformation.
... | from collections import deque
from typing import List
def ladder_length(begin_word: str, end_word: str, word_list: List[str]) -> int:
"""
Finds the shortest transformation sequence from begin_word to end_word,
changing only one letter at a time, using words from word_list.
"""
if end_word not in wo... | from solution import ladder_length
def test_ladder_length_basic_case():
assert ladder_length("hit", "cog", ["hot","dot","dog","lot","log","cog"]) == 5
def test_ladder_length_no_such_transformation():
assert ladder_length("hit", "cog", ["hot","dot","dog","lot","log"]) == -1
def test_ladder_length_same_begin_e... | [
{
"docstring": "Finds the shortest transformation sequence from begin_word to end_word,\nchanging only one letter at a time, using words from word_list.",
"function_declaration": "def ladder_length(begin_word, end_word, word_list):",
"function_name": "ladder_length",
"parameter_list": "(begin_word, ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef ladder_length(begin_word, end_word, word_list):\n def get_neighbors(word):\n neighbors = []\n for i in r... | trial_gpt4o_1 | {
"original_instruction": "#### Problem Description:\n\nYou are given two words, `begin_word` and `end_word`, and a dictionary of words called `word_list`. All the words in the dictionary and the given words are of the same length and contain only lowercase alphabets. You are to find the length of the shortest transf... | 0.609398 | Data_Structure_48553 | C | [
"ladder_length",
"visit_word_node"
] | 2 | [
[
"ladder_length",
"visit_word_node"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 186f3d640643822368bc9f9170422b7cc5db56ad | 490dcdce8ea997512e9add59d1184ce451ec3882 | |||
v1.0 | complete | Data_Structure | Data_Structure_48844_C | def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
""" Implement the radix sort algorithm.
Takes a list of non-negative integers and sorts it using the radix sort method.
Args:
arr (List[int]): A list of non-negative integers.
simulation (bool): If set to True, prints the ar... | from typing import List
def counting_sort(arr, exp, simulation):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp)
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
in... | def test_radix_sort_empty_array():
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort([42]) == [42]
def test_radix_sort_multiple_elements():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_sorted_input():
a... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool) -> None:\n n = len(arr)\n output = [0] * n\n count = [0] * 1... | trial_gpt4o_1 | {
"original_instruction": "Radix Sort Implementation\n\nWe need to implement the radix sort algorithm. Your task is to write a function that takes a list of non-negative integers and sorts it using the radix sort method.\n\n### Input\n- A list `arr` of non-negative integers `arr = [n1, n2, n3, ..., nk]` where `0 <= n... | 0.662935 | Data_Structure_48844 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 3fb4200d4d1f90edda90e6b38f704d0ce2020c6b | 09ce573d416269b70cdbe64fd38953e2a50f02c6 | |||
v1.0 | complete | Data_Structure | Data_Structure_48777_C | def advanced_gcd_and_trailing_zeros(a: int, b: int) -> (int, int, int, int):
"""
Calculate the GCD using bitwise operations and count trailing zeros in binary.
>>> advanced_gcd_and_trailing_zeros(40, 24) (8, 3, 3, 3)
>>> advanced_gcd_and_trailing_zeros(0, 5) (5, 0, 0, 0)
>>> advanced_gcd_and_traili... | def count_trailing_zeros(n):
"""
Counts the number of trailing zeroes in the binary representation of n.
"""
if n == 0:
return 0
count = 0
while (n & 1) == 0:
n >>= 1
count += 1
return count
def gcd(a, b):
"""
Computes the GCD of a and b using bitwise operati... | from solution import advanced_gcd_and_trailing_zeros
def test_advanced_gcd_and_trailing_zeros_example_case():
assert advanced_gcd_and_trailing_zeros(40, 24) == (8, 3, 3, 3)
def test_advanced_gcd_and_trailing_zeros_zero_case():
assert advanced_gcd_and_trailing_zeros(0, 5) == (5, 0, 0, 0)
assert advanced_gc... | [
{
"docstring": "Counts the number of trailing zeroes in the binary representation of n.",
"function_declaration": "def count_trailing_zeros(n):",
"function_name": "count_trailing_zeros",
"parameter_list": "(n)"
},
{
"docstring": "Computes the GCD of a and b using bitwise operations.",
"f... | [
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 advanced_gcd_and_trailing_zeros(a: int, b: int) -> (int, int, int, int):\n \"\"\"\n Calculates the GCD of a and b using bitwise operations and count... | trial_gpt4o_2 | {
"original_instruction": "### Question: Enhanced GCD and Trailing Zero Count\n\nYou are asked to implement a new function that combines the calculation of GCD using bitwise operations and also provides the count of trailing zeros in binary representation of the inputs and the result. The function should handle edge ... | 0.68584 | Data_Structure_48777 | C | [
"count_trailing_zeros",
"gcd",
"advanced_gcd_and_trailing_zeros"
] | 3 | [
[
"advanced_gcd_and_trailing_zeros",
"count_trailing_zeros"
],
[
"advanced_gcd_and_trailing_zeros",
"gcd"
],
[
"gcd",
"count_trailing_zeros"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | df7c3c19c8f2158305fbb869f31e0118123c18ae | 000702b0152dbaa3dfdea19a894c3191cb44535f | |||
v1.0 | complete | Data_Structure | Data_Structure_48833_C | def prime_check(num: int) -> bool:
""" Checks if a number is prime.
>>> prime_check(2)
True
>>> prime_check(3)
True
>>> prime_check(4)
False
>>> prime_check(29)
True
"""
pass
def find_primitive_root(n: int) -> List[int]:
""" Finds all primitive roots of a given prime num... | import random
from typing import List, Tuple
def prime_check(num: int) -> bool:
"""
Checks if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0... | from solution import prime_check, find_primitive_root, diffie_hellman_key_exchange
def test_prime_check():
assert prime_check(2)
assert prime_check(3)
assert not prime_check(4)
assert prime_check(5)
assert not prime_check(1)
assert prime_check(29)
assert not prime_check(30)
def test_find_p... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Finds all primitive roots of a given prime number n.",
"function_declaration": "def find_primitive_root(n):",
"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List, Tuple\n\ndef prime_check(num: int) -> bool:\n \"\"\"\n Checks if a number is a prime number.\n \"\"\"\n if... | trial_gpt4o_2 | {
"original_instruction": "Secure Messaging System\n\nYou have been tasked to implement a secure messaging system that uses the Diffie-Hellman key exchange protocol to establish a shared secret key between two parties, Alice and Bob. Follow the given steps and constraints to correctly perform the key exchange and ver... | 0.620444 | Data_Structure_48833 | C | [
"prime_check",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 3 | [
[
"diffie_hellman_key_exchange",
"prime_check"
],
[
"find_primitive_root",
"prime_check"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ab58a26409f2bf744f195d10b0bf2520cf8c0ed5 | 9b45fc3795d1978065606cc34daf086acddb84f8 | |||
v1.0 | complete | Data_Structure | Data_Structure_48954_C | from typing import List
def wildcard_search(text: str, pattern: str) -> List[int]:
""" Finds all starting indices of substrings in the text that match the pattern with wildcards.
The pattern may contain wildcards represented by the character '?', which matches any single character.
Args:
text (str... | from typing import List
def kmp_partial_match_table(pattern: str) -> List[int]:
""" Generates the KMP partial match table (also known as the "pi" table). """
m = len(pattern)
pi = [0] * m
k = 0
for q in range(1, m):
while k > 0 and (pattern[k] != pattern[q] and pattern[k] != '?' and pa... | from solution import wildcard_search
def test_wildcard_search_simple():
assert wildcard_search('hello there hero!', 'he?lo') == [0]
def test_wildcard_search_multiple_matches():
assert wildcard_search('abcabcabcabc', 'a?c') == [0, 3, 6, 9]
def test_wildcard_search_repeated_chars():
assert wildcard_search(... | [
{
"docstring": "Generates the KMP partial match table (also known as the \"pi\" table). ",
"function_declaration": "def kmp_partial_match_table(pattern):",
"function_name": "kmp_partial_match_table",
"parameter_list": "(pattern)"
},
{
"docstring": "Finds all starting indices of substrings in... | [
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": "from typing import List\n\ndef compute_prefix_function_wildcard(pattern: str) -> List[int]:\n \"\"\"\n Computes the prefix function for the given patter... | trial_gpt4o_6 | {
"original_instruction": "**String Matching with Wildcards**\n\nGiven a text string and a pattern string, write a function `wildcard_search` to find all starting indices of substrings in the text that match the pattern. The pattern can contain wildcards represented by the character `?`, which matches any single char... | 0.583443 | Data_Structure_48954 | C | [
"kmp_partial_match_table",
"wildcard_search"
] | 2 | [
[
"wildcard_search",
"kmp_partial_match_table"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 68fa70b6f0593a6894da28e63e661f53e840a295 | e58c591c3049b1a53d40d776f556f1fed821a791 | |||
v1.0 | complete | Data_Structure | Data_Structure_48361_C | def generate_key(k, seed=None):
""" Generates an RSA public-private key pair where k is the number of bits in the modulus n.
>>> n, e, d = generate_key(16, seed=42)
>>> isinstance(n, int) and n > 0
True
>>> isinstance(e, int) and e > 0
True
>>> isinstance(d, int) and d > 0
True
"""
... | import random
from sympy import isprime, mod_inverse
def generate_key(k, seed=None):
"""
Generates an RSA public-private key pair where k is the number of bits in the modulus n.
"""
if seed:
random.seed(seed)
# Ensure k is at least 8 bits
if k < 8:
raise ValueError("Bit length k... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16, seed=42)
assert isinstance(n, int) and n > 0
assert isinstance(e, int) and e > 0
assert isinstance(d, int) and d > 0
def test_encrypt_decrypt():
n, e, d = generate_key(16, seed=42)
data ... | [
{
"docstring": "Generates an RSA public-private key pair where k is the number of bits in the modulus n.",
"function_declaration": "def generate_key(k, seed=None):",
"function_name": "generate_key",
"parameter_list": "(k, seed=None)"
},
{
"docstring": null,
"function_declaration": "def g... | [
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": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_large_prime(bits, seed=None):\n \"\"\"Generate a random large prime number of approxi... | trial_gpt4o_3 | {
"original_instruction": "### RSA Key Generation and Message Encryption/Decryption\n\nGiven the RSA encryption system, your task is to implement the functions needed to generate an RSA key pair (public and private keys) and use these to encrypt and decrypt a given message. \n\n#### Task\nImplement the following func... | 0.75095 | Data_Structure_48361 | C | [
"generate_key",
"get_prime",
"get_coprime",
"gcd",
"encrypt",
"decrypt"
] | 6 | [
[
"generate_key",
"get_coprime"
],
[
"generate_key",
"get_prime"
],
[
"get_coprime",
"gcd"
]
] | 3 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 684e85c9f16055c8cf7fbd203e196e38df6bd3f3 | 4e15d2d48cd39875e07e9801481a85bc8fbf66b9 | |||
v1.0 | complete | Data_Structure | Data_Structure_48425_C | from typing import List
def invert_matrix(matrix: List[List[int]]) -> List[List[float]]:
"""
Returns the inverse of the given n x n matrix of integers. If the matrix is not invertible, returns an error code inside a nested list.
Error codes:
- [[-1]] if the input is not a valid matrix.
- [[-2... | from typing import List
def determinant(matrix: List[List[int]], n: int) -> int:
""" Helper function to compute determinant of given matrix of size n x n """
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for c in r... | from solution import invert_matrix
def test_invert_2x2_matrix():
matrix = [
[4, 7],
[2, 6]
]
result = invert_matrix(matrix)
expected = [
[0.6, -0.7],
[-0.2, 0.4]
]
for r, e in zip(result, expected):
assert all(abs(val_r - val_e) < 1e-9 for val_r, val_e in... | [
{
"docstring": "Helper function to compute determinant of given matrix of size n x n ",
"function_declaration": "def determinant(matrix, n):",
"function_name": "determinant",
"parameter_list": "(matrix, n)"
},
{
"docstring": "Helper function to get cofactor of matrix[p][q] ",
"function_d... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef invert_matrix(matrix: List[List[int]]) -> List[List[float]]:\n def matrix_minor(m, i, j):\n return [row[:j] + row[j+1... | trial_gpt4o_2 | {
"original_instruction": "You are given an \\(n \\times n\\) matrix of integers. Your task is to write a function `invert_matrix(matrix: List[List[int]]) -> List[List[float]]` that returns the inverse of the matrix. If the matrix is not invertible, return an error code inside a nested list.\n\n### Guidelines\n1. Imp... | 0.564885 | Data_Structure_48425 | C | [
"determinant",
"get_cofactor",
"adjoint",
"invert_matrix"
] | 4 | [
[
"adjoint",
"determinant"
],
[
"adjoint",
"get_cofactor"
],
[
"invert_matrix",
"adjoint"
],
[
"invert_matrix",
"determinant"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 5ae92777f008d2d0bd6caf5ebf717f1ebf49fb79 | de0b9ca86157927b848af4409512585c35912b3d | |||
v1.0 | complete | Data_Structure | Data_Structure_49069_C | class Node:
def __init__(self, value):
self.value = value
self.next = None
def find_intersection(head1: Node, head2: Node) -> Node:
"""
Find the first common node where the two singly linked lists intersect, if any.
Args:
head1 (Node): The head of the first linked list.
hea... | class Node:
def __init__(self, value):
self.value = value
self.next = None
def get_length(head):
length = 0
while head:
length += 1
head = head.next
return length
def find_intersection(head1, head2):
"""
Returns the first common node in two singly linked lists, ... | import pytest
from solution import Node, find_intersection
def test_no_intersection():
head1 = Node(1)
head1.next = Node(2)
head1.next.next = Node(3)
head2 = Node(4)
head2.next = Node(5)
head2.next.next = Node(6)
assert find_intersection(head1, head2) is None
def test_intersection_at_fir... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\ndef find_intersection(head1: Node, head2: Node) -> Node:\... | trial_gpt4o_1 | {
"original_instruction": "You are given two singly linked lists, potentially sharing some nodes. Your task is to find the first common node where the lists intersect, if any. \n\n### Function Signature\n```python\ndef find_intersection(head1: Node, head2: Node) -> Node:\n```\n\n### Input\n* Two heads of linked lists... | 0.615155 | Data_Structure_49069 | C | [
"get_length",
"find_intersection"
] | 2 | [
[
"find_intersection",
"get_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 09854739ae46e6116cddb668d2475c9a09ab35c3 | 45977178fc1b3791e82846b47bc4d780e46242d7 | |||
v1.0 | complete | Data_Structure | Data_Structure_49012_C | from typing import List
def bfs(capacity, flow, source, sink, parent):
pass
def edmonds_karp(capacity: List[List[int]], source: int, sink: int) -> int:
""" Compute the maximum flow in a flow network using the Edmonds-Karp algorithm.
Args:
capacity: A two-dimensional list of integers where capacity... | from collections import deque
from typing import List
def bfs(capacity, flow, source, sink, parent):
visited = set()
queue = deque([source])
visited.add(source)
while queue:
u = queue.popleft()
for v in range(len(capacity)):
if v not in visited and capacity[u][v] - flow[u][v... | from solution import edmonds_karp
def test_edmonds_karp_example():
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 edmonds_karp(capa... | [
{
"docstring": null,
"function_declaration": "def bfs(capacity, flow, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, flow, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def edmonds_karp(capacity, source, sink):",
"function_nam... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List\n\ndef edmonds_karp(capacity: List[List[int]], source: int, sink: int) -> int:\n n = len(capacity)\n... | trial_gpt4o_2 | {
"original_instruction": "### Maximum Flow Problem in Flow Network\n\nIn this task, you are required to implement the **Edmonds-Karp** algorithm to compute the maximum flow in a flow network. The implementation must demonstrate an understanding of BFS for finding augmenting paths and augmenting the flow according to... | 0.542193 | Data_Structure_49012 | C | [
"bfs",
"edmonds_karp"
] | 2 | [
[
"edmonds_karp",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 466e1a6bd975ca514c8dbbdec345cecfc1c4ce92 | c3e90672c215d7dfce2d7b2bbe07301c3d2a95fc | |||
v1.0 | complete | Data_Structure | Data_Structure_48734_C | from typing import List
def find_order(a: int, n: int) -> int:
""" Returns the smallest positive integer k such that a^k % n == 1,
or -1 if no such integer exists.
>>> find_order(10, 7) == 6
>>> find_order(2, 9) == 6
>>> find_order(3, 11) == 5
>>> find_order(11, 13) == 12
>>> find_order(2, ... | import math
from functools import reduce
from sympy import gcd
def find_order(a, n):
"""
Returns the smallest positive integer k such that a^k % n == 1,
or -1 if no such integer exists.
"""
if gcd(a, n) != 1:
return -1
k = 1
ak = a % n
while ak != 1:
ak = (ak * a) %... | from solution import find_order, euler_totient, find_primitive_root
def test_find_order():
assert find_order(10, 7) == 6
assert find_order(2, 9) == 6
assert find_order(3, 11) == 5
assert find_order(11, 13) == 12
assert find_order(2, 4) == -1 # gcd(2, 4) != 1, so should return -1
def test_euler_to... | [
{
"docstring": "Returns the smallest positive integer k such that a^k % n == 1,\nor -1 if no such integer exists.",
"function_declaration": "def find_order(a, n):",
"function_name": "find_order",
"parameter_list": "(a, n)"
},
{
"docstring": "Computes Euler's Totient function φ(n), which coun... | [
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 gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef find_order(a, n):\n \"\"\" Find the smallest positive integer k such that a^k % ... | trial_gpt4o_2 | {
"original_instruction": "You are given three functions: `find_order`, `euler_totient`, and `find_primitive_root`, which are used to determine the primitive roots of a given integer `n` based on advanced number theory concepts.\n\n**Objectives**:\n1. Implement the `find_order` function, which finds the smallest posi... | 0.55429 | Data_Structure_48734 | C | [
"find_order",
"euler_totient",
"find_primitive_root",
"prime_factors"
] | 4 | [
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"prime_factors"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 1b5aebb0328067fcf9569d182de4d63318c3bf08 | c254eedcd3ddfa00511223cc6d393830b98d7d64 | |||
v1.0 | complete | Data_Structure | Data_Structure_49074_C | import math
def nearest_neighbor(x: tuple, tSet: dict) -> any:
"""
Find the class label of the nearest neighbor to the point x in the training set tSet.
Parameters:
x (tuple): A new data point represented as a tuple of integers or floats.
tSet (dict): A dictionary where keys are tuples... | import math
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points.
"""
return math.sqrt(sum((p1 - p2) ** 2 for p1, p2 in zip(point1, point2)))
def nearest_neighbor(x: tuple, tSet: dict) -> any:
"""
Find the class label of the nearest neighbor to the po... | from solution import nearest_neighbor
def test_simple_case():
x = (2.0, 3.0)
tSet = {
(1.0, 2.0): 'A',
(4.0, 6.0): 'B',
(2.5, 3.5): 'C'
}
assert nearest_neighbor(x, tSet) == 'C'
def test_case_with_negative_coordinates():
x = (0.0, 0.0)
tSet = {
(-1.0, -1.0): 'A'... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef nearest_neighbor(x, tSet):\n \"\"\"\n Finds the nearest neighbor to the point x in the training set tSet.\n Args:\n x : tuple \... | trial_gpt4o_2 | {
"original_instruction": "## Nearest Neighbor Classifier\n\n### Context\nYou're working on a simple machine learning project and need to implement the Nearest Neighbor algorithm. This algorithm will classify a new data point based on its 'nearest' neighbor in an existing training set of classified points. The proble... | 0.64712 | Data_Structure_49074 | C | [
"euclidean_distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 874360aa146540e3881ef175c0af04ff5b9fad7b | 626ff31b83e2cdf99b25321b84a28c614732be35 | |||
v1.0 | complete | Data_Structure | Data_Structure_49267_C | def optimized_rotate_array(array, k):
"""
Rotates the array 'k' times to the right.
:param array: List[int] - List of integers that need to be rotated
:param k: int - Number of steps to rotate the array
:return: List[int] - Rotated array
Examples:
>>> optimized_rotate_array([1, 2, 3, 4, 5,... | def optimized_rotate_array(array, k):
"""
Rotates the array 'k' times to the right.
:param array: List[int] - List of integers that need to be rotated
:param k: int - Number of steps to rotate the array
:return: List[int] - Rotated array
"""
n = len(array)
if n == 0:
return arra... | from solution import optimized_rotate_array
def test_rotate_normal_case():
assert optimized_rotate_array([1, 2, 3, 4, 5, 6, 7], 3) == [5, 6, 7, 1, 2, 3, 4]
def test_rotate_with_zero_k():
assert optimized_rotate_array([1, 2, 3, 4, 5], 0) == [1, 2, 3, 4, 5]
def test_rotate_with_large_k():
assert optimized_... | [
{
"docstring": "Rotates the array 'k' times to the right.\n\n:param array: List[int] - List of integers that need to be rotated\n:param k: int - Number of steps to rotate the array\n:return: List[int] - Rotated array",
"function_declaration": "def optimized_rotate_array(array, k):",
"function_name": "op... | [
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_rotate_array(array, k):\n \"\"\"\n Rotates the array 'k' times to the right.\n\n :param array: List[int] - List of integers that need t... | trial_gpt4o_2 | {
"original_instruction": "### Context\nYou are given an array that you need to rotate to the right by `k` steps. The need for such rotations is common in algorithm design, where rearrangements optimize search or organization processes.\n\n### Task\nImplement a function `optimized_rotate_array` which encapsulates the... | 0.599554 | Data_Structure_49267 | C | [
"optimized_rotate_array",
"reverse"
] | 2 | [
[
"optimized_rotate_array",
"reverse"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c849c616f2511e51598416ffdc1dcfb024f77af6 | 52ecf9ec4f246f3a3c7b8a508e2a36064cc9dee3 | |||
v1.0 | complete | Data_Structure | Data_Structure_49090_C | def bitonic_sort(arr: list, reverse: bool = False) -> list:
"""
Bitonic sort function to sort an array with size a power of two.
Handles empty input arrays gracefully, ensuring they return an empty list.
Raises a ValueError if the input array's length is not a power of two.
Parameters:
arr... | def bitonic_sort(arr: list, reverse: bool = False) -> list:
"""
Bitonic sort function to sort an array with size a power of two.
"""
if len(arr) == 0:
return []
if not is_power_of_two(len(arr)):
raise ValueError("The length of the input list is not a power of two.")
def... | from solution import bitonic_sort, is_power_of_two
import pytest
def test_bitonic_sort_empty_array():
assert bitonic_sort([]) == []
def test_bitonic_sort_single_element():
assert bitonic_sort([1]) == [1]
def test_bitonic_sort_two_elements():
assert bitonic_sort([2, 1]) == [1, 2]
def test_bitonic_sort_po... | [
{
"docstring": "Bitonic sort function to sort an array with size a power of two.",
"function_declaration": "def bitonic_sort(arr, reverse=False):",
"function_name": "bitonic_sort",
"parameter_list": "(arr, reverse=False)"
},
{
"docstring": null,
"function_declaration": "def is_power_of_t... | [
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 bitonic_sort(arr: list, reverse: bool = False) -> list:\n if len(arr) == 0:\n return arr\n \n if not (len(arr) > 0 and (len(arr) & (len(ar... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nYou are building a sorting module for a parallel processing system that often deals with data sizes that are powers of two. The current implementation of bitonic sort needs to be enhanced to ensure it handles a common edge case effectively.\n\n### Task\nImplement the `bitonic_... | 0.616118 | Data_Structure_49090 | C | [
"bitonic_sort",
"is_power_of_two"
] | 2 | [
[
"bitonic_sort",
"is_power_of_two"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 29373cc78b230f7438470d678ffdbbf71db63648 | dd69ff67e21a76021dad956931641628e5c81508 | |||
v1.0 | complete | Data_Structure | Data_Structure_49095_C | def decimal_to_binary_util(val: str) -> str:
""" Converts an 8-bit decimal number to an 8-bit binary string.
>>> decimal_to_binary_util("255")
"11111111"
>>> decimal_to_binary_util("0")
"00000000"
>>> decimal_to_binary_util("128")
"10000000"
>>> decimal_to_binary_util("1")
"00000001"... | def decimal_to_binary_util(val):
"""
Converts an 8-bit decimal number to an 8-bit binary string.
"""
return format(int(val), '08b')
def decimal_to_binary_ip(ip):
"""
Converts an IP address from dotted-decimal notation to binary format.
"""
return '.'.join(decimal_to_binary_util(octet) f... | def test_decimal_to_binary_util():
assert decimal_to_binary_util("255") == "11111111"
assert decimal_to_binary_util("0") == "00000000"
assert decimal_to_binary_util("128") == "10000000"
assert decimal_to_binary_util("1") == "00000001"
assert decimal_to_binary_util("170") == "10101010"
def test_deci... | [
{
"docstring": "Converts an 8-bit decimal number to an 8-bit binary string.",
"function_declaration": "def decimal_to_binary_util(val):",
"function_name": "decimal_to_binary_util",
"parameter_list": "(val)"
},
{
"docstring": "Converts an IP address from dotted-decimal notation to binary form... | [
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 decimal_to_binary_util(val: str) -> str:\n \"\"\"\n Converts an 8-bit decimal number (integer value from 0 to 255) \n to an 8-bit binary string.\... | trial_gpt4o_2 | {
"original_instruction": "### Question\n\n#### Context\nYou are working on a networking tool that needs to display IP addresses in their binary representation format. To achieve this, you must convert IP addresses provided in decimal notation to their corresponding binary format.\n\n#### Task\nWrite two functions, `... | 0.644804 | Data_Structure_49095 | C | [
"decimal_to_binary_util",
"decimal_to_binary_ip"
] | 2 | [
[
"decimal_to_binary_ip",
"decimal_to_binary_util"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 135bb0047a17270b143c7ee9fd5f6b81e272d758 | bf764971915121179231bbe32e176bd2e439750a | |||
v1.0 | complete | Data_Structure | Data_Structure_49280_C | def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
"""
Efficiently sorts a list of non-negative integers using the Radix Sort algorithm.
Args:
arr: List[int] - a list of non-negative integers (0 ≤ arr[i] ≤ 10^9)
simulation: bool - an optional flag to print the internal state at ... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i ... | from solution import radix_sort
def test_radix_sort_example():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_single_element():
assert radix_sort([5]) == [5]
def test_radix_sort_empty_list():
assert radix_sort([]) == []
def test_radix_sort_i... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # St... | trial_gpt4o_2 | {
"original_instruction": "### Question: Radix Sort Implementation\nYou are tasked with implementing the `radix_sort` function that efficiently sorts a list of non-negative integers using the Radix Sort algorithm. This algorithm should handle the digits of numbers from the least significant to the most significant.\n... | 0.673739 | Data_Structure_49280 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c252441c11b59c5da988e6e95906b91084c51cf8 | 4f099a5e10ddaf10e9ad6acb2ec34390a34e39a0 | |||
v1.0 | complete | Data_Structure | Data_Structure_49288_C | from typing import List, Tuple
def is_sorted(arr: List[int]) -> 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 shuffle(arr: List[int]) -> List[int]:
"""
Helper function to... | import random
from typing import List, Tuple
def is_sorted(arr: List[int]) -> 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 shuffle(arr: List[int]) -> List[int]:
"""
Help... | from solution import constrained_bogo_sort
def test_bogo_sort_sorted_array():
arr = [1, 2, 3, 4, 5]
sorted_arr, iterations = constrained_bogo_sort(arr, 10)
assert sorted_arr == [1, 2, 3, 4, 5]
assert iterations == 0
def test_bogo_sort_reverse_sorted_array():
arr = [5, 4, 3, 2, 1]
sorted_arr, i... | [
{
"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 shuffle the array randomly.",
"function_declaration": "def shuffle(arr):",
"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List, Tuple\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"Check if the list is sorted.\"\"\"\n return all(arr[i] <... | trial_gpt4o_2 | {
"original_instruction": "### Bogo Sort Simulation with Additional Constraints\n\n**Scenario**: You have encountered a whimsical sorting algorithm called Bogo Sort. However, in this magical land, it is used in a unique context at a magical marketplace lottery system where occasionally items are picked in a rush, cau... | 0.662788 | Data_Structure_49288 | C | [
"is_sorted",
"shuffle",
"constrained_bogo_sort"
] | 3 | [
[
"constrained_bogo_sort",
"is_sorted"
],
[
"constrained_bogo_sort",
"shuffle"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ecd2185b91679cc13468dc598f0f3e51ae2ff864 | 4c558c414f8856604c2995889094dd02c6bb2d12 | |||
v1.0 | complete | Data_Structure | Data_Structure_48476_C | from typing import List
def hybrid_quick_sort(arr: List[int], threshold: int = 10, simulation: bool = False) -> List[int]:
""" Implements a hybrid quick sort that uses the median-of-three method for pivot selection
and switches to insertion sort for small sub-arrays.
Args:
arr (List[int]): A ... | def median_of_three(arr, low, high):
mid = (low + high) // 2
if arr[low] > arr[mid]:
arr[low], arr[mid] = arr[mid], arr[low]
if arr[low] > arr[high]:
arr[low], arr[high] = arr[high], arr[low]
if arr[mid] > arr[high]:
arr[mid], arr[high] = arr[high], arr[mid]
return mid
def i... | from solution import hybrid_quick_sort
def test_hybrid_quick_sort_normal_case():
arr = [3, 6, 8, 10, 1, 2, 1]
assert hybrid_quick_sort(arr) == [1, 1, 2, 3, 6, 8, 10]
def test_hybrid_quick_sort_with_threshold():
arr = [3, 6, 8, 10, 1, 2, 1]
assert hybrid_quick_sort(arr, threshold=2) == [1, 1, 2, 3, 6, ... | [
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, low, high):",
"function_name": "insertion_sort",
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insertion_sort(arr, left, right):\n for i in range(left + 1, right + 1):\n key = arr[i]\n j = i - 1\n while j >= left and arr[j] >... | trial_gpt4o_1 | {
"original_instruction": "### Quick Sort Optimization and Implementation\n\nQuick Sort is a widely used sorting algorithm known for its efficiency in average cases while having potential performance pitfalls with poor pivot choices. Your task is to implement a hybrid version of Quick Sort that improves upon the trad... | 0.58026 | Data_Structure_48476 | C | [
"median_of_three",
"insertion_sort",
"quick_sort_helper",
"hybrid_quick_sort"
] | 4 | [
[
"hybrid_quick_sort",
"quick_sort_helper"
],
[
"quick_sort_helper",
"insertion_sort"
],
[
"quick_sort_helper",
"median_of_three"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 49fa4f4c08fba34cdb1cf5d0743aafc5a7add3ee | d5dc00cdea3729b4b5dd9e1de21b16a31ad2d439 | |||
v1.0 | complete | Data_Structure | Data_Structure_49467_C | from typing import List
def iterative_quick_sort(arr: List[int]) -> List[int]:
""" Sorts an array of integers in ascending order using the iterative Quick Sort algorithm.
Args:
arr (List[int]): The list of integers to be sorted.
Returns:
List[int]: The sorted list of integers.
Exampl... | def iterative_quick_sort(arr):
"""
Sorts the array using the iterative version of Quick Sort.
"""
if len(arr) == 0:
return arr
stack = [(0, len(arr) - 1)]
while stack:
low, high = stack.pop()
if low < high:
pivot_index = partition(arr, low, high)
... | from solution import iterative_quick_sort
def test_iterative_quick_sort_empty():
assert iterative_quick_sort([]) == []
def test_iterative_quick_sort_single_element():
assert iterative_quick_sort([1]) == [1]
def test_iterative_quick_sort_sorted():
assert iterative_quick_sort([1, 2, 3, 4, 5]) == [1, 2,... | [
{
"docstring": "Sorts the array using the iterative version of Quick Sort.",
"function_declaration": "def iterative_quick_sort(arr):",
"function_name": "iterative_quick_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def iterative_quick_sort(arr):\n \"\"\"\n Sorts a list using an iterative implementation of the quicksort algorithm.\n \"\"\"\n if len(arr) < 2:\n... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement the Function to Sort an Array Using Iterative Quick Sort\n\n#### Context:\nYou are tasked with implementing a more efficient sorting algorithm to handle larger datasets more efficiently than Exchange Sort. Quick Sort offers better average-case performance with O(n lo... | 0.663289 | Data_Structure_49467 | C | [
"iterative_quick_sort",
"partition"
] | 2 | [
[
"iterative_quick_sort",
"partition"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f10f0c3d245f935528ffd8f0b7c80da778983b9f | 6ec9ef05958384babd2f1456342bd6f3dabeccb6 | |||
v1.0 | complete | Data_Structure | Data_Structure_48713_C | ### Problem Description
You are given a 2D board containing characters and a list of words. Your task is to write a function `find_words_in_board(board, words)` which returns a list of words from the given list that can be formed in the board. The words must be constructed from letters of sequentially adjacent cells (... | class TrieNode:
def __init__(self):
self.children = {}
self.word = None
def build_trie(words):
root = TrieNode()
for word in words:
node = root
for letter in word:
if letter not in node.children:
node.children[letter] = TrieNode()
node... | from solution import find_words_in_board
def test_find_words_in_board_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_in_board(board, words)
expec... | [] | [
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": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.word = None\n\ndef build_trie(words):\n root = TrieNode()\n for word ... | trial_gpt4o_0 | {
"original_instruction": "<|Analysis Begin|>\n\n### Algorithm/Data Structure: \nThis algorithm implements a **Trie** (Prefix Tree) combined with **Backtracking** to solve the \"Word Search II\" problem, which involves finding all words from a list that exist in a given board.\n\n### Complexity:\n- **Time Complexity*... | 0.622559 | Data_Structure_48713 | C | [
"build_trie",
"find_words_in_board"
] | 2 | [
[
"find_words_in_board",
"build_trie"
]
] | 1 | [] | false | [
"TrieNode"
] | true | pytest | true | [] | true | 2cababda224a433e247b3d2d614cd2a22355d464 | 0427f05a0d901ef2d1b42eeac53b14c186c7d35e | |||
v1.0 | complete | Data_Structure | Data_Structure_49592_C | from typing import Tuple, Dict, Any
def classify_vector(input_vector: Tuple[int, ...], training_set: Dict[Tuple[int, ...], Any]) -> Any:
"""
Classifies the input vector based on the nearest neighbor principle.
Parameters:
input_vector (Tuple[int, ...]): The vector to be classified.
training_set (... | from typing import Tuple, Dict, Any
import math
def calculate_distance(v1: Tuple[int, ...], v2: Tuple[int, ...]) -> float:
"""
Calculates the Euclidean distance between two vectors.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def classify_vector(input_vector: Tuple[int, ...], train... | from solution import classify_vector
def test_classify_vector_single_element():
training_set = {
(1,): 'A',
(2,): 'B',
(3,): 'C'
}
input_vector = (2,)
assert classify_vector(input_vector, training_set) == 'B'
def test_classify_vector_two_elements():
training_set = {
... | [
{
"docstring": "Calculates the Euclidean distance between two vectors.",
"function_declaration": "def calculate_distance(v1, v2):",
"function_name": "calculate_distance",
"parameter_list": "(v1, v2)"
},
{
"docstring": "Classifies the input vector based on the nearest neighbor principle.\n\nP... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Tuple, Dict, Any\nimport math\n\ndef classify_vector(input_vector: Tuple[int, ...], training_set: Dict[Tuple[int, ...], Any]) -> Any:\n ... | trial_gpt4o_2 | {
"original_instruction": "You are part of a development team creating a basic machine learning library. You need to implement a core classification feature using the Nearest Neighbor algorithm. Your task is to write a function to classify an input vector based on the closest vectors in a given training set.\n\n### F... | 0.521049 | Data_Structure_49592 | C | [
"calculate_distance",
"classify_vector"
] | 2 | [
[
"classify_vector",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8c956c8f0931b99e5f3d8a8796e1fd8f40f36a4a | a341309c7773140fde4987d78d5e1131c2ea21f4 | |||
v1.0 | complete | Data_Structure | Data_Structure_48836_C | def maximum_flow_bfs(adjacency_matrix: List[List[int]]) -> int:
""" Compute the maximum flow in a given flow network using the Breadth-First Search based Edmonds-Karp algorithm.
Args:
adjacency_matrix (List[List[int]]): A 2D list of integers representing the n x n adjacency matrix of the network graph.... | from collections import deque
from typing import List
def bfs(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:
visited = [False] * len(residual_graph)
queue = deque([source])
visited[source] = True
while queue:
node = queue.popleft()
for... | from solution import maximum_flow_bfs
def test_maximum_flow_simple():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow_bfs(graph) == 23
def test_maxim... | [
{
"docstring": null,
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(adjacency_matrix):",
"function_name"... | [
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_capacity(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool... | trial_gpt4o_1 | {
"original_instruction": "### Question: Maximum Flow in a Network with BFS (Edmonds-Karp Algorithm)\n\n**Context**: You are working as a network engineer for a company that manages extensive data networks. One of your tasks is to ensure efficient data transfer from a source server to a sink server through the networ... | 0.567775 | Data_Structure_48836 | C | [
"bfs",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8eddd8fe27148d0059cd9a573d0b94a92206a259 | 915d7861118521e8e5c1997256af79b69abb234e | |||
v1.0 | complete | Data_Structure | Data_Structure_49561_C | from typing import List, Union
def is_safe_prime_with_primitive_roots(p: int) -> Union[List[int], str]:
"""Determines whether a given number p is a safe prime and, if so, returns its primitive roots.
A prime number `p` is called a safe prime if `(p-1)/2` is also a prime number.
Args:
p (i... | from typing import List, Union
import math
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
re... | from solution import is_safe_prime_with_primitive_roots
def test_prime_is_safe():
assert is_safe_prime_with_primitive_roots(7) == [3, 5]
assert is_safe_prime_with_primitive_roots(11) == [2, 6, 7, 8]
assert is_safe_prime_with_primitive_roots(23) == [5, 7, 10, 11, 14, 15, 17, 19, 20, 21]
def test_prime_not_... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def is_safe_prime_with_primitive_roots(p):",
"function_name": "is_safe_prime_with_primitive_roots",
"parameter_li... | [
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, Union\n\ndef is_safe_prime_with_primitive_roots(p: int) -> Union[List[int], str]:\n def is_prime(n):\n \"\"\"Helper functio... | trial_gpt4o_4 | {
"original_instruction": "### Question: Determining Safe Prime Numbers and Their Primitive Roots\n\n#### Problem Statement\n\nA prime number `p` is called a **safe prime** if `(p-1)/2` is also a prime number. Safe primes are notable in cryptography for their resistance to certain attacks. Your task is to write a fun... | 0.610162 | Data_Structure_49561 | C | [
"is_prime",
"is_safe_prime_with_primitive_roots"
] | 2 | [
[
"is_safe_prime_with_primitive_roots",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b4c4f40af2d8e9d00d23131048c18e5024f85aad | 44362e88bc50236f49e283d4b1abce00e44cab2e | |||
v1.0 | complete | Data_Structure | Data_Structure_49304_C | from typing import List
def find_word_squares(words: List[str]) -> List[List[str]]:
"""Create a function that generates all possible word squares from a given set of words.
A word square is an arrangement of words in a square grid such that each row reads the same as the corresponding column.
Arg... | from typing import List, Dict, Tuple, Set
def build_prefix_map(words: List[str]) -> Dict[str, List[str]]:
prefix_map = {}
for word in words:
for i in range(len(word)):
prefix = word[:i+1]
if prefix not in prefix_map:
prefix_map[prefix] = []
prefix_map... | from solution import find_word_squares
def test_find_word_squares_multiple_squares():
words = ["area", "lead", "wall", "lady", "ball"]
result = find_word_squares(words)
expected_output = [
["wall", "area", "lead", "lady"],
["ball", "area", "lead", "lady"]
]
assert sorted(result) == ... | [
{
"docstring": null,
"function_declaration": "def build_prefix_map(words):",
"function_name": "build_prefix_map",
"parameter_list": "(words)"
},
{
"docstring": null,
"function_declaration": "def backtrack(step, word_len, word_square, results, prefix_map):",
"function_name": "backtrac... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import defaultdict\n\ndef find_word_squares(words: List[str]) -> List[List[str]]:\n def build_prefix_dict(words):... | trial_gpt4o_2 | {
"original_instruction": "<|Analysis Begin|>\n\n### Core Identification\n* **Algorithm/Data Structure**: The given code constructs \"word squares\" using a backtracking search algorithm.\n* **Complexity**:\n - **Time Complexity**: Worst-case time complexity is O(N * 26^L), where N is the number of words, and L is t... | 0.59564 | Data_Structure_49304 | C | [
"build_prefix_map",
"backtrack",
"find_word_squares"
] | 3 | [
[
"find_word_squares",
"backtrack"
],
[
"find_word_squares",
"build_prefix_map"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 94002b2236e948ab8be2f3dae178918c53ebd0c5 | 5f34667f405b689919c48c59cb5d0651b92eafe9 | |||
v1.0 | complete | Data_Structure | Data_Structure_49125_C | def update(bit_tree: list, idx: int, val: int) -> None:
"""
Updates the Fenwick Tree at given index by adding val to it.
Fenwick Tree indices are 1-based, so we need to adjust the given index.
"""
pass
def query(bit_tree: list, idx: int) -> int:
"""
Returns the sum of the array from start t... | def update(bit_tree, idx, val):
"""
Updates the Fenwick Tree at given index by adding val to it.
Fenwick Tree indices are 1-based, so we need to adjust the given index.
"""
idx += 1 # Convert to 1-based index
while idx < len(bit_tree):
bit_tree[idx] += val
idx += idx & -idx
def... | from solution import update, query, construct
def test_construct():
frequencies = [3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3]
bit_tree = construct(frequencies)
expected_bit_tree = [0, 3, 5, -1, 10, 5, 9, -3, 19, 7, 9, 3]
# Only testing some elements to ensure correctness
assert bit_tree[:6] == expected_bit... | [
{
"docstring": "Updates the Fenwick Tree at given index by adding val to it.\nFenwick Tree indices are 1-based, so we need to adjust the given index.",
"function_declaration": "def update(bit_tree, idx, val):",
"function_name": "update",
"parameter_list": "(bit_tree, idx, val)"
},
{
"docstri... | [
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 update(bit_tree, idx, val):\n \"\"\"\n Updates the Fenwick Tree at given index by adding val to it.\n Fenwick Tree indices are 1-based, so we nee... | trial_gpt4o_0 | {
"original_instruction": "You are provided with a list of integers representing frequencies of occurrences of various events. Your task is to efficiently handle queries related to the sum of frequencies up to a specific index and also update the frequency of an event at a specific index. You will implement a Fenwick... | 0.535691 | Data_Structure_49125 | C | [
"update",
"query",
"construct"
] | 3 | [
[
"construct",
"update"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 44d56189ec925926d77be2ae1b58f6836667cada | f5d4b4ad82fc49b0f39a6329ef731693225dc4a5 | |||
v1.0 | complete | Data_Structure | Data_Structure_49770_C | def prime_check(n: int) -> bool:
"""Returns True if n is a prime number, False otherwise."""
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 Fals... | def prime_check(n: int) -> bool:
"""Returns True if n is a prime number, False otherwise."""
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 Fals... | from solution import is_prime_digit_sum
def test_prime_digit_sum_for_prime_digit_sum():
assert is_prime_digit_sum(58) == True # 5 + 8 = 13 -> True
assert is_prime_digit_sum(29) == True # 2 + 9 = 11 -> True
assert is_prime_digit_sum(23) == True # 2 + 3 = 5 -> True
def test_non_prime_digit_sum():
ass... | [
{
"docstring": "Returns True if n is a prime number, False otherwise.",
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": "Returns True if the sum of the digits of n is a prime number, False otherwise.",
"function_dec... | [
0,
0,
0,
1,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime_digit_sum(n: int) -> bool:\n def prime_check(x: int) -> bool:\n if x < 2:\n return False\n for i in range(2, int(x **... | trial_gpt4o_8 | {
"original_instruction": "### Prime Digit Sum\n\n**Scenario**: Imagine you're designing a system that filters out certain numbers based on their mathematical properties. One specific feature is to detect numbers whose digit sum is a prime number. This is useful in contexts like cryptography, random number generation... | 0.801746 | Data_Structure_49770 | C | [
"prime_check",
"is_prime_digit_sum"
] | 2 | [
[
"is_prime_digit_sum",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 39918f4e1ac6c00523bc5d91db16662096dab6be | bfe633e8ba64b5a334fcc925d0361e8a8d8d20a7 | |||
v1.0 | complete | Data_Structure | Data_Structure_48739_C | from typing import List
import bisect
def find_LIS_length_dp(sequence: List[int]) -> int:
"""
Returns the length of the longest increasing subsequence using dynamic programming.
Time complexity: O(n^2)
"""
pass
def find_LIS_length_optimized(sequence: List[int]) -> int:
"""
Returns the leng... | from typing import List
import bisect
def find_LIS_length_dp(sequence: List[int]) -> int:
"""
Returns the length of the longest increasing subsequence using dynamic programming.
Time complexity: O(n^2)
"""
if not sequence:
return 0
n = len(sequence)
lis = [1] * n
for i... | import pytest
from solution import find_LIS_length, find_LIS_length_dp, find_LIS_length_optimized
def test_find_LIS_length_empty():
assert find_LIS_length([]) == 0
assert find_LIS_length_dp([]) == 0
assert find_LIS_length_optimized([]) == 0
def test_find_LIS_length_single_element():
assert find_LIS_le... | [
{
"docstring": "Returns the length of the longest increasing subsequence using dynamic programming.\nTime complexity: O(n^2)",
"function_declaration": "def find_LIS_length_dp(sequence):",
"function_name": "find_LIS_length_dp",
"parameter_list": "(sequence)"
},
{
"docstring": "Returns the len... | [
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 bisect\n\ndef find_LIS_length_dp(sequence: List[int]) -> int:\n \"\"\"\n Returns the length of the longest increasing su... | trial_gpt4o_0 | {
"original_instruction": "### Question: Longest Increasing Subsequence with Multiple Implementations\n\nYou are given an unsorted array of integers. Your task is to implement a function that finds the length of the longest increasing subsequence (LIS).\n\nWrite a function `find_LIS_length(sequence: List[int]) -> int... | 0.604252 | Data_Structure_48739 | C | [
"find_LIS_length_dp",
"find_LIS_length_optimized",
"find_LIS_length"
] | 3 | [
[
"find_LIS_length",
"find_LIS_length_optimized"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e4242d37fe9a12acb6c94bd0f719728855d82711 | a7426bbe4e04d6523f0efff8ac765f6113238de2 | |||
v1.0 | complete | Data_Structure | Data_Structure_49431_C | from typing import Tuple
def generate_key(k: int) -> Tuple[int, int, int]:
"""
Generate RSA keys of bit-length k.
- k (int): The number of bits in the modulus n.
- Returns: A tuple (n, e, d) where n is the modulus, e is the public exponent, and d is the private exponent.
>>> n, e, d = generate_key... | import random
from sympy import isprime, mod_inverse, gcd
def generate_prime_candidate(length):
"""Generate an odd integer randomly."""
p = random.getrandbits(length)
# apply a mask to set MSB and LSB to 1
p |= (1 << length - 1) | 1
return p
def generate_prime_number(length=1024):
"""Generate ... | 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)
# Ensure n is 16 bits length roughly (2^15 <= n < 2^16)
assert 2**15 <= n < 2**16
# Ensure e and d are positi... | [
{
"docstring": "Generate an odd integer randomly.",
"function_declaration": "def generate_prime_candidate(length):",
"function_name": "generate_prime_candidate",
"parameter_list": "(length)"
},
{
"docstring": "Generate a prime number of specified bit length.",
"function_declaration": "de... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, randprime, mod_inverse, gcd\n\ndef generate_key(k):\n \"\"\"\n Generate RSA keys.\n :param k: Number of bit... | trial_gpt4o_2 | {
"original_instruction": "You have been hired to enhance the security protocol of a messaging service by implementing a robust encryption system. Your task is to implement functions to generate RSA keys and use them for encrypting and decrypting messages.\n\nRSA (Rivest-Shamir-Adleman) is an asymmetric cryptographic... | 0.780864 | Data_Structure_49431 | C | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 4e9ef5a770c6d2e661ab1ff474b05c7cd2709c0f | 5a72840c2b30629dd9b7e8b3b7e4b81d16d6ecfa | |||
v1.0 | complete | Data_Structure | Data_Structure_49586_C | from typing import List
def invert_matrix(matrix: List[List[float]]) -> List[List[float]]:
""" Inverts an n x n matrix if possible.
Handles matrices of arbitrary size (greater than 1x1) and returns
correct results for matrices that are invertible. Returns specific
error codes for non-invertible or in... | from typing import List
def determinant(matrix: List[List[float]]) -> float:
if len(matrix) == 1:
return matrix[0][0]
if len(matrix) == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for c in range(len(matrix)):
submatrix = [row[:c] + row[c + 1:] for... | from solution import invert_matrix
def test_invert_matrix_valid_2x2():
matrix = [
[4, 7],
[2, 6]
]
expected = [
[0.6, -0.7],
[-0.2, 0.4]
]
result = invert_matrix(matrix)
for a, b in zip(result, expected):
assert all(round(a_i, 1) == round(b_i, 1) for a_i,... | [
{
"docstring": null,
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def get_matrix_minor(matrix, i, j):",
"function_name": "get_matrix_minor",
"parameter_list": "(ma... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef invert_matrix(matrix: List[List[float]]) -> List[List[float]]:\n if not isinstance(matrix, list) or not all(isinstance(row, ... | trial_gpt4o_2 | {
"original_instruction": "You are given a task to implement a function that inverts an n x n matrix if possible. Your function needs to handle matrices of arbitrary size (greater than 1x1) and provide correct results for matrices that are invertible. In case a matrix is non-invertible or invalid, your function shoul... | 0.567892 | Data_Structure_49586 | C | [
"determinant",
"get_matrix_minor",
"invert_matrix"
] | 3 | [
[
"invert_matrix",
"determinant"
],
[
"invert_matrix",
"get_matrix_minor"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a9cf83305e4fd2758a52506d597a65c5546114a0 | 43084200ec54b24ef4e21659e17dbde852e1a3bc | |||
v1.0 | complete | Data_Structure | Data_Structure_49019_C | def get_bit(num, bit):
"""
Returns the bit value (0 or 1) at the specified position.
Parameters:
- num: Integer, the number to get the bit from.
- bit: Integer, the position of the bit to get.
Returns:
int: The bit value (0 or 1).
"""
pass
def set_bit(num, bit):
"""
Sets t... | def get_bit(num, bit):
return (num >> bit) & 1
def set_bit(num, bit):
return num | (1 << bit)
def clear_bit(num, bit):
return num & ~(1 << bit)
def update_bit(num, bit, value):
mask = ~(1 << bit)
return (num & mask) | ((value & 1) << bit)
def compress_data(bin_list):
"""
Compress a list ... | from solution import get_bit, set_bit, clear_bit, update_bit, compress_data, decompress_data
def test_compress_decompress():
binary_list = ["101", "011", "110"]
compressed = compress_data(binary_list)
decompressed = decompress_data(compressed, 3, 3)
assert decompressed == binary_list
def test_single_b... | [
{
"docstring": null,
"function_declaration": "def get_bit(num, bit):",
"function_name": "get_bit",
"parameter_list": "(num, bit)"
},
{
"docstring": null,
"function_declaration": "def set_bit(num, bit):",
"function_name": "set_bit",
"parameter_list": "(num, bit)"
},
{
"doc... | [
0,
0,
0,
1,
0,
0,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_bit(num, i):\n \"\"\"\n Get the bit value at position i.\n \"\"\"\n return (num >> i) & 1\n\ndef set_bit(num, i):\n \"\"\"\n Set the... | trial_gpt4o_3 | {
"original_instruction": "You are working on an embedded system where storage and processing efficiency are critical. You need to implement an efficient compression algorithm that uses bit manipulation to compress and decompress data. Given the functions `get_bit`, `set_bit`, `clear_bit`, and `update_bit`, extend th... | 0.68737 | Data_Structure_49019 | C | [
"get_bit",
"set_bit",
"clear_bit",
"update_bit",
"compress_data",
"decompress_data"
] | 6 | [
[
"compress_data",
"clear_bit"
],
[
"compress_data",
"set_bit"
],
[
"decompress_data",
"get_bit"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 400419564a9cb6dbf6a08a4d0c243d5b8bd6beb1 | 97b66077e76a1b44cc80089c3f57bff886e494b0 | |||
v1.0 | complete | Data_Structure | Data_Structure_49698_C | def compute_gcd(a: int, b: int) -> int:
""" Calculate the greatest common divisor (GCD) of two non-negative integers.
>>> compute_gcd(48, 18) == 6
>>> compute_gcd(0, 10) == 10
>>> compute_gcd(25, 0) == 25
"""
def compute_lcm(a: int, b: int) -> int:
""" Calculate the least common multiple (LCM) ... | def compute_gcd(a, b):
"""
Returns the greatest common divisor (GCD) of a and b using Euclidean algorithm.
"""
while b:
a, b = b, a % b
return a
def compute_lcm(a, b):
"""
Returns the least common multiple (LCM) of a and b.
LCM is computed using the formula: LCM(a, b) = abs(a*b)... | from solution import compute_gcd, compute_lcm, count_trailing_zeros
def test_compute_gcd():
assert compute_gcd(48, 18) == 6
assert compute_gcd(0, 10) == 10
assert compute_gcd(25, 0) == 25
assert compute_gcd(17, 13) == 1 # co-primes
assert compute_gcd(101, 103) == 1 # co-primes
assert compute_... | [
{
"docstring": "Returns the greatest common divisor (GCD) of a and b using Euclidean algorithm.",
"function_declaration": "def compute_gcd(a, b):",
"function_name": "compute_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the least common multiple (LCM) of a and b.\nLCM is comput... | [
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, b):\n \"\"\"\n Returns the greatest common divisor of a and b.\n \"\"\"\n while b:\n a, b = b, a % b\n return a\n\nde... | trial_gpt4o_2 | {
"original_instruction": "#### Problem Description\nYou are given two non-negative integers, `a` and `b`. Your task is to write a function that calculates their greatest common divisor (GCD), least common multiple (LCM), and the number of trailing zeros in each integer.\n\n#### Requirements:\n1. **Function 1: Greate... | 0.747162 | Data_Structure_49698 | C | [
"compute_gcd",
"compute_lcm",
"count_trailing_zeros"
] | 3 | [
[
"compute_lcm",
"compute_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e26b8a3647286ff7afc20d47728c3c3d05d56ad0 | 3b0bf6ee153802b8f1e446435cf308b0a17656d7 | |||
v1.0 | complete | Data_Structure | Data_Structure_49865_C | from typing import List
def highlight_occurrences(text: str, pattern: str) -> List[int]:
"""
Find and return the start indices of all occurrences of a search word within a given text using the KMP algorithm.
>>> highlight_occurrences("hello there hero!", "he") # Output: [0, 7, 12]
>>> highlight_occurr... | from typing import List
def build_lps(pattern: str) -> List[int]:
"""
Builds the longest prefix which is also suffix (lps) array for the KMP algorithm.
"""
length = 0
lps = [0] * len(pattern)
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += ... | from solution import highlight_occurrences
def test_highlight_occurrences_basic():
assert highlight_occurrences("hello there hero!", "he") == [0, 7, 12]
assert highlight_occurrences("aabcaabxaaaz", "aab") == [0, 4]
assert highlight_occurrences("mississippi", "iss") == [1, 4]
def test_highlight_occurrences... | [
{
"docstring": "Builds the longest prefix which is also suffix (lps) array for the KMP algorithm.",
"function_declaration": "def build_lps(pattern):",
"function_name": "build_lps",
"parameter_list": "(pattern)"
},
{
"docstring": "Returns the starting indices of all occurrences of the pattern... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef compute_lps(pattern: str) -> List[int]:\n lps = [0] * len(pattern)\n length = 0\n i = 1\n while i < len(pattern):\n... | trial_gpt4o_2 | {
"original_instruction": "#### Context:\nYou are tasked with developing a feature for a text editor that highlights all occurrences of a given search word in the editor's content. To efficiently find and highlight the search word, you decide to use the Knuth-Morris-Pratt (KMP) algorithm.\n\n#### Problem:\nImplement ... | 0.552051 | Data_Structure_49865 | C | [
"build_lps",
"highlight_occurrences"
] | 2 | [
[
"highlight_occurrences",
"build_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 39e802c067a702db8c13c6a2ae8ecce94a12ed05 | 17b69a55afab95251d0f5c285ed1f8bfe3bffbdf | |||
v1.0 | complete | Data_Structure | Data_Structure_49318_C | import random
def simulate_markov_chain(chain: dict, initial_state: str, steps: int) -> list:
""" Simulate a Markov chain for a specified number of steps.
:param chain: A dictionary representing the Markov chain where the keys are states and values are dictionaries with probable next states and their corr... | import random
def __choose_state(probabilities):
"""
Helper function to choose a state based on given probabilities.
"""
random_value = random.random()
cumulative = 0.0
for state, probability in probabilities.items():
cumulative += probability
if random_value < cumulative:
... | import pytest
from solution import simulate_markov_chain
def test_simulate_markov_chain_single_step():
chain = {
'A': {'A': 0.6, 'B': 0.4},
'B': {'A': 0.3, 'B': 0.7}
}
initial_state = 'A'
steps = 1
path = simulate_markov_chain(chain, initial_state, steps)
assert len(path) =... | [
{
"docstring": "Helper function to choose a state based on given probabilities.",
"function_declaration": "def __choose_state(probabilities):",
"function_name": "__choose_state",
"parameter_list": "(probabilities)"
},
{
"docstring": "Simulate a Markov chain for a specified number of steps.\n... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef simulate_markov_chain(chain: dict, initial_state: str, steps: int) -> list:\n def choose_state(current_state):\n next_states = ... | trial_gpt4o_2 | {
"original_instruction": "You are given an implementation of a Markov Chain that can iterate through states based on given transition probabilities. Your task is to extend this functionality by creating a function that simulates a Markov Chain for a specified number of steps and collects the states visited in a path... | 0.519324 | Data_Structure_49318 | C | [
"__choose_state",
"simulate_markov_chain"
] | 2 | [
[
"simulate_markov_chain",
"__choose_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9ceaf70cbe2de456281f3b6c00603f99ea073d89 | 4a0a2c0a96b17247660432ec681db589eff3d009 | |||
v1.0 | complete | Data_Structure | Data_Structure_49234_C | from typing import List
def maximum_flow(graph: List[List[int]], source: int, sink: int) -> int:
""" Find the maximum possible flow from a source node to a sink node in a directed graph representing a flow network.
Args:
graph (List[List[int]]): a 2D list of integers representing the capacity matrix o... | from collections import deque
def bfs(rGraph, source, sink, parent):
""" Returns true if there is a path from source to sink in residual graph.
Also fills parent[] to store the path """
visited = [False] * len(rGraph)
queue = deque([source])
visited[source] = True
while queue:
u = ... | import pytest
from solution import maximum_flow
def test_example_1():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow(graph, 0, 5) == 23
def test_sin... | [
{
"docstring": "Returns true if there is a path from source to sink in residual graph.\nAlso fills parent[] to store the path ",
"function_declaration": "def bfs(rGraph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(rGraph, source, sink, parent)"
},
{
"docstring": null... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(rGraph, s, t, parent):\n visited = [False] * len(rGraph)\n queue = deque([s])\n visited[s] = True\n \n ... | trial_gpt4o_2 | {
"original_instruction": "### Maximum Flow Implementation\n\n**Context**:\n\nAs part of a network design team, your task is to optimize the data transfer rate from the central server (source) to the client nodes (sinks) across a designed network. Understanding the maximum capacity achievable in given constraints of ... | 0.562796 | Data_Structure_49234 | C | [
"bfs",
"maximum_flow"
] | 2 | [
[
"maximum_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6926f48b247c86ee95b9281d3ee0bc6c38fd177c | a0664ef1fe677a163ab95cbb839ecf76bdc35e4b | |||
v1.0 | complete | Data_Structure | Data_Structure_49598_C | def gen_prime_optimized(k: int, seed: int = None) -> int:
""" Generate a prime number of k bits using a probabilistic prime-testing method (like Miller-Rabin).
>>> prime = gen_prime_optimized(16, seed=123)
>>> isinstance(prime, int)
True
>>> len(bin(prime)) == 18
True
"""
pass
def modin... | import random
import time
def miller_rabin_test(n, k):
""" Perform 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
s //= 2
for _ in range(k):
a = random.r... | from solution import gen_prime_optimized, modinv_optimized, analyze_performance
def test_gen_prime_optimized():
# Testing prime generation with 16 bits
prime = gen_prime_optimized(16, seed=123)
assert isinstance(prime, int), "Prime number generation failed"
assert len(bin(prime)) == 18, "Generated prim... | [
{
"docstring": "Perform the Miller-Rabin primality test. ",
"function_declaration": "def miller_rabin_test(n, k):",
"function_name": "miller_rabin_test",
"parameter_list": "(n, k)"
},
{
"docstring": "Generate a k-bit prime number using a probabilistic method. ",
"function_declaration": "... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport time\n\ndef miller_rabin_test(n, k):\n \"\"\" Perform the Miller-Rabin primality test. \"\"\"\n if n == 2 or n == 3:\n retu... | trial_gpt4o_0 | {
"original_instruction": "### RSA Encryption Algorithm Implementation and Performance Verification\n\nAs part of understanding the RSA encryption algorithm and its efficiency, you need to extend the current RSA implementation to include:\n1. Verification of prime generation speed using probabilistic methods.\n2. An ... | 0.554734 | Data_Structure_49598 | C | [
"miller_rabin_test",
"gen_prime_optimized",
"extended_euclidean_algorithm",
"modinv_optimized",
"rsa_key_generation",
"analyze_performance"
] | 6 | [
[
"analyze_performance",
"rsa_key_generation"
],
[
"gen_prime_optimized",
"miller_rabin_test"
],
[
"modinv_optimized",
"extended_euclidean_algorithm"
],
[
"rsa_key_generation",
"gen_prime_optimized"
],
[
"rsa_key_generation",
"modinv_optimized"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 2e9587bd055ad96b1f689f2cdb7811d8815da683 | 6054767cec2b9b293787e6d0345a7b9ac651dad4 | |||
v1.0 | complete | Data_Structure | Data_Structure_49814_C | from typing import List, Dict, Union
from fractions import Fraction
def simplify_polynomial(monomials: List[Dict[str, Union[Dict[int, int], Union[int, float, Fraction]]]]) -> str:
"""
Takes a polynomial represented as a list of coefficient-variable pairs and returns the simplified version of the polynomial aft... | from fractions import Fraction
def format_monomial(monomial):
"""
Returns a string representation of a single monomial.
"""
parts = []
coeff = monomial["coeff"]
if isinstance(coeff, Fraction):
coeff_str = f'{coeff}'
elif isinstance(coeff, float):
if coeff.is_integer():
... | from solution import simplify_polynomial
from fractions import Fraction
def test_simplify_polynomial_basic():
monomials = [
{"variables": {1: 1}, "coeff": 2},
{"variables": {2: 3, 1: -1}, "coeff": -1},
{"variables": {}, "coeff": 3.14},
{"variables": {}, "coeff": Fraction(-1, 4)}
... | [
{
"docstring": "Returns a string representation of a single monomial.",
"function_declaration": "def format_monomial(monomial):",
"function_name": "format_monomial",
"parameter_list": "(monomial)"
},
{
"docstring": "Simplifies the given polynomial and returns a string representation.",
"... | [
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 fractions import Fraction\n\ndef monomial_to_string(variables, coeff):\n if isinstance(coeff, Fraction):\n coeff_str = f\"{coeff.numerator}/{co... | trial_gpt4o_1 | {
"original_instruction": "### Polynomial Manipulation Challenge\n\nYou are given a Monomial and Polynomial class that can perform various arithmetic operations such as addition, subtraction, multiplication, and division.\n\nYour task is to implement a function `simplify_polynomial` which takes a polynomial represent... | 0.551931 | Data_Structure_49814 | C | [
"format_monomial",
"simplify_polynomial"
] | 2 | [
[
"simplify_polynomial",
"format_monomial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8fb663e1ff069b34dfe69da510775a80abe15523 | 28f59e61ef37c2358fcdbd1cac87328526275d7b | |||
v1.0 | complete | Data_Structure | Data_Structure_49811_C | from typing import List
def max_heap_sort(arr: List[int]) -> List[int]:
""" Sort an array of integers in ascending order using the max heap sort algorithm.
>>> max_heap_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
>>> max_heap_sort([5, 7, 3, 1, 2, 8, 6, 4])
[1, 2, 3, 4,... | from typing import List
def max_heapify(arr: List[int], n: int, i: int):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
... | from solution import max_heap_sort, min_heap_sort
def test_max_heap_sort():
assert max_heap_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
assert max_heap_sort([5, 7, 3, 1, 2, 8, 6, 4]) == [1, 2, 3, 4, 5, 6, 7, 8]
assert max_heap_sort([1]) == [1]
assert max_heap_sort([]) =... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": null,
"function_declaration": "def min_heapify(arr, n, i):",
"function_name": "min_heapify",
"parameter_list": "(arr, n, i... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef max_heapify(arr: List[int], n: int, i: int):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n \n if left <... | trial_gpt4o_0 | {
"original_instruction": "### Objective:\nImplement the heap sort algorithm for an array of integers. Your implementation should allow sorting in both ascending and descending order. Create functions for both max-heap sort and min-heap sort. Your solutions should be efficient with a time complexity of O(n log n) and... | 0.681527 | Data_Structure_49811 | C | [
"max_heapify",
"min_heapify",
"max_heap_sort",
"min_heap_sort"
] | 4 | [
[
"max_heap_sort",
"max_heapify"
],
[
"min_heap_sort",
"min_heapify"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9153e55f56b11aa5536e936fcb0a76ebd3715cea | 6acf14e23babbf76de155607f51a1be23af0afb1 | |||
v1.0 | complete | Data_Structure | Data_Structure_49884_C | def secure_communication(a: int, p: int) -> str:
"""Securely communicate using Diffie-Hellman key exchange.
Args:
a (int): The potential primitive root.
p (int): A large prime number.
Returns:
str: "Success" if the key exchange is successful, otherwise "Failure".
"""
# I... | import random
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def power(x, y, p):
res = 1... | def test_prime_check():
assert is_prime(23) == True
assert is_prime(24) == False
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
def test_primitive_root_finding():
assert find_primitive_root(23) == 5
assert find_primitive_root(29) == 2
assert find_primi... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def power(x, y, p):",
"function_name": "power",
"parameter_list": "(x, y, p)"
},
{
"docstring": null,
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\n\nAlice and Bob want to communicate securely over an insecure network. To achieve this, they decide to use the Diffie-Hellman key exchange algorithm to generate a shared secret key. \n\n### Objective\n\nWrite a function `secure_communication(a: int, p: int) -> str` that:\n\n1.... | 0.506805 | Data_Structure_49884 | C | [
"is_prime",
"power",
"find_primitive_root",
"diffie_hellman_key_exchange",
"secure_communication"
] | 5 | [
[
"diffie_hellman_key_exchange",
"power"
],
[
"find_primitive_root",
"power"
],
[
"secure_communication",
"diffie_hellman_key_exchange"
],
[
"secure_communication",
"find_primitive_root"
],
[
"secure_communication",
"is_prime"
]
] | 5 | [] | false | [] | false | pytest | false | [] | true | ef3ccf9dc2ac40fbdf38fe4dce4a9759d9c39daa | 3679f3356f515d9548f9cf76f428be4a8fd53e3f | |||
v1.0 | complete | Data_Structure | Data_Structure_49843_C | from typing import List
def enhanced_bucket_sort(arr: List[int]) -> List[int]:
""" Implements an enhanced version of bucket sort by dynamically determining bucket size and using quicksort for
sorting within each bucket. Additionally, determines the median of the input array to split the array into two
hal... | from typing import List
def quicksort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(righ... | from solution import enhanced_bucket_sort
def test_example_case():
assert enhanced_bucket_sort([4, 2, 7, 1, 3, 2]) == [1, 2, 2, 3, 4, 7]
def test_all_elements_same():
assert enhanced_bucket_sort([5, 5, 5, 5]) == [5, 5, 5, 5]
def test_already_sorted():
assert enhanced_bucket_sort([1, 2, 3, 4, 5]) == [1, 2... | [
{
"docstring": null,
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def median_of_medians(arr, k):",
"function_name": "median_of_medians",
"parameter_list": "(arr, k)"
},
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef quicksort(arr):\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < p... | trial_gpt4o_2 | {
"original_instruction": "### Question: Implement an Enhanced Bucket Sort with Median Selection\n\n#### Description\nYou have been given the task to implement an enhanced version of bucket sort. This version will improve upon the basic bucket sort by dynamically determining the bucket size and using a quicksort impl... | 0.598872 | Data_Structure_49843 | C | [
"quicksort",
"median_of_medians",
"enhanced_bucket_sort"
] | 3 | [
[
"enhanced_bucket_sort",
"median_of_medians"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8de624791f31d17c6c239b8ffe549e318f5907e6 | 903eeb92029facf2319348c3c11417086484187b | |||
v1.0 | complete | Data_Structure | Data_Structure_49844_C | from typing import List
def find_lcm_multiple(numbers: List[int]) -> int:
"""
Compute the least common multiple (LCM) of a list of integers. This function
internally uses the GCD algorithm implemented with bitwise operations for optimal performance.
Args:
numbers: A list of non-negative inte... | from typing import List
from functools import reduce
def gcd_bit(a: int, b: int) -> int:
if a == 0:
return b
if b == 0:
return a
# Finding common factors of 2
shift = 0
while ((a | b) & 1) == 0:
a >>= 1
b >>= 1
shift += 1
while (a & 1) == 0:
a >>=... | from solution import find_lcm_multiple
def test_find_lcm_multiple_simple():
assert find_lcm_multiple([4, 6]) == 12
def test_find_lcm_multiple_three_numbers():
assert find_lcm_multiple([12, 15, 20]) == 60
def test_find_lcm_multiple_large_numbers():
assert find_lcm_multiple([1000000000, 999999999]) == 9999... | [
{
"docstring": null,
"function_declaration": "def gcd_bit(a, b):",
"function_name": "gcd_bit",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"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 functools import reduce\n\ndef gcd_bit(a: int, b: int) -> int:\n if a == 0:\n return b\n if b == 0:\n return... | trial_gpt4o_0 | {
"original_instruction": "Least Common Multiple Finder\n\n#### Objective\nWrite a Python function `find_lcm_multiple(numbers: List[int]) -> int` that computes the least common multiple (LCM) of a list of integers. This function should internally use the GCD algorithm implemented with bitwise operations for optimal p... | 0.655794 | Data_Structure_49844 | C | [
"gcd_bit",
"lcm",
"find_lcm_multiple"
] | 3 | [
[
"find_lcm_multiple",
"lcm"
],
[
"lcm",
"gcd_bit"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 154b1cbd94f61816141b17277cc06f18cd35f4a9 | cbfa444dd4edfdc6c401b396898fad986347811a | |||
v1.0 | complete | Data_Structure | Data_Structure_49116_C | def dynamic_heap_sort(arr: List[int], use_max_heap: bool, simulation: bool = False) -> List[int]:
"""
Sort an array of integers in ascending order using either Max Heap Sort or Min Heap Sort
based on the given configuration.
Parameters:
arr (List[int]): A list of integers that need to be sorte... | from typing import List
def max_heapify(arr: List[int], n: int, i: int, simulate: bool):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i... | from solution import dynamic_heap_sort
def test_dynamic_heap_sort_max_heap():
arr = [4, 10, 3, 5, 1]
sorted_arr = dynamic_heap_sort(arr, use_max_heap=True)
assert sorted_arr == [1, 3, 4, 5, 10]
def test_dynamic_heap_sort_min_heap():
arr = [4, 10, 3, 5, 1]
sorted_arr = dynamic_heap_sort(arr, use_ma... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, simulate):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, simulate)"
},
{
"docstring": null,
"function_declaration": "def heap_sort_max(arr, simulate):",
"function_name": "heap_sort_max",
"... | [
0,
0,
0,
0,
0,
0,
0,
1,
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 dynamic_heap_sort(arr: List[int], use_max_heap: bool, simulation: bool = False) -> List[int]:\n n = len(arr)\n \n def ... | trial_gpt4o_8 | {
"original_instruction": "You have been provided with an implementation of Heap Sort using both Max Heap and Min Heap. Your task is to implement a function that decides dynamically which heap sort to use based on a given configuration, and then sorts the array in ascending order.\n\n### Function Signature\n\n```pyth... | 0.654835 | Data_Structure_49116 | C | [
"max_heapify",
"heap_sort_max",
"min_heapify",
"heap_sort_min",
"dynamic_heap_sort"
] | 5 | [
[
"dynamic_heap_sort",
"heap_sort_max"
],
[
"dynamic_heap_sort",
"heap_sort_min"
],
[
"heap_sort_max",
"max_heapify"
],
[
"heap_sort_min",
"min_heapify"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 4bdacc3a9aa5dfbabc65adeb8f73b73f86416031 | ee788880d8e30b95b671e2eacc0ce5a8ec81e434 | |||
v1.0 | complete | Data_Structure | Data_Structure_49669_C | def set_cover(
universe: set,
subsets: dict[str, set],
costs: dict[str, int]
) -> (list[str], list[str]):
"""
Finds a subcollection of subsets whose union is universe U,
such that the total cost is minimized. Returns a tuple containing
the result of the optimal set cover and the greedy se... | from itertools import combinations
def optimal_set_cover(universe, subsets, costs):
subset_list = list(subsets.keys())
N = len(subset_list)
optimal_solution = None
optimal_cost = float('inf')
for r in range(1, N + 1):
for combo in combinations(subset_list, r):
union_set = set()... | import pytest
from solution import set_cover
def test_set_cover_example():
universe = {1, 2, 3, 4, 5}
subsets = {'S1': {4, 1, 3}, 'S2': {2, 5}, 'S3': {1, 4, 3, 2}}
costs = {'S1': 5, 'S2': 10, 'S3': 3}
optimal, greedy = set_cover(universe, subsets, costs)
assert sorted(optimal) == sorted([... | [
{
"docstring": null,
"function_declaration": "def optimal_set_cover(universe, subsets, costs):",
"function_name": "optimal_set_cover",
"parameter_list": "(universe, subsets, costs)"
},
{
"docstring": null,
"function_declaration": "def greedy_set_cover(universe, subsets, costs):",
"fu... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import chain, combinations\n\ndef set_cover(universe, subsets, costs):\n def optimal_set_cover(universe, subsets, costs):\n # Generat... | trial_gpt4o_6 | {
"original_instruction": "## Problem Description\n\nYou are given a universe of elements \\( U \\) and a collection of subsets that together cover all elements of \\( U \\). Each subset has an associated cost. Your task is to write a function that finds a subcollection of subsets whose union is \\( U \\), such that ... | 0.561812 | Data_Structure_49669 | C | [
"optimal_set_cover",
"greedy_set_cover",
"set_cover"
] | 3 | [
[
"set_cover",
"greedy_set_cover"
],
[
"set_cover",
"optimal_set_cover"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 035373915c4a4a5b2232908167d0a1aa2970d32e | f0e90382d6063b85a5a994269172aae3f634eedb | |||
v1.0 | complete | Data_Structure | Data_Structure_49897_C | from typing import List, Tuple
def find_k_closest_points(points: List[Tuple[int, int]], k: int, origin: Tuple[int, int] = (0, 0)) -> List[Tuple[int, int]]:
""" Find the k closest points to the origin in a list of points.
Args:
points (List[Tuple[int, int]]): A list of tuples where each tuple represent... | import heapq
from typing import List, Tuple
def squared_euclidean_distance(point: Tuple[int, int], origin: Tuple[int, int]) -> int:
"""
Return the squared Euclidean distance between point and origin.
Squared distance is used to avoid the computational cost of the square root.
"""
return (point[0] -... | from solution import find_k_closest_points
def test_find_k_closest_points_basic():
points = [(1, 3), (-2, 2), (5, 8), (0, 1)]
k = 2
origin = (0, 0)
result = find_k_closest_points(points, k, origin)
expected = [(0, 1), (-2, 2)]
assert set(result) == set(expected)
def test_find_k_closest_points_... | [
{
"docstring": "Return the squared Euclidean distance between point and origin.\nSquared distance is used to avoid the computational cost of the square root.",
"function_declaration": "def squared_euclidean_distance(point, origin):",
"function_name": "squared_euclidean_distance",
"parameter_list": "... | [
0,
0,
0,
1,
1,
1,
0,
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": "import heapq\nfrom typing import List, Tuple\nimport math\n\ndef find_k_closest_points(points: List[Tuple[int, int]], k: int, origin: Tuple[int, int] = (0, 0)... | trial_gpt4o_7 | {
"original_instruction": "### Closest Points to Origin \n\n#### Scenario\nYou are working on a GPS-based application that frequently needs to find the k closest POIs (Points of Interest) to the user's current location, referred to as the origin. Given this requirement, your task is to write a function that efficient... | 0.66887 | Data_Structure_49897 | C | [
"squared_euclidean_distance",
"find_k_closest_points"
] | 2 | [
[
"find_k_closest_points",
"squared_euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 281b692697e773f13ec8530742b0bcf7af295e55 | 93585664d660483c74c85e1156b5bc82e54672e9 | |||
v1.0 | complete | Data_Structure | Data_Structure_8546_C | import random
from typing import Tuple
def generate_rsa_keypair(k, seed=None) -> Tuple[int, int, int]:
""" Generate an RSA key pair more efficiently.
Args:
k (int): The number of bits for the modulus `n`.
seed (optional, int): An optional integer seed to initialize the random number generator for ... | import random
from typing import Tuple
def is_prime(n, k=5):
"""Miller-Rabin primality test."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
r, d = 0, n - 1
while d % 2 == 0:
r += 1
d //= 2
def check_composite(a):
... | from solution import generate_rsa_keypair
def test_generate_rsa_keypair():
n, e, d = generate_rsa_keypair(16, seed=42)
assert n > 0
assert e == 65537
assert d > 0
plaintext = 42
encrypted = pow(plaintext, e, n)
decrypted = pow(encrypted, d, n)
assert decrypted == plaintext
def test_gen... | [
{
"docstring": "Miller-Rabin primality test.",
"function_declaration": "def is_prime(n, k=5):",
"function_name": "is_prime",
"parameter_list": "(n, k=5)"
},
{
"docstring": "Generate an odd integer randomly.",
"function_declaration": "def generate_prime_candidate(length):",
"function_... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import Tuple\n\ndef miller_rabin(n, k=40):\n if n in (2, 3):\n return True\n if n % 2 == 0 or n == 1:\n return ... | trial_gpt4o_1 | {
"original_instruction": "### Question\n\nGiven the following RSA key generation specification, implement a more efficient RSA key generator.\n\n#### Problem Statement\n\nYou are required to implement a function `generate_rsa_keypair(k, seed=None)` that generates an RSA key pair more efficiently. You will use the Mi... | 0.715543 | Data_Structure_8546 | C | [
"is_prime",
"generate_prime_candidate",
"generate_prime_number",
"extended_gcd",
"mod_inverse",
"generate_rsa_keypair"
] | 6 | [
[
"generate_prime_number",
"generate_prime_candidate"
],
[
"generate_prime_number",
"is_prime"
],
[
"generate_rsa_keypair",
"generate_prime_number"
],
[
"generate_rsa_keypair",
"mod_inverse"
],
[
"mod_inverse",
"extended_gcd"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 976bd87189a7042c9b1f25f4a9905e08b3f3df17 | ec7fc14ccad46b58a4365ae02b58122f300f3a62 | |||
v1.0 | complete | Data_Structure | Data_Structure_27379_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def bin_tree_to_list(root: TreeNode) -> TreeNode:
""" Convert a given Binary Tree into a doubly linked list. The doubly linked list should be sorted if the tree is a Bina... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def bin_tree_to_list(root: TreeNode) -> TreeNode:
if not root:
return None
# Initialize the previous node as None
bin_tree_to_list_util.prev = None
... | import pytest
from solution import TreeNode, bin_tree_to_list, print_list
def test_empty_tree():
assert bin_tree_to_list(None) == None
def test_single_node_tree():
root = TreeNode(1)
head = bin_tree_to_list(root)
assert head.val == 1
assert head.left == None
assert head.right == None
def test... | [] | [
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 bi... | trial_gpt4o_1 | {
"original_instruction": "You are tasked with converting a given Binary Tree into a doubly linked list. The doubly linked list should be sorted if the tree is a Binary Search Tree. Each node in the doubly linked list should have two pointers (`left` for the previous node and `right` for the next node), and it should... | 0.53654 | Data_Structure_27379 | C | [
"bin_tree_to_list",
"bin_tree_to_list_util",
"print_list"
] | 3 | [
[
"bin_tree_to_list",
"bin_tree_to_list_util"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | da4a70245e07f6e1150ec7afc9dc95b0ee154be7 | 46475912b8572d54bb93d77e6d803c649f4a9cb1 | |||
v1.0 | complete | Data_Structure | Data_Structure_27375_C | import random
from typing import Tuple
def generate_key(k: int, seed: int = None) -> Tuple[int, int, int]:
"""
Generate RSA public and private keys.
Parameters:
-----------
k: int
The number of bits in the modulus n.
seed: int
Optional random seed for reproducibility.
Retu... | import random
from sympy import isprime
from sympy import mod_inverse
def generate_prime_candidate(bits):
"""Generate an odd integer randomly"""
p = random.getrandbits(bits)
# apply a mask to set MSB and LSB to 1
p |= (1 << bits - 1) | 1
return p
def generate_prime_number(bits):
"""Generate a ... | from solution import generate_key
def test_generate_key_returns_three_integers():
n, e, d = generate_key(32, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_encryption_decryption():
k = 32
seed = 42
n, e, d = generate_key(k, seed)
origin... | [
{
"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... | [
0,
0,
0,
0,
0,
0,
1,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\nfrom math import gcd\n\ndef generate_large_prime(bits, seed=None):\n if seed is not None:\n r... | trial_gpt4o_8 | {
"original_instruction": "Implementing RSA Key Generation\n\n#### Context:\nYou are tasked with building a secure communication system and decide to use the RSA algorithm for encrypting messages. The core part of this implementation involves generating the RSA keys correctly. Your job is to refine and complete the R... | 0.686327 | Data_Structure_27375 | C | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key"
] | 3 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | edd3f1f81406564beabbcbd673de3609012b5e91 | 28ed0fe5396590adb6814f75ac92b7ba8a418655 | |||
v1.0 | complete | Data_Structure | Data_Structure_33273_C | def maximum_flow_bfs(adjacency_matrix: List[List[int]]) -> int:
""" Compute the maximum number of vehicles that can be transported from the first intersection (source)
to the last intersection (sink) using the adjacency matrix representation of the graph.
>>> graph = [[0, 16, 13, 0, 0, 0],
... | from typing import List
from collections import deque
def bfs(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:
# Mark all vertices as not visited
visited = [False] * len(residual_graph)
# Create a queue for BFS
queue = deque()
# Mark the source node as ... | from solution import maximum_flow_bfs
def test_basic_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow_bfs(graph) == 23
def test_no_flow_case(... | [
{
"docstring": null,
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(adjacency_matrix):",
"function_name"... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n \"... | trial_gpt4o_2 | {
"original_instruction": "### Maximum Flow in Transport Network\n\nYou are responsible for managing traffic flow in a city's transport network represented as a directed graph in the form of an adjacency matrix. The nodes represent intersections, and the edges represent streets with capacities indicating the maximum ... | 0.561468 | Data_Structure_33273 | C | [
"bfs",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0915ec51df7e0b14f2793da732906b436f5b4d10 | 6619874106610f1ff4bd6c02df844f8a9bf7afd7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.