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_43915_C | import collections
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_subtree(big: TreeNode, small: TreeNode) -> bool:
""" Given two binary trees `s` and `t`, determine if `t` is a subtree of `s`.
>>> class TreeNode:
... def __ini... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def comp(p: TreeNode, q: TreeNode) -> bool:
if p is None and q is None:
return True
if p is not None and q is not None:
return p.val == q.val and comp(p.left, q.left) and comp(p.ri... | def test_is_subtree():
# Helper function to create a TreeNode from list
def create_tree(values):
if not values:
return None
nodes = [TreeNode(val) if val is not None else None for val in values]
for i in range(len(nodes)):
if nodes[i] is not None:
... | [] | [
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\n\ndef is_subtree(big: TreeNode, smal... | trial_gpt4o_2 | {
"original_instruction": "Given two binary trees `s` and `t`, determine if `t` is a subtree of `s`. A subtree of `s` is a tree consisting of a node in `s` and all of that node's descendants. \n\n### Function Signature\n```python\ndef is_subtree(big: TreeNode, small: TreeNode) -> bool:\n```\n\n### Input\n- `big` (Tre... | 0.604954 | Data_Structure_43915 | C | [
"comp",
"is_subtree"
] | 2 | [
[
"is_subtree",
"comp"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | false | [] | true | 2c85c91f2ac12adc929296306d01937d787ed460 | 72a3f6a2a456b73f17202305297e2fbc252f9487 | |||
v1.0 | complete | Data_Structure | Data_Structure_43649_C | def matrix_power(matrix: list, power: int) -> list:
""" Compute the matrix exponentiation of a given square matrix to a specified power.
>>> matrix = [
... [1, 2],
... [3, 4]
... ]
>>> matrix_power(matrix, 2)
[[7, 10], [15, 22]]
>>> matrix = [
... [1, 0],
... [0,... | def identity_matrix(n):
"""Generate an identity matrix of size n x n."""
return [[1 if i == j else 0 for j in range(n)] for i in range(n)]
def matrix_multiply(A, B):
"""Multiplies two square matrices A and B."""
n = len(A)
result = [[0] * n for _ in range(n)]
for i in range(n):
for... | from solution import matrix_power
def test_identity_matrix_power():
matrix = [
[1, 0],
[0, 1]
]
power = 5
expected = [
[1, 0],
[0, 1]
]
assert matrix_power(matrix, power) == expected
def test_zero_power():
matrix = [
[3, 4],
[5, 6]
]
... | [
{
"docstring": "Generate an identity matrix of size n x n.",
"function_declaration": "def identity_matrix(n):",
"function_name": "identity_matrix",
"parameter_list": "(n)"
},
{
"docstring": "Multiplies two square matrices A and B.",
"function_declaration": "def matrix_multiply(A, B):",
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B.\n \"\"\"\n n = len(A)\n C = [[0] * n for _ in range(n)]\n for i in ra... | trial_gpt4o_2 | {
"original_instruction": "### Matrix Exponentiation Problem\n\nYou are tasked with implementing a function to compute the matrix exponentiation of a given square matrix to a specified power.\n\n#### Function Signature\n```python\ndef matrix_power(matrix: list, power: int) -> list:\n```\n\n#### Input\n* `matrix` (lis... | 0.544615 | Data_Structure_43649 | C | [
"identity_matrix",
"matrix_multiply",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity_matrix"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 02b64f2acf4402c09bf223a5ab1e3c8fcdbe784f | 944fbfd17c67be489c8ca2882553de069cb3a938 | |||
v1.0 | complete | Data_Structure | Data_Structure_44425_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_tree: TreeNode, small_tree: TreeNode) -> bool:
""" Determines if small_tree is a subtree of big_tree.
Args:
big_tree (TreeNode): The root ... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big_tree: TreeNode, small_tree: TreeNode) -> bool:
if not small_tree:
return True
if not big_tree:
return False
if is_same_tre... | from solution import TreeNode, is_subtree
def test_is_subtree_example1():
# Example 1
big_tree = TreeNode(3, TreeNode(4, TreeNode(1), TreeNode(2)), TreeNode(5))
small_tree = TreeNode(4, TreeNode(1), TreeNode(2))
assert is_subtree(big_tree, small_tree) == True
def test_is_subtree_example2():
# Exam... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_0 | {
"original_instruction": "### Subtree Check in Binary Trees\n\nGiven two binary trees, `big_tree` and `small_tree`, determine if `small_tree` is a subtree of `big_tree`. A subtree of `big_tree` is defined as any node in `big_tree` and all of its descendants in `big_tree` that match exactly with `small_tree`.\n\n####... | 0.56239 | Data_Structure_44425 | C | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 52ebb984805b9f98f880202b9e1958f0234e2616 | 2f4478bfa67cc26da31bef635a06222d14a18aea | |||
v1.0 | complete | Data_Structure | Data_Structure_43957_C | def matrix_power(mat: list, n: int) -> list:
""" Compute the power of a square matrix using matrix exponentiation.
Args:
mat (list): A list of lists where each sublist is of length `d` and itself is `d` such that it represents a `d x d` matrix. The elements of the matrix are integers.
n (int): A no... | def matrix_multiply(mat1, mat2):
"""
Multiplies two matrices mat1 and mat2.
"""
d = len(mat1)
result = [[0] * d for _ in range(d)]
for i in range(d):
for j in range(d):
for k in range(d):
result[i][j] += mat1[i][k] * mat2[k][j]
return result
def matrix_id... | from solution import matrix_power
def test_matrix_power_zero_exp():
mat = [
[2, 0],
[0, 2]
]
result = matrix_power(mat, 0)
expected = [
[1, 0],
[0, 1]
]
assert result == expected
def test_matrix_power_identity_matrix():
mat = [
[2, 0],
[0, 2]... | [
{
"docstring": "Multiplies two matrices mat1 and mat2.",
"function_declaration": "def matrix_multiply(mat1, mat2):",
"function_name": "matrix_multiply",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": "Returns the identity matrix of dimension d x d.",
"function_declaration": "def matr... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_power(mat, n):\n \"\"\"\n Computes the power n of a square matrix mat.\n \"\"\"\n\n def identity_matrix(size):\n \"\"\"Creates a... | trial_gpt4o_2 | {
"original_instruction": "### Matrix Power Calculation\n\n**Context**:\nYou are developing a library of linear algebra utilities for scientific computing. One of the necessary functions is efficient computation of the power of a square matrix. Your task is to implement a function that computes the power of a matrix ... | 0.549567 | Data_Structure_43957 | C | [
"matrix_multiply",
"matrix_identity",
"matrix_power"
] | 3 | [
[
"matrix_power",
"matrix_identity"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 07f28bdb8e7f0ae20864d30c4b67bb7df9718b43 | 523bb04b667418c7e78b23c6a2fc9dfe3e56974b | |||
v1.0 | complete | Data_Structure | Data_Structure_44546_C | from typing import List
def generate_strobogrammatic_numbers(n: int) -> List[str]:
""" Generate all strobogrammatic numbers of length n.
>>> sorted(generate_strobogrammatic_numbers(2))
['11', '69', '88', '96']
>>> sorted(generate_strobogrammatic_numbers(1))
['0', '1', '8']
"""
pass
def cou... | from typing import List
def generate_strobogrammatic_numbers(n: int) -> List[str]:
def helper(m, n):
if m == 0: return [""]
if m == 1: return ["0", "1", "8"]
prev = helper(m - 2, n)
result = []
for num in prev:
if m != n: # Prevent numbers sta... | from solution import generate_strobogrammatic_numbers, count_strobogrammatic_in_range
def test_generate_strobogrammatic_numbers_length_0():
assert generate_strobogrammatic_numbers(0) == [""]
def test_generate_strobogrammatic_numbers_length_1():
assert sorted(generate_strobogrammatic_numbers(1)) == sorted(["0"... | [
{
"docstring": null,
"function_declaration": "def generate_strobogrammatic_numbers(n):",
"function_name": "generate_strobogrammatic_numbers",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def count_strobogrammatic_in_range(low, high):",
"function_name": "co... | [
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 generate_strobogrammatic_numbers(n):\n \"\"\"\n Returns all strobogrammatic numbers of length n.\n \"\"\"\n if n == 0: \n return [\"\"]... | trial_gpt4o_9 | {
"original_instruction": "### Strobogrammatic Number Generation\n\nGiven an integer n, write a function `generate_strobogrammatic_numbers(n)` that generates all strobogrammatic numbers of length n.\n\nAdditionally, write a function `count_strobogrammatic_in_range(low, high)` that returns the count of strobogrammatic... | 0.577016 | Data_Structure_44546 | C | [
"generate_strobogrammatic_numbers",
"count_strobogrammatic_in_range"
] | 2 | [
[
"count_strobogrammatic_in_range",
"generate_strobogrammatic_numbers"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c308f2f302846878c4b248839fc037146333cc35 | d170b5d5242700731095d307771df69d36fe7a8d | |||
v1.0 | complete | Data_Structure | Data_Structure_44192_C | def extended_gcd(num1: int, num2: int) -> (int, int, int):
""" Returns the Bézout's coefficients and GCD of num1 and num2.
>>> s, t, g = extended_gcd(56, 15)
# Should output: (s, t, g) such that 56*s + 15*t = g
"""
def solve_for_linear_combination(num1: int, num2: int, target: int) -> (int, int):
"... | def extended_gcd(num1, num2):
"""
Returns the Bézout's coefficients and GCD of num1 and num2.
"""
if num1 == 0:
return (0, 1, num2)
else:
s, t, g = extended_gcd(num2 % num1, num1)
return (t - (num2 // num1) * s, s, g)
def solve_for_linear_combination(num1, num2, target):
... | from solution import extended_gcd, solve_for_linear_combination
def test_extended_gcd():
s, t, g = extended_gcd(56, 15)
assert g == 1
assert 56 * s + 15 * t == g
s, t, g = extended_gcd(101, 10)
assert g == 1
assert 101 * s + 10 * t == g
s, t, g = extended_gcd(48, 18)
assert g == 6
... | [
{
"docstring": "Returns the Bézout's coefficients and GCD of num1 and num2.",
"function_declaration": "def extended_gcd(num1, num2):",
"function_name": "extended_gcd",
"parameter_list": "(num1, num2)"
},
{
"docstring": "Solves for the coefficients s' and t' such that:\nnum1 * s' + num2 * t' ... | [
0,
0,
0,
1,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def extended_gcd(num1: int, num2: int) -> (int, int, int):\n \"\"\"\n Computes the extended GCD of num1 and num2.\n Returns a tuple (s, t, g) where s... | trial_gpt4o_7 | {
"original_instruction": "**Extended GCD Function Implementation and Application**\n\n**Context**: \nIn cryptography, particularly in RSA algorithm, it is often required to compute Bézout's coefficients as part of the key generation and decryption processes. Bézout's coefficients are the integers \\( s \\) and \\( t... | 0.626955 | Data_Structure_44192 | C | [
"extended_gcd",
"solve_for_linear_combination"
] | 2 | [
[
"solve_for_linear_combination",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 07fb60d256abccbba17618d3e1b6b7b57b27ad2f | 1598fe44e81a7356016932ce7c66844dfab8afbb | |||
v1.0 | complete | Data_Structure | Data_Structure_43979_C | from typing import List, Tuple
def can_install_all_particles(modules: List[str], dependencies: List[Tuple[str, str]]) -> List[str]:
"""Analyzes a list of Roman numeral dependencies and provides an installation order.
Args:
modules (List[str]): List of strings where each string is a Roman numeral repre... | from typing import List, Tuple
def roman_to_int(s: str) -> int:
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
prev_value = 0
for char in reversed(s):
value = roman[char]
if value < prev_value:
result -= value
else:
r... | from solution import can_install_all_particles
def test_simple_case():
modules = ["I", "II", "III", "IV"]
dependencies = [("II", "I"), ("III", "II"), ("IV", "III")]
assert can_install_all_particles(modules, dependencies) == ["I", "II", "III", "IV"]
def test_cycle_case():
modules = ["I", "II", "III", "... | [
{
"docstring": null,
"function_declaration": "def roman_to_int(s):",
"function_name": "roman_to_int",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def can_install_all_particles(modules, dependencies):",
"function_name": "can_install_all_particles",
"pa... | [
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 roman_to_int(s):\n \"\"\"\n Converts a Roman numeral to an integer.\n \"\"\"\n roman_numerals = {\n 'I': 1, 'V': 5, 'X': 10, 'L': 50,\n... | trial_gpt4o_1 | {
"original_instruction": "### Roman Numeral Dependency Checker\n\nYou are tasked with creating a utility that analyzes a list of Roman numeral dependencies in a project. Each projection module is represented by a Roman numeral and has dependencies on other modules (also represented by Roman numerals). A projection m... | 0.535923 | Data_Structure_43979 | C | [
"roman_to_int",
"can_install_all_particles"
] | 2 | [
[
"can_install_all_particles",
"roman_to_int"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 12a5bc1a6a26fb31635fc750048fe95d24a88002 | aa4e3b41bfdc714b08184324ffb2270d50365f9a | |||
v1.0 | complete | Data_Structure | Data_Structure_43958_C | from typing import List, Tuple
def bogo_sort(arr: List[int]) -> Tuple[List[int], int, float]:
"""
Sorts an input list using Bogo Sort and returns a tuple consisting of the sorted list,
the number of permutations tried, and the time taken in seconds.
:param arr: List[int] - List of integers to sort.
... | import random
import time
from typing import List, Tuple
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if a list is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr: List[int]) -> Tuple[List[int],... | from solution import bogo_sort
def test_bogo_sort_empty_list():
sorted_list, permutations, time_taken = bogo_sort([])
assert sorted_list == []
assert permutations == 0
assert time_taken >= 0
def test_bogo_sort_single_element():
sorted_list, permutations, time_taken = bogo_sort([1])
assert sort... | [
{
"docstring": "Helper function to check if a list is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts an input list using Bogo Sort and returns a tuple consisting of the sorted list, \nthe number of per... | [
0,
0,
0,
0,
1,
1,
1,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport time\nfrom typing import List, Tuple\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to check if the list is ... | trial_gpt4o_9 | {
"original_instruction": "### Bogo Sort Challenge\n\nBogo Sort, also known as permutation sort or stupid sort, is a highly inefficient sorting algorithm based on generating random permutations of its input until it finds one that is sorted. Although it is not used in practice, understanding the algorithm can highlig... | 0.608198 | Data_Structure_43958 | C | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 881d45246e4754150d7c9f4f04ea367374aaa861 | f0e4dd8c123471df6690e26b269151c23103e2a1 | |||
v1.0 | complete | Data_Structure | Data_Structure_44341_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 in ascending order. If simulation is True, print the state of the array at each iteration.
>>> radix_sort([170, 45, 75, 90, 802, 2... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool) -> None:
n = len(arr)
output = [0] * n
count = [0] * 10
# Store count of occurrences in count[]
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
# Change count[i] so that... | from solution import radix_sort
def test_small_list():
assert radix_sort([3, 2, 1]) == [1, 2, 3]
assert radix_sort([5, 3, 8, 6]) == [3, 5, 6, 8]
def test_single_element_list():
assert radix_sort([1]) == [1]
def test_empty_list():
assert radix_sort([]) == []
def test_large_numbers():
asse... | [
{
"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,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool) -> None:\n n = len(arr)\n output = [0] * n\n count = [0] * 1... | trial_gpt4o_0 | {
"original_instruction": "### Radix Sort Implementation\n\n**Objective**: Implement a function for the Radix Sort algorithm that sorts an array of non-negative integers in ascending order. This function should allow an optional simulation mode that outputs each iteration's result.\n\n**Function Signature**:\n```pyth... | 0.624816 | Data_Structure_44341 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 15b65468aae8ac476d99173e31f7be040c757882 | 301b626415e13af782fbb294b8d8bdae1fff18ab | |||
v1.0 | complete | Data_Structure | Data_Structure_43917_C | from typing import List
import random
def is_sorted(arr: List[int]) -> bool:
"""
Returns True if the given array is sorted in ascending order, False otherwise.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def safe_bogo_sort(arr: List[int], ... | from typing import List
import random
def is_sorted(arr: List[int]) -> bool:
"""
Returns True if the given array is sorted in ascending order, False otherwise.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def safe_bogo_sort(arr: List[int], ... | from solution import safe_bogo_sort
def test_sorted_array():
assert safe_bogo_sort([1, 2, 3], 1) == [1, 2, 3]
def test_sort_small_array():
result = safe_bogo_sort([3, 2, 1], 100)
assert result == [1, 2, 3]
def test_large_iterations_needed():
result = safe_bogo_sort([5, 4, 3, 2, 1], 1000)
assert r... | [
{
"docstring": "Returns True if the given array is sorted in ascending order, False otherwise.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Function to sort an array using Bogo Sort with enforced iteration limit.\... | [
0,
0,
0,
1,
0,
0,
1,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Checks if an array is sorted in non-decreasing order.\n \... | trial_gpt4o_8 | {
"original_instruction": "#### Context:\nYou have been presented with an intentionally inefficient sorting algorithm, Bogo Sort. Despite its impractical nature, it can be useful for understanding fundamental concepts about algorithm analysis and probabilistic methods. The following question tests your understanding ... | 0.588244 | Data_Structure_43917 | C | [
"is_sorted",
"safe_bogo_sort"
] | 2 | [
[
"safe_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e0d71443dd1b8eaa37ddafbd5a1686ea7a1bbd36 | 9f508ce7440e9c5e8348e31afe54bd0227d26c1d | |||
v1.0 | complete | Data_Structure | Data_Structure_44535_C | from typing import Tuple, Dict
def euclidean_distance(point1: Tuple[float, ...], point2: Tuple[float, ...]) -> float:
"""
Calculate the Euclidean distance between two points.
"""
return sum((a - b) ** 2 for a, b in zip(point1, point2)) ** 0.5
def k_nearest_neighbors(x: Tuple[float, ...], tSet: Dict[Tu... | import math
from collections import Counter
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(point1, point2)))
def k_nearest_neighbors(x, tSet, k):
"""
Classify the input vector `x` by conside... | from solution import k_nearest_neighbors
def test_k_nearest_neighbors_basic():
training_set = {
(2.0, 3.0): 'A',
(1.0, 1.0): 'B',
(1.5, 2.5): 'B',
(4.0, 4.0): 'A',
(3.0, 3.5): 'A'
}
x = (1.0, 2.0)
k = 2
assert k_nearest_neighbors(x, training_set, k) == 'B'
d... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import Counter\nimport math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points.\... | trial_gpt4o_2 | {
"original_instruction": "You have been provided with the implementation of the nearest neighbor algorithm, which classifies a given input vector based on the closest training data point. The Euclidean distance measure is used to determine the closeness of the input vector to each training point.\n\n**Your task is t... | 0.683201 | Data_Structure_44535 | C | [
"euclidean_distance",
"k_nearest_neighbors"
] | 2 | [
[
"k_nearest_neighbors",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6324f26a322125bccaeb8248197aaad4de0a288b | f3954b11079b153d2dae5c25a55634e0bd6133c0 | |||
v1.0 | complete | Data_Structure | Data_Structure_43647_C | def optimized_gcd(a, b):
"""
Computes the GCD of two integers a and b using bitwise operations.
Includes error handling for non-integer and invalid inputs.
Args:
a (int): The first integer.
b (int): The second integer.
Returns:
int: The greatest common divisor of `... | def optimized_gcd(a, b):
"""
Computes the GCD of two integers a and b using bitwise operations.
Includes error handling for non-integer and invalid inputs.
"""
if not isinstance(a, int) or not isinstance(b, int):
raise ValueError("Input values must be integers.")
if a == 0 and b == 0:
... | from solution import optimized_gcd, optimized_lcm
def test_optimized_gcd_positive_numbers():
assert optimized_gcd(8, 12) == 4
assert optimized_gcd(54, 24) == 6
def test_optimized_gcd_negative_numbers():
assert optimized_gcd(-8, 12) == 4
assert optimized_gcd(8, -12) == 4
assert optimized_gcd(-54, -... | [
{
"docstring": "Computes the GCD of two integers a and b using bitwise operations.\nIncludes error handling for non-integer and invalid inputs.",
"function_declaration": "def optimized_gcd(a, b):",
"function_name": "optimized_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the L... | [
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 optimized_gcd(a, b):\n \"\"\"\n Computes the GCD of two integers using bitwise operations and handles errors.\n \"\"\"\n # Validate inputs\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Optimize GCD and LCM Calculation with Additional Error Handling\n\nYou are given a task to implement optimized and robust functions that compute the Greatest Common Divisor (GCD) and the Least Common Multiple (LCM) of two integers. You are also supposed to handle all potential... | 0.738405 | Data_Structure_43647 | C | [
"optimized_gcd",
"optimized_lcm"
] | 2 | [
[
"optimized_lcm",
"optimized_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9f2794976dd5e384a9a54b0718c89c96bc665dc7 | ec0ab8e945309c7bb920119b734d2e2bd233bca0 | |||
v1.0 | complete | Data_Structure | Data_Structure_43867_C | def get_field(header: int, i: int) -> int:
""" Extract the bit at the `i`-th position of `header`.
>>> get_field(0b10101010, 3)
1
>>> get_field(0b10101010, 2)
0
>>> get_field(0b11111111, 7)
1
>>> get_field(0b00000000, 0)
0
"""
pass
def set_field(header: int, i: int) -> int:
... | def get_field(header, i):
"""
Extract the bit at the `i`-th position of `header`.
"""
return (header >> i) & 1
def set_field(header, i):
"""
Set the bit at the `i`-th position of `header` to 1.
"""
return header | (1 << i)
def clear_field(header, i):
"""
Clear the bit at the `i... | def test_get_field():
assert get_field(0b10101010, 3) == 1
assert get_field(0b10101010, 2) == 0
assert get_field(0b11111111, 7) == 1
assert get_field(0b00000000, 0) == 0
def test_set_field():
assert set_field(0b10101010, 5) == 0b10101010
assert set_field(0b10101010, 6) == 0b11101010
assert ... | [
{
"docstring": "Extract the bit at the `i`-th position of `header`.",
"function_declaration": "def get_field(header, i):",
"function_name": "get_field",
"parameter_list": "(header, i)"
},
{
"docstring": "Set the bit at the `i`-th position of `header` to 1.",
"function_declaration": "def ... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_field(header, i):\n \"\"\"\n Returns the bit at the i-th position of the header.\n \"\"\"\n return (header >> i) & 1\n\ndef set_field(head... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nIn a low-level network protocol, each packet consists of a 32-bit header where different fields are represented by specific bits. You need to write functions to manipulate these fields accurately within the header. The header fields include information such as flags and numeri... | 0.612286 | Data_Structure_43867 | C | [
"get_field",
"set_field",
"clear_field",
"update_field"
] | 4 | [
[
"update_field",
"clear_field"
],
[
"update_field",
"set_field"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | bef1448a163652239a28ef1bbda31707b2ced5bf | f5c3496e9fc3fcbc27f0585747bc7c98f538fa2f | |||
v1.0 | complete | Data_Structure | Data_Structure_44798_C | from typing import List, Union
def invertible_matrix_check(matrix: List[List[float]]) -> Union[List[List[float]], str]:
""" Check if a given matrix is invertible and return its inverse if it is.
If the matrix is not invertible, returns a descriptive string indicating the specific issue.
Error Con... | from typing import List, Union
def determinant(matrix: List[List[float]]) -> float:
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]
det = 0
for c in range(n):
det += ((-1)**c) * matrix[0][c] * deter... | from solution import invertible_matrix_check
def test_valid_invertible_matrix():
matrix = [
[4, 7],
[2, 6]
]
expected = [
[0.6, -0.7],
[-0.2, 0.4]
]
assert invertible_matrix_check(matrix) == expected
def test_singular_matrix():
matrix = [
[1, 2],
... | [
{
"docstring": null,
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def minor(matrix, i, j):",
"function_name": "minor",
"parameter_list": "(matrix, i, j)"
},
{
... | [
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, Union\n\ndef determinant(matrix: List[List[float]]) -> float:\n n = len(matrix)\n if n == 1:\n return matrix[0][0]\n ... | trial_gpt4o_1 | {
"original_instruction": "#### Context:\nYou have been provided with the implementation for matrix inversion. Your task is to extend this functionality to handle different scenarios and ensure robustness. This function is critical for applications like solving linear equations, computer graphics, and systems modelin... | 0.478234 | Data_Structure_44798 | C | [
"determinant",
"minor",
"transpose",
"inverse",
"invertible_matrix_check"
] | 5 | [
[
"determinant",
"minor"
],
[
"inverse",
"determinant"
],
[
"inverse",
"minor"
],
[
"inverse",
"transpose"
],
[
"invertible_matrix_check",
"inverse"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 57a177cdc2dbe0a49046dca94f5f248555e3dbac | cf1a05bc82916a435264a07cff461ef81785c879 | |||
v1.0 | complete | Data_Structure | Data_Structure_45057_C | def fibonacci_matrix(n: int) -> int:
"""Computes the nth Fibonacci number using matrix exponentiation.
>>> fibonacci_matrix(0) == 0
>>> fibonacci_matrix(1) == 1
>>> fibonacci_matrix(10) == 55
>>> fibonacci_matrix(100) == 354224848179261915075
""" | def matrix_multiply(A, B):
"""
Multiplies two 2x2 matrices A and B.
"""
return [[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]]
def matrix_power(matrix, n):
"""
Raises the... | from solution import fibonacci_matrix
def test_fibonacci_zero():
assert fibonacci_matrix(0) == 0
def test_fibonacci_one():
assert fibonacci_matrix(1) == 1
def test_fibonacci_small():
assert fibonacci_matrix(2) == 1
assert fibonacci_matrix(3) == 2
assert fibonacci_matrix(4) == 3
assert fibonac... | [
{
"docstring": "Multiplies two 2x2 matrices A and B.",
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": "Raises the matrix to the power of n using exponentiation by squaring.",
"function_declaration": "... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_mult(A, B):\n \"\"\"\n Multiplies two 2x2 matrices A and B.\n \"\"\"\n return [[A[0][0]*B[0][0] + A[0][1]*B[1][0], A[0][0]*B[0][1] + A[... | trial_gpt4o_2 | {
"original_instruction": "### Question\nWrite a function `fibonacci_matrix(n: int) -> int` that computes the nth Fibonacci number using matrix exponentiation. The nth Fibonacci number can be derived from the relation:\n\\[ F(n) = \\begin{bmatrix} 1 & 1 \\\\ 1 & 0 \\end{bmatrix}^n \\begin{bmatrix} 1 \\\\ 0 \\end{bmat... | 0.829237 | Data_Structure_45057 | C | [
"matrix_multiply",
"matrix_power",
"fibonacci_matrix"
] | 3 | [
[
"fibonacci_matrix",
"matrix_power"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ec04f7908aeb1e391add252be5f1a75cdcae18a2 | b039e25856c295821bcda638103505748c9a0570 | |||
v1.0 | complete | Data_Structure | Data_Structure_44100_C | class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = [[] for _ in range(vertices)]
def add_edge(self, u, v):
self.graph[u].append(v)
def _dfs(self, v, visited):
visited[v] = True
for i in self.graph[v]:
if not visited[i]:
... | class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = [[] for _ in range(vertices)]
def add_edge(self, u, v):
self.graph[u].append(v)
def _dfs(self, v, visited):
visited[v] = True
for i in self.graph[v]:
if not visited[i]:
... | from solution import Graph, add_multiple_edges, check_strong_connectivity
def test_add_multiple_edges():
graph = Graph(4)
edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
add_multiple_edges(graph, edges)
assert graph.graph == [[1], [2], [3], [0]]
def test_check_strong_connectivity_true():
vertex_count = 5... | [] | [
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 Graph:\n def __init__(self, vertices):\n self.V = vertices\n self.graph = [[] for _ in range(vertices)]\n self.rev_graph = [[] f... | trial_gpt4o_2 | {
"original_instruction": "You are given a class `Graph` that models a directed graph and includes methods to determine if the graph is strongly connected. The code includes methods for adding edges, performing a Depth First Search (DFS), reversing the graph, and checking strong connectivity.\n\n### Problem Statement... | 0.601476 | Data_Structure_44100 | C | [
"add_multiple_edges",
"check_strong_connectivity"
] | 2 | [
[
"check_strong_connectivity",
"add_multiple_edges"
]
] | 1 | [] | false | [
"Graph"
] | true | pytest | true | [] | true | 8a0661032d579e1d1fceb8a56c515d3a36749d02 | da6bb7d6a814ebc410defea707007ed27d78c147 | |||
v1.0 | complete | Data_Structure | Data_Structure_44064_C | def prime_check(num: int) -> bool:
"""
Check if a number is prime.
>>> prime_check(2) == True
>>> prime_check(3) == True
>>> prime_check(4) == False
>>> prime_check(11) == True
>>> prime_check(18) == False
>>> prime_check(23) == True
"""
pass
def find_primitive_root(n: int)... | def prime_check(num: int) -> bool:
"""
Check if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return Fals... | from solution import secure_diffie_hellman_key_exchange, prime_check, find_primitive_root
def test_prime_check():
assert prime_check(2) == True
assert prime_check(3) == True
assert prime_check(4) == False
assert prime_check(11) == True
assert prime_check(18) == False
assert prime_check(23) == T... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Finds all primitive roots of n.",
"function_declaration": "def find_primitive_root(n):",
"function_name": "find_... | [
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 prime_check(n: int) -> bool:\n \"\"\"\n Checks if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n retu... | trial_gpt4o_2 | {
"original_instruction": "### Diffie-Hellman with Improved Primality Check\n\nImplement a function `secure_diffie_hellman_key_exchange(a: int, p: int) -> bool` that performs the Diffie-Hellman key exchange protocol with improved security checks. Your implementation should include the following:\n\n1. **Function**: `... | 0.601881 | Data_Structure_44064 | C | [
"prime_check",
"find_primitive_root",
"secure_diffie_hellman_key_exchange"
] | 3 | [
[
"find_primitive_root",
"prime_check"
],
[
"secure_diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"secure_diffie_hellman_key_exchange",
"prime_check"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | e2991a08278dd857dad8b4fa412fa931cacc0a3e | a8fb2347c134fd48ed89b8f48794082df6c70c76 | |||
v1.0 | complete | Data_Structure | Data_Structure_44310_C | def get_permission(user_permissions: int, permission_index: int) -> int:
"""Returns whether the user has a specific permission (0 or 1).
>>> get_permission(0b10101010, 3)
1
>>> get_permission(0b10101010, 1)
1
>>> get_permission(0b10101010, 2)
0
>>> get_permission(0b00000000, 0)
0
... | def get_permission(user_permissions: int, permission_index: int) -> int:
"""
Returns whether the user has a specific permission (0 or 1).
"""
return (user_permissions >> permission_index) & 1
def grant_permission(user_permissions: int, permission_index: int) -> int:
"""
Grants a specific permis... | import pytest
from solution import get_permission, grant_permission, revoke_permission, update_permission
def test_get_permission():
assert get_permission(0b10101010, 3) == 1
assert get_permission(0b10101010, 1) == 1
assert get_permission(0b10101010, 2) == 0
assert get_permission(0b00000000, 0) == 0
d... | [
{
"docstring": "Returns whether the user has a specific permission (0 or 1).",
"function_declaration": "def get_permission(user_permissions, permission_index):",
"function_name": "get_permission",
"parameter_list": "(user_permissions, permission_index)"
},
{
"docstring": "Grants a specific p... | [
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 get_permission(user_permissions: int, permission_index: int) -> int:\n \"\"\"\n Returns whether the user has a specific permission (0 or 1) based on... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nYou are working on a project handling large datasets related to user permissions. Each user's permissions are represented as a 32-bit integer where each bit signifies the presence (1) or absence (0) of a specific permission. Efficiently manipulating these bits is crucial for y... | 0.466671 | Data_Structure_44310 | C | [
"get_permission",
"grant_permission",
"revoke_permission",
"update_permission"
] | 4 | [
[
"update_permission",
"grant_permission"
],
[
"update_permission",
"revoke_permission"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 70dcf8d2cce7b2b78f8882e5907e5405aa173e83 | 0ccc76f4aff0a159243a993e3e8c29cb59480017 | |||
v1.0 | complete | Data_Structure | Data_Structure_44656_C | def build_pi_table(pattern: str) -> List[int]:
"""
Builds the partial match (pi) table for KMP algorithm.
"""
pass
def knuth_morris_pratt(text: str, pattern: str) -> List[int]:
"""
Given two strings 'text' and 'pattern', return a list of starting indices in 'text' where 'pattern' is found.
... | from typing import List
def build_pi_table(pattern: str) -> List[int]:
"""
Builds the partial match (pi) table for KMP algorithm.
"""
m = len(pattern)
pi = [0] * m
j = 0
for i in range(1, m):
while j > 0 and pattern[i] != pattern[j]:
j = pi[j - 1]
if pattern... | from solution import knuth_morris_pratt
def test_kmp_basic():
assert knuth_morris_pratt('hello there hero!', 'he') == [0, 7, 12]
def test_kmp_repeating_pattern():
assert knuth_morris_pratt('abcabcabcabc', 'abc') == [0, 3, 6, 9]
def test_kmp_overlapping_patterns():
assert knuth_morris_pratt('aaaaa', 'aa')... | [
{
"docstring": "Builds the partial match (pi) table for KMP algorithm.",
"function_declaration": "def build_pi_table(pattern):",
"function_name": "build_pi_table",
"parameter_list": "(pattern)"
},
{
"docstring": "Given two strings 'text' and 'pattern', return a list of starting indices in 't... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef knuth_morris_pratt(text: str, pattern: str) -> List[int]:\n if not pattern:\n return []\n \n def compute_lps_ta... | trial_gpt4o_1 | {
"original_instruction": "### KMP Algorithm: Detect Substring Occurrences\n\n#### Objective\nImplement and optimize the KMP algorithm to search for all occurrences of a pattern within a given text. Your implementation should be efficient and correctly handle various edge cases.\n\n#### Function Signature\n```python\... | 0.537166 | Data_Structure_44656 | C | [
"build_pi_table",
"knuth_morris_pratt"
] | 2 | [
[
"knuth_morris_pratt",
"build_pi_table"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b307585f1d82b475845aa020cdb83ba784fd65fe | 6486764552cccd32e67523afa85b5693287cfa94 | |||
v1.0 | complete | Data_Structure | Data_Structure_44534_C | def binary_insertion_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers `arr` in ascending order using binary insertion sort.
Args:
arr (List[int]): The list of integers to be sorted.
Returns:
List[int]: A new list containing the elements of `arr` sorted in ascending order... | from typing import List
def search_insert(sorted_arr: List[int], value: int) -> int:
"""
Utility function to find the index at which `value` should be inserted in `sorted_arr`
to keep it sorted. This uses binary search for efficiency.
"""
left, right = 0, len(sorted_arr)
while left < right:
... | from solution import binary_insertion_sort
def test_empty_list():
assert binary_insertion_sort([]) == []
def test_single_element():
assert binary_insertion_sort([1]) == [1]
def test_sorted_list():
assert binary_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list():
assert... | [
{
"docstring": "Utility function to find the index at which `value` should be inserted in `sorted_arr`\nto keep it sorted. This uses binary search for efficiency.",
"function_declaration": "def search_insert(sorted_arr, value):",
"function_name": "search_insert",
"parameter_list": "(sorted_arr, valu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(sorted_list: List[int], target: int) -> int:\n \"\"\"\n Perform a binary search to find the index at which ... | trial_gpt4o_2 | {
"original_instruction": "### Context\nInsertion Sort is a simple yet inefficient algorithm for sorting small lists. An efficient variant involves using binary search to find the correct position for insertion. You are required to implement this variant using the provided helper function `search_insert`.\n\n### Prob... | 0.67539 | Data_Structure_44534 | C | [
"search_insert",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6530550bebaa60dbcee15e4eb2628a659dd2d6f2 | 8391e30da93ba1cb05ac8d7b3aa713d776fbdf01 | |||
v1.0 | complete | Data_Structure | Data_Structure_43960_C | from typing import List
def enhanced_interpolation_search(array: List[int], search_key: int) -> int:
"""
Returns the index of search_key in the sorted array if found, otherwise -1.
:param array: A sorted list of integers.
:param search_key: The key to be searched for in the array.
:return... | def enhanced_interpolation_search(array, search_key):
"""
Returns the index of search_key in the sorted array if found, otherwise -1.
"""
if not array:
return -1
low = 0
high = len(array) - 1
while low <= high and search_key >= array[low] and search_key <= array[high]:
if l... | def test_enhanced_interpolation_search():
array = [5, 10, 12, 14, 17, 20, 21]
assert enhanced_interpolation_search(array, 14) == 3
assert enhanced_interpolation_search(array, 55) == -1
assert enhanced_interpolation_search(array, 5) == 0
assert enhanced_interpolation_search([], 1) == -1
# E... | [
{
"docstring": "Returns the index of search_key in the sorted array if found, otherwise -1.",
"function_declaration": "def enhanced_interpolation_search(array, search_key):",
"function_name": "enhanced_interpolation_search",
"parameter_list": "(array, search_key)"
},
{
"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": "from typing import List\n\ndef enhanced_interpolation_search(array: List[int], search_key: int) -> int:\n \"\"\"\n Implements an enhanced interpolation ... | trial_gpt4o_2 | {
"original_instruction": "### Coding Problem: Advanced Interpolation Search Implementation\n\n#### Problem Description:\nYou are tasked with implementing an enhanced version of the interpolation search algorithm that can handle non-uniform distributions efficiently. Your algorithm should still aim to maintain O(log ... | 0.543968 | Data_Structure_43960 | C | [
"enhanced_interpolation_search",
"binary_search"
] | 2 | [
[
"enhanced_interpolation_search",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | cb30142e1ae5413dbb9c773134861c272b3aacf8 | 06349b4a2196c34ba91659e94b292fd540171f7a | |||
v1.0 | complete | Data_Structure | Data_Structure_43969_C | def multi_commodity_max_flow(capacities, sources, sinks):
"""
Calculates the maximum flow for multiple commodities in a flow network.
Parameters:
capacities (List[List[int]]): A 2D array representing the capacities of each edge in the graph.
sources (List[int]): A list of source nodes for each ... | from collections import deque
def bfs(capacities, source, sink, parent):
"""
Returns True if there is a path from source to sink in the residual graph.
Also fills parent[] to store the path.
"""
visited = [False] * len(capacities)
queue = deque([source])
visited[source] = True
whil... | from solution import multi_commodity_max_flow
def test_single_commodity():
capacities = [
[0, 10, 10, 0, 0, 0],
[0, 0, 2, 4, 8, 0],
[0, 0, 0, 0, 9, 0],
[0, 0, 0, 0, 0, 10],
[0, 0, 0, 6, 0, 10],
[0, 0, 0, 0, 0, 0]
]
sources = [0]
sinks = [5]
assert mul... | [
{
"docstring": "Returns True if there is a path from source to sink in the residual graph.\nAlso fills parent[] to store the path.",
"function_declaration": "def bfs(capacities, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacities, source, sink, parent)"
},
{
"docs... | [
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\nclass FlowNetwork:\n def __init__(self, size):\n self.size = size\n self.capacity = [[0] * size for _ in ran... | trial_gpt4o_1 | {
"original_instruction": "Implement a Multi-Commodity Max Flow Algorithm\n\n#### Scenario\nYou work for a logistics company that optimizes the movement of goods through a network of warehouses and transport routes. Each path between warehouses has a certain capacity, and you need to compute the maximum number of dif... | 0.588578 | Data_Structure_43969 | C | [
"bfs",
"edmonds_karp",
"multi_commodity_max_flow"
] | 3 | [
[
"edmonds_karp",
"bfs"
],
[
"multi_commodity_max_flow",
"edmonds_karp"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 33c5921b772e16c45fa63a773a294e849c5ad416 | 6324fb5f2a73881a1f8cc7dda78703099fbbffa7 | |||
v1.0 | complete | Data_Structure | Data_Structure_44701_C | from typing import List
def radix_sort_strings(arr: List[str], k: int) -> List[str]:
"""
Given a list of strings where each string is exactly `k` characters long,
implement the Radix Sort algorithm to sort the strings in lexicographical order.
>>> radix_sort_strings(["bca", "acb", "abc", "cab", "bac"]... | from typing import List
def counting_sort(arr: List[str], index: int) -> List[str]:
"""
A helper function for radix_sort_strings to perform a stable counting sort
based on characters at a specific index.
"""
# Create a count array for 26 lowercase letters
count = [0] * 26
output = ["" for _... | from solution import radix_sort_strings
def test_radix_sort_strings_basic():
input_strings = ["bca", "acb", "abc", "cab", "bac"]
k = 3
expected_output = ['abc', 'acb', 'bac', 'bca', 'cab']
assert radix_sort_strings(input_strings, k) == expected_output
def test_radix_sort_strings_same_strings():
in... | [
{
"docstring": "A helper function for radix_sort_strings to perform a stable counting sort\nbased on characters at a specific index.",
"function_declaration": "def counting_sort(arr, index):",
"function_name": "counting_sort",
"parameter_list": "(arr, index)"
},
{
"docstring": "Sorts an arra... | [
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 radix_sort_strings(arr: List[str], k: int) -> List[str]:\n \"\"\"\n Sort a list of strings using Radix Sort.\n \n A... | trial_gpt4o_2 | {
"original_instruction": "### Coding Problem: Radix Sort for Strings\n\n**Context**:\nConsider a scenario where you need to sort a large list of strings consisting of lowercase letters only. String sorting algorithms often face challenges due to variable lengths and the lexicographical order. Leveraging the principl... | 0.660956 | Data_Structure_44701 | C | [
"counting_sort",
"radix_sort_strings"
] | 2 | [
[
"radix_sort_strings",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 79ee8ddbaa15276da2cea7ed1ee6df2ea9365445 | 2c1b0ebd2130bed5f32ac9676994ccd61b12bf55 | |||
v1.0 | complete | Data_Structure | Data_Structure_45240_C | def secure_key_exchange(p: int, a: int) -> Union[int, str]:
""" Simulate a secure key exchange using the Diffie-Hellman method.
Ensure provided prime number `p` and its primitive root `a` are valid.
Generate private and public keys for two parties (Alice and Bob), compute the shared secret key.
Arg... | 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_mod(base, exp, mod):
... | from solution import secure_key_exchange
def test_secure_key_exchange_valid_prime_and_primitive_root():
p = 23
a = 5
shared_key = secure_key_exchange(p, a)
assert isinstance(shared_key, int)
assert shared_key > 0
def test_secure_key_exchange_invalid_prime():
p = 15
a = 5
assert secure_... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def power_mod(base, exp, mod):",
"function_name": "power_mod",
"parameter_list": "(base, exp, mod)"
},
{
... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Union\nimport random\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n ... | trial_gpt4o_8 | {
"original_instruction": "### Diffie-Hellman Secure Key Exchange Simulation\n\nYou are tasked with implementing a secure key exchange algorithm using the Diffie-Hellman method. The given code snippets include all the utility functions required to verify primes, compute Euler's Totient function, find primitive roots,... | 0.493984 | Data_Structure_45240 | C | [
"is_prime",
"power_mod",
"find_primitive_root",
"secure_key_exchange"
] | 4 | [
[
"find_primitive_root",
"power_mod"
],
[
"secure_key_exchange",
"find_primitive_root"
],
[
"secure_key_exchange",
"is_prime"
],
[
"secure_key_exchange",
"power_mod"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 240b6999ed1b6455f6ffa31b9b4ebe99e1d8fa0c | 8fa6a91146ea821ec8667a8d80d7b8c273a43fb0 | |||
v1.0 | complete | Data_Structure | Data_Structure_44809_C | def identity(d: int) -> list:
"""
Returns the identity matrix of dimension d x d.
"""
return [[1 if i == j else 0 for j in range(d)] for i in range(d)]
def multiply(mat1: list, mat2: list) -> list:
"""
Multiplies two matrices mat1 and mat2.
Returns the resulting matrix.
"""
d = len(... | def identity(d: int) -> list:
"""
Returns the identity matrix of dimension d x d.
"""
return [[1 if i == j else 0 for j in range(d)] for i in range(d)]
def multiply(mat1: list, mat2: list) -> list:
"""
Multiplies two matrices mat1 and mat2.
Returns the resulting matrix.
"""
d = len(... | from solution import matrix_exponentiation_optimized
def test_identity_power():
mat = [
[1, 0],
[0, 1]
]
assert matrix_exponentiation_optimized(mat, 5) == mat
def test_zero_power():
mat = [
[2, 3],
[4, 5]
]
expected = [
[1, 0],
[0, 1]
]
a... | [
{
"docstring": "Returns the identity matrix of dimension d x d.",
"function_declaration": "def identity(d):",
"function_name": "identity",
"parameter_list": "(d)"
},
{
"docstring": "Multiplies two matrices mat1 and mat2.\nReturns the resulting matrix.",
"function_declaration": "def multi... | [
0,
0,
0,
1,
1,
1,
0,
1,
0
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply(mat1, mat2):\n d = len(mat1)\n res = [[0] * d for _ in range(d)]\n for i in range(d):\n for j in range(d):\n for k in ... | trial_gpt4o_8 | {
"original_instruction": "### Scenario:\nYou are tasked with implementing matrix operations as part of a larger scientific computing library. As a first step, you need to verify your understanding of matrix exponentiation using the provided matrix multiplication and identity matrix functions.\n\n### Problem:\nGiven ... | 0.527447 | Data_Structure_44809 | C | [
"identity",
"multiply",
"matrix_exponentiation_optimized"
] | 3 | [
[
"matrix_exponentiation_optimized",
"identity"
],
[
"matrix_exponentiation_optimized",
"multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 064b4f1a61d387e7ca62c1f8729bea4eb4543c93 | 6d791cfaec652e92ae74b0cfd060e63dcb6a2c51 | |||
v1.0 | complete | Data_Structure | Data_Structure_45065_C | from typing import List
def find_words_with_constraints(board: List[List[str]], words: List[str], n: int) -> List[str]:
""" You are given a 2D grid `board` consisting of letters and a list of words.
Write a function `find_words_with_constraints(board: List[List[str]], words: List[str], n: int) -> List[str]`
... | from typing import List
class TrieNode:
def __init__(self):
self.children = {}
self.word = None
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for letter in word:
if letter not in node.children:
... | from solution import find_words_with_constraints
def test_find_words_with_constraints_basic():
board = [['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']]
words = ["oath", "pea", "eat", "rain"]
n = 5
assert sorted(find_words_with_constrain... | [] | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.is_end_of_word = False\n\nclass Trie:\n def __init__(self):\n sel... | trial_gpt4o_5 | {
"original_instruction": "### Word Search with Constraints\n\n#### Objective:\nYou are given a 2D grid `board` consisting of letters and a list of words. Write a function `find_words_with_constraints(board: List[List[str]], words: List[str], n: int) -> List[str]` that returns all words from the list that can be cons... | 0.68128 | Data_Structure_45065 | C | [
"find_words_with_constraints",
"get_usage_count"
] | 2 | [
[
"find_words_with_constraints",
"get_usage_count"
]
] | 1 | [] | false | [
"TrieNode",
"Trie"
] | true | pytest | true | [] | true | dd1bd29b77112cea915382b9f8865c8b7623e8ab | 551c49efae906769ab1d32447dd9665522c3d933 | |||
v1.0 | complete | Data_Structure | Data_Structure_44501_C | from typing import List
def maximum_flow_capacity_scaling(adjacency_matrix: List[List[int]]) -> int:
"""
Computes the maximum flow in a network using the capacity scaling version of the
Ford-Fulkerson method.
Args:
adjacency_matrix (List[List[int]]): an n x n matrix where adjacency_matrix[i][... | def bfs(residual_graph, source, sink, parent):
"""
Breadth-First Search that also stores the path in parent list.
Returns True if there's a path from source to sink.
"""
visited = [False] * len(residual_graph)
queue = [source]
visited[source] = True
while queue:
u = queue.pop(0)... | from solution import maximum_flow_capacity_scaling
def test_example_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow_capacity_scaling(graph) ==... | [
{
"docstring": "Breadth-First Search that also stores the path in parent list.\nReturns True if there's a path from source to sink.",
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs_with_capacity_scaling(residual_graph, source, sink, scale):\n \"\"\"\n Performs BFS to find augmenting path wit... | trial_gpt4o_1 | {
"original_instruction": "### Maximum Flow in a Network with Capacity Scaling\n\nIn network theory, finding the maximum flow through a network is a common problem with applications in various domains, such as traffic flow management and data routing. In this problem, you will implement a more advanced version of the... | 0.589346 | Data_Structure_44501 | C | [
"bfs",
"maximum_flow_capacity_scaling"
] | 2 | [
[
"maximum_flow_capacity_scaling",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4404635cc32e81d9fa970f2021b3f64e1ac3709d | cf69a429a124e76df3941ca04a61cf700cd19266 | |||
v1.0 | complete | Data_Structure | Data_Structure_45250_C | from typing import List, Optional, Tuple
class UndirectedGraphNode:
def __init__(self, label: int):
self.label = label
self.neighbors = []
def add_neighbor(self, node: 'UndirectedGraphNode'):
self.neighbors.append(node)
def clone_and_validate_path(node: Optional[UndirectedGraphNode], ... | from typing import List, Optional, Tuple
class UndirectedGraphNode:
def __init__(self, label: int):
self.label = label
self.neighbors = []
def add_neighbor(self, node: 'UndirectedGraphNode'):
self.neighbors.append(node)
def clone_graph(node: Optional[UndirectedGraphNode]) -> Optional[... | from solution import UndirectedGraphNode, clone_and_validate_path
def test_clone_and_validate_path_empty_graph():
assert clone_and_validate_path(None, [1, 2]) == (None, False)
def test_clone_and_validate_path_simple_graph_valid_path():
node0 = UndirectedGraphNode(0)
node1 = UndirectedGraphNode(1)
node... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Optional, List, Tuple\nfrom collections import deque\n\nclass UndirectedGraphNode:\n def __init__(self, label: int):\n self.label... | trial_gpt4o_1 | {
"original_instruction": "### Graph Cloning with Path Validation\n\nYou are given an undirected graph representation using a class `UndirectedGraphNode` and a function `clone_graph` that can clone graphs. Your task is to enhance this cloning function with an additional feature: validate if a particular path exists i... | 0.539176 | Data_Structure_45250 | C | [
"clone_graph",
"find_path",
"clone_and_validate_path"
] | 3 | [
[
"clone_and_validate_path",
"clone_graph"
],
[
"clone_and_validate_path",
"find_path"
]
] | 2 | [] | false | [
"UndirectedGraphNode"
] | true | pytest | true | [] | true | 338d5b820092e923a67c7586dbca5ede70292f46 | e65d22c6a8961ee0e8732134a0cfb42bdc1edeb3 | |||
v1.0 | complete | Data_Structure | Data_Structure_45269_C | def enhanced_quick_sort(arr):
"""Sorts an array using an optimized Quick Sort algorithm.
Args:
arr (list): List of integers to sort.
Returns:
list: Sorted list of integers.
The implementation enhances performance by choosing an optimal pivot and
handles diverse edge c... | from random import randint
def insertion_sort(arr, left, right):
"""Use insertion sort for smaller sub-arrays for efficiency."""
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j... | from solution import enhanced_quick_sort
def test_empty_array():
assert enhanced_quick_sort([]) == []
def test_single_element_array():
assert enhanced_quick_sort([3]) == [3]
def test_sorted_array():
assert enhanced_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reversed_array():
assert enha... | [
{
"docstring": "Use insertion sort for smaller sub-arrays for efficiency.",
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": "Hoare partition scheme with a randomized pivot.",
"fun... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef 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 >= ... | trial_gpt4o_2 | {
"original_instruction": "### Quick Sort Implementation with Edge Case Handling\n\n#### Scenario:\nYou are developing a high-performance software system that frequently requires sorting datasets of various lengths and distributions. While Quick Sort is a strong candidate due to its average-case efficiency, you need ... | 0.64356 | Data_Structure_45269 | C | [
"insertion_sort",
"partition",
"_quick_sort",
"enhanced_quick_sort"
] | 4 | [
[
"_quick_sort",
"insertion_sort"
],
[
"_quick_sort",
"partition"
],
[
"enhanced_quick_sort",
"_quick_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | bbce2c966721c63c0943b7552c90b305e3caf7e7 | 9ea5668c66505c48b25e932a79245dba9f3cff04 | |||
v1.0 | complete | Data_Structure | Data_Structure_45343_C | def diffie_hellman_key_exchange(a: int, p: int, display_steps: bool = False) -> bool:
"""
Perform Diffie-Hellman key exchange.
Parameters:
- a (int): The primitive root of p.
- p (int): A large prime number.
- display_steps (bool): If True, print the steps of the key exchange process.
... | import random
from sympy import isprime, primerange
def is_primitive_root(a, p):
required_set = set(num for num in range(1, p) if gcd(num, p) == 1)
actual_set = set(pow(a, powers, p) for powers in range(1, p))
return required_set == actual_set
def gcd(a, b):
while b:
a, b = b, a % b
return... | from solution import diffie_hellman_key_exchange
def test_diffie_hellman_key_exchange_valid_keys():
assert diffie_hellman_key_exchange(5, 23, False) == True
def test_diffie_hellman_key_exchange_invalid_prime():
try:
diffie_hellman_key_exchange(5, 21, False)
assert False, "Expected ValueError"
... | [
{
"docstring": null,
"function_declaration": "def is_primitive_root(a, p):",
"function_name": "is_primitive_root",
"parameter_list": "(a, p)"
},
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstri... | [
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, primerange\n\ndef is_primitive_root(a, p):\n required_set = set(num for num in range(1, p) if gcd(num, p) == 1)\n... | trial_gpt4o_0 | {
"original_instruction": "In this task, you are required to write a Python function that performs the Diffie-Hellman Key Exchange algorithm outlined above. You will implement both the key exchange and verification of the shared key. Make sure to handle all edge cases and possible errors.\n\n#### Function Signature\n... | 0.491038 | Data_Structure_45343 | C | [
"is_primitive_root",
"gcd",
"diffie_hellman_key_exchange"
] | 3 | [
[
"diffie_hellman_key_exchange",
"is_primitive_root"
],
[
"is_primitive_root",
"gcd"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | c9280d01fe3d730605950b92f82d3bb711baeab9 | 8e7a8432229e35f845ddc2d866deac3b3f402ae6 | |||
v1.0 | complete | Data_Structure | Data_Structure_45110_C | def stoogesort(arr, l, h, performance_data=None):
"""
Sorts arr[l..h] using Stooge Sort algorithm.
Parameters:
arr (list of int): The list of integers to be sorted.
l (int): Starting index of the current segment of the array to be sorted.
h (int): Ending index of the current segment of the ... | import time
def stoogesort(arr, l, h, performance_data=None):
"""
Sorts arr[l..h] using Stooge Sort algorithm.
"""
if l >= h:
return
# Compare arr[l] and arr[h]
if performance_data is not None:
performance_data['comparisons'] += 1
if arr[l] > arr[h]:
arr[l], ar... | from solution import stoogesort, analyze_stoogesort_performance
def test_stoogesort_basic():
arr = [3, 2, 1]
stoogesort(arr, 0, len(arr) - 1)
assert arr == [1, 2, 3]
def test_stoogesort_single_element():
arr = [1]
stoogesort(arr, 0, len(arr) - 1)
assert arr == [1]
def test_stoogesort_sorted_a... | [
{
"docstring": "Sorts arr[l..h] using Stooge Sort algorithm.",
"function_declaration": "def stoogesort(arr, l, h, performance_data=None):",
"function_name": "stoogesort",
"parameter_list": "(arr, l, h, performance_data=None)"
},
{
"docstring": null,
"function_declaration": "def analyze_s... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\n\ndef stoogesort(arr, l, h):\n \"\"\"\n Sorts an array using the Stooge Sort algorithm.\n \n Parameters:\n arr (list): the list of... | trial_gpt4o_2 | {
"original_instruction": "### Stooge Sort Implementation and Analysis\n\nImagine you are a data scientist who has been provided with an archaic and theoretical sorting algorithm, Stooge Sort. You are tasked with writing the implementation and providing an analysis of its performance on various edge cases.\n\n#### Ta... | 0.605876 | Data_Structure_45110 | C | [
"stoogesort",
"analyze_stoogesort_performance"
] | 2 | [
[
"analyze_stoogesort_performance",
"stoogesort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9dab647d18b48b0ddd935197dc7fecee43c85f1d | fe940e435abc9fce0fda3dfb36445fe9a64de262 | |||
v1.0 | complete | Data_Structure | Data_Structure_44586_C | def nearest_neighbor_manhattan(test_point, data_set):
"""
Finds the nearest neighbor of test_point in data_set using Manhattan distance.
Parameters:
test_point (tuple): A tuple representing the test point (x1, x2, ..., xn).
data_set (dict): A dictionary where keys are tuples representing po... | def manhattan_distance(point1, point2):
"""
Computes the Manhattan distance between two points.
Parameters:
point1 (tuple): The first point.
point2 (tuple): The second point.
Returns:
int: The Manhattan distance between the two points.
"""
return sum(abs(a - b) ... | from solution import nearest_neighbor_manhattan
def test_single_point_data_set():
test_point = (3, 4)
data_set = {(1, 2): 'A'}
assert nearest_neighbor_manhattan(test_point, data_set) == 'A'
def test_multiple_points_data_set():
test_point = (3, 4)
data_set = {
(1, 2): 'A',
(5, 5): '... | [
{
"docstring": "Computes the Manhattan distance between two points.\n\nParameters:\n point1 (tuple): The first point.\n point2 (tuple): The second point.\n\nReturns:\n int: The Manhattan distance between the two points.",
"function_declaration": "def manhattan_distance(point1, point2):",
"funct... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def nearest_neighbor_manhattan(test_point, data_set):\n \"\"\"\n Finds the nearest neighbor of test_point in data_set using Manhattan distance.\n\n P... | trial_gpt4o_1 | {
"original_instruction": "You are tasked with implementing a variant of the Nearest Neighbor algorithm. Instead of using Euclidean distance, you will use Manhattan distance (also known as L1 distance).\n\n### Scenario\nYou are given a dataset of points where each point has a label, and a test point for which you nee... | 0.651726 | Data_Structure_44586 | C | [
"manhattan_distance",
"nearest_neighbor_manhattan"
] | 2 | [
[
"nearest_neighbor_manhattan",
"manhattan_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 737b7c0676e188d7d01f7ba73e38e966974c7521 | 72dcfd358604f728a930dd4cb37d777f0203ba54 | |||
v1.0 | complete | Data_Structure | Data_Structure_45134_C | def calculate_max_height(keys):
"""
Computes the maximum height of the AVL tree after inserting all keys.
:param keys: A list of integers to insert into the AVL tree.
:return: An integer representing the maximum height of the AVL tree.
"""
# Your implementation here
class TreeNode:
def __i... | class TreeNode:
def __init__(self, key):
self.key = key
self.height = 1
self.left = None
self.right = None
def get_height(node):
if not node:
return 0
return node.height
def update_height(node):
if node:
node.height = 1 + max(get_height(node.left), get_h... | from solution import calculate_max_height
def test_empty_tree():
assert calculate_max_height([]) == 0
def test_single_element():
assert calculate_max_height([10]) == 1
def test_balanced_tree():
assert calculate_max_height([10, 20, 30, 40, 50, 25]) == 3
def test_left_heavy_tree():
assert calculate_ma... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n self.height = 1\n\nclass AVLTr... | trial_gpt4o_1 | {
"original_instruction": "### AVL Tree Maximum Height Challenge\n\nYour task is to complete the implementation of an AVL tree as laid out in the provided partial implementation. Specifically, you need to write a function `calculate_max_height` that computes the maximum height of the AVL tree after a series of insert... | 0.489575 | Data_Structure_45134 | C | [
"get_height",
"update_height",
"get_balance",
"right_rotate",
"left_rotate",
"insert",
"compute_max_height",
"calculate_max_height"
] | 8 | [
[
"calculate_max_height",
"compute_max_height"
],
[
"calculate_max_height",
"insert"
],
[
"get_balance",
"get_height"
],
[
"insert",
"get_balance"
],
[
"insert",
"left_rotate"
],
[
"insert",
"right_rotate"
],
[
"insert",
"update_height"... | 10 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 63814604ab803d09d945fe68758ebe8764a6191c | 7167ab76575e5c542978e61d803b484571288a6b | |||
v1.0 | complete | Data_Structure | Data_Structure_45244_C | def get_bit(num, i):
""" Returns the bit value (0 or 1) at the specified index from the integer `num`.
>>> get_bit(0b101, 0) == 1
>>> get_bit(0b101, 1) == 0
>>> get_bit(0b101, 2) == 1
"""
pass
def set_bit(num, i):
""" Returns an integer with the bit at the specified index set to 1.
>>> ... | def get_bit(num, i):
"""
Returns the bit value (0 or 1) at the specified index from the integer `num`.
"""
if i < 0 or i >= 32:
raise ValueError("Index out of range")
return (num >> i) & 1
def set_bit(num, i):
"""
Returns an integer with the bit at the specified index set to 1.
... | import pytest
from solution import get_bit, set_bit, clear_bit, update_bit
def test_get_bit():
assert get_bit(0b101, 0) == 1
assert get_bit(0b101, 1) == 0
assert get_bit(0b101, 2) == 1
with pytest.raises(ValueError):
get_bit(0b101, 32)
def test_set_bit():
assert set_bit(0b101, 1) == 0b111
... | [
{
"docstring": "Returns the bit value (0 or 1) at the specified index from the integer `num`.",
"function_declaration": "def get_bit(num, i):",
"function_name": "get_bit",
"parameter_list": "(num, i)"
},
{
"docstring": "Returns an integer with the bit at the specified index set to 1.",
"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_bit(num, i):\n \"\"\"\n Returns the bit value (0 or 1) at the specified index from the integer `num`.\n \"\"\"\n if i < 0 or i > 31:\n ... | trial_gpt4o_2 | {
"original_instruction": "#### Context\nYou work for a company developing a low-level hardware driver for a new communication device. This device relies on efficient bit manipulation to handle its numerous control flags effectively. Your task is to implement several functions that will set, clear, get, and update sp... | 0.719698 | Data_Structure_45244 | C | [
"get_bit",
"set_bit",
"clear_bit",
"update_bit"
] | 4 | [
[
"update_bit",
"clear_bit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6c8f6f4cd30dbbd0436cc4733454fb7e2c25ac55 | 4d619bd34c2efe4286ab1708ef7a334a467680a8 | |||
v1.0 | complete | Data_Structure | Data_Structure_45556_C | from typing import List
def max_flow(capacity: List[List[int]], source: int, sink: int) -> int:
""" Determine the maximum flow from a given source node to a sink node in a directed graph using Dinic's algorithm.
Args:
capacity (List[List[int]]): A 2D list of integers where capacity[i][j] is the capaci... | from typing import List
from collections import deque
def bfs_level_graph(capacity: List[List[int]], source: int, sink: int, level: List[int]) -> bool:
V = len(capacity)
for i in range(V):
level[i] = -1
level[source] = 0
queue = deque([source])
while queue:
u = queue.popleft()
... | from solution import max_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 max_flow(capacity, source, sin... | [
{
"docstring": null,
"function_declaration": "def bfs_level_graph(capacity, source, sink, level):",
"function_name": "bfs_level_graph",
"parameter_list": "(capacity, source, sink, level)"
},
{
"docstring": null,
"function_declaration": "def dfs_send_flow(u, flow, sink, capacity, level, s... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List\n\ndef bfs(level: List[int], capacity: List[List[int]], source: int, sink: int) -> bool:\n n = len(c... | trial_gpt4o_1 | {
"original_instruction": "Maximum Flow - Advanced Graph Algorithms\n\n#### Scenario\nA company is building a network of pipelines to transport water from a source to various facilities. The pipelines have different capacities, and the company needs to determine the maximum amount of water that can be transported fro... | 0.558794 | Data_Structure_45556 | C | [
"bfs_level_graph",
"dfs_send_flow",
"max_flow"
] | 3 | [
[
"max_flow",
"bfs_level_graph"
],
[
"max_flow",
"dfs_send_flow"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4801ee251d23d46880f705b25eab901ffb715bff | e88e782732ba34cb04ba70edfed622757b630d11 | |||
v1.0 | complete | Data_Structure | Data_Structure_45426_C | from fractions import Fraction
from collections import defaultdict
class Monomial:
def __init__(self, vars, coeff=1):
"""Initialize a monomial with variables and coefficients."""
def __mul__(self, other):
"""Multiply this monomial by another monomial or a scalar."""
def __truediv__(self, ... | from fractions import Fraction
from collections import defaultdict
class Monomial:
def __init__(self, vars, coeff=1):
self.vars = {v: exp for v, exp in vars.items() if exp != 0} # Filter out zero exponents
self.coeff = Fraction(coeff)
def __mul__(self, other):
assert isinstance(other,... | from solution import Monomial, Polynomial, gcd, lcm
def test_monomial_multiplication():
mon1 = Monomial({1: 2, 2: 1}, 2)
mon2 = Monomial({2: 3, 3: 1}, 3)
result = mon1 * mon2
assert result == Monomial({1: 2, 2: 4, 3: 1}, 6)
def test_polynomial_addition():
poly1 = Polynomial([Monomial({1: 1}, 2)])
... | [] | [
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 math import prod\nfrom fractions import Fraction\nfrom collections import defaultdict\n\nclass Monomial:\n def __init__(self, variables, coefficient):... | trial_gpt4o_2 | {
"original_instruction": "### Objective\nDesign and implement a class for polynomials that supports basic arithmetic operations and some advanced features. Your class should be able to handle monomials and perform polynomial operations such as addition, subtraction, multiplication, and division.\n\n### Problem State... | 0.595661 | Data_Structure_45426 | C | [
"gcd",
"lcm"
] | 2 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [
"Monomial",
"Polynomial"
] | true | pytest | true | [] | true | a73d9c54680c1c9129b164ffc85da40615915130 | 454d0c0d56d387ae24dcedb68ddc9a4feb340e1c | |||
v1.0 | complete | Data_Structure | Data_Structure_45660_C | def gcd(a: int, b: int) -> int:
""" Helper function to compute GCD of two integers using the Euclidean algorithm.
"""
pass
def find_order(a: int, n: int) -> int:
""" Returns the smallest positive integer k such that a^k ≡ 1 (mod n).
If gcd(a, n) != 1, print an error message and return -1.
If a ... | def gcd(a, b):
"""Helper function to compute GCD of two integers using Euclidean algorithm."""
while b:
a, b = b, a % b
return a
def find_order(a, n):
"""
Returns the smallest positive integer k such that a^k ≡ 1 (mod n).
If gcd(a, n) != 1, print an error message and return -1.
If a... | from solution import find_order
def test_find_order_relative_primes():
assert find_order(3, 7) == 6
assert find_order(10, 17) == 16
assert find_order(4, 13) == 6
def test_find_order_non_relative_primes():
assert find_order(2, 8) == -1
assert find_order(3, 9) == -1
def test_find_order_a_equals_1_n... | [
{
"docstring": "Helper function to compute GCD of two integers using Euclidean algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the smallest positive integer k such that a^k ≡ 1 (mod n).\nIf gcd(a, n) != 1, p... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef find_order(a, n):\n if gcd(a, n) != 1:\n print(\"a and n should be relati... | trial_gpt4o_5 | {
"original_instruction": "### Scenario\n\nImagine you are working on implementing a robust encryption algorithm. As part of the encryption process, you need to compute the modular order of integers to strengthen the encryption scheme. Given integers `a` and `n`, the order of `a` modulo `n` is defined as the smallest... | 0.701566 | Data_Structure_45660 | C | [
"gcd",
"find_order"
] | 2 | [
[
"find_order",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 846971dcf11dd6db7a020636b4d7aa1b7e79c406 | 09d9b85b099d667a3359acf39a696a97ad781254 | |||
v1.0 | complete | Data_Structure | Data_Structure_45635_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
""" Determine if t is a subtree of s.
>>> s = TreeNode(3)
>>> s.left = TreeNode(4)
>>> s.right = TreeNode(5... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_same_tree(s: TreeNode, t: TreeNode) -> bool:
if not s and not t:
return True
if not s or not t:
return False
if s.val != t.val:
ret... | import pytest
from solution import TreeNode, is_subtree
def test_subtree_case_1():
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.left.right = TreeNode(2)
t = TreeNode(4)
t.left = TreeNode(1)
t.right = TreeNode(2)
assert is_subtree(s... | [] | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n sel... | trial_gpt4o_2 | {
"original_instruction": "### Subtree Verification Challenge\n\nYou are given two binary trees, `s` (large tree) and `t` (potential subtree). Write a function to determine if `t` is a subtree of `s`. A subtree of `s` is defined as a node in `s` and all its descendants that form a tree identical to `t`.\n\n#### Input... | 0.562491 | Data_Structure_45635 | C | [
"is_same_tree",
"is_subtree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 9ba1f635f9da4a8e392ceb29660a1ceafedb103c | 9287c777c849d0c0f1212534a430a62dec664bea | |||
v1.0 | complete | Data_Structure | Data_Structure_45223_C | def heap_sort_switch(arr, sort_type, simulation=False):
"""
Sorts the array using either max heap or min heap sort based on 'sort_type'.
Parameters:
arr (list of int): The array to be sorted
sort_type (str): 'max' for max heap sort, 'min' for min heap sort
simulation (bool): If True, enable... | def max_heapify(arr, n, i, simulation):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[l] > arr[largest]:
largest = l
if r < n and arr[r] > arr[largest]:
largest = r
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
if simulation:
... | from solution import heap_sort_switch
def test_heap_sort_switch_max():
arr = [4, 10, 3, 5, 1]
sorted_arr = heap_sort_switch(arr, 'max')
assert sorted_arr == [1, 3, 4, 5, 10]
def test_heap_sort_switch_min():
arr = [4, 10, 3, 5, 1]
sorted_arr = heap_sort_switch(arr, 'min')
assert sorted_arr == [... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, simulation):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, simulation)"
},
{
"docstring": null,
"function_declaration": "def max_heap_sort(arr, simulation=False):",
"function_name": "max_heap_... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_heapify(arr, n, i, simulation=False):\n largest = i\n l = 2 * i + 1\n r = 2 * i + 2\n\n if l < n and arr[l] > arr[largest]:\n large... | trial_gpt4o_5 | {
"original_instruction": "### Question\n\nGiven the provided implementations of max heap sort and min heap sort algorithms, you are required to write a function that switches between the sorting algorithms based on user input.\n\nThe function signature should be defined as follows:\n```python\ndef heap_sort_switch(a... | 0.589442 | Data_Structure_45223 | C | [
"max_heapify",
"max_heap_sort",
"min_heapify",
"min_heap_sort",
"heap_sort_switch"
] | 5 | [
[
"heap_sort_switch",
"max_heap_sort"
],
[
"heap_sort_switch",
"min_heap_sort"
],
[
"max_heap_sort",
"max_heapify"
],
[
"min_heap_sort",
"min_heapify"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 73e3135b7eeccb0ac7f0fda618def2ee3b36b572 | b020e44727748da63818424f2f1751e7f6e035fe | |||
v1.0 | complete | Data_Structure | Data_Structure_45180_C | from typing import List
def rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:
"""
Rotate the given matrix 90 degrees clockwise.
>>> rotate_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
>>> rotate_clockwise([[1]])
[[1]]
>>> rotate_clockwise([])
... | from typing import List
def rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:
"""
Rotate the given matrix 90 degrees clockwise.
"""
return [list(row) for row in zip(*matrix[::-1])]
def rotate_counterclockwise(matrix: List[List[int]]) -> List[List[int]]:
"""
Rotate the given matrix ... | import pytest
from solution import rotate_clockwise, rotate_counterclockwise, bottom_left_invert, rotate_anticlockwise
def test_rotate_clockwise():
assert rotate_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
assert rotate_clockwise([[1]]) == [[1]]
assert rotate_clockwis... | [
{
"docstring": "Rotate the given matrix 90 degrees clockwise.",
"function_declaration": "def rotate_clockwise(matrix):",
"function_name": "rotate_clockwise",
"parameter_list": "(matrix)"
},
{
"docstring": "Rotate the given matrix 90 degrees counterclockwise.",
"function_declaration": "de... | [
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 rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Rotate the given matrix 90 degrees clockwise.\n ... | trial_gpt4o_0 | {
"original_instruction": "### Question: Matrix Manipulation Functions\n\n#### Context\nYou are working on a project that involves image processing. Images in your system are represented as 2D matrices of pixels. You need to implement various transformations on these matrices, including rotating them and inverting th... | 0.58954 | Data_Structure_45180 | C | [
"rotate_clockwise",
"rotate_counterclockwise",
"bottom_left_invert",
"rotate_anticlockwise"
] | 4 | [
[
"rotate_anticlockwise",
"rotate_counterclockwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d86b8f5df078c4063651b36f5f74cde0f1cde1c9 | 2fffa3f7fae1b942451fdac3b230f3b5d6d7ab98 | |||
v1.0 | complete | Data_Structure | Data_Structure_45460_C | import random
from typing import Tuple
def optimized_generate_key(k: int, seed: int = None) -> Tuple[int, int, int]:
"""
Optimized RSA key generating algorithm.
k: Number of bits in n
seed: Optional seed for reproducibility of the random number generator
Returns: (n, e, d): Tuple of RSA modulus and... | import random
def miller_rabin_test(n, k: int) -> bool:
"""
Miller-Rabin primality test.
n: the number to be tested for primality
k: number of testing rounds for accuracy
Returns: True if n is likely prime, False if composite
"""
if n in (2, 3):
return True
if n <= 1 or n % 2 ==... | from solution import optimized_generate_key, miller_rabin_test, generate_large_prime, extended_gcd, modinv_optimized
def test_miller_rabin_test():
assert miller_rabin_test(101, 5) == True
assert miller_rabin_test(10, 5) == False
def test_generate_large_prime():
prime = generate_large_prime(16)
assert ... | [
{
"docstring": "Miller-Rabin primality test.\nn: the number to be tested for primality\nk: number of testing rounds for accuracy\nReturns: True if n is likely prime, False if composite",
"function_declaration": "def miller_rabin_test(n, k):",
"function_name": "miller_rabin_test",
"parameter_list": "... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef miller_rabin_test(n, k: int) -> bool:\n \"\"\"\n Miller-Rabin primality test.\n n: the number to be tested for primality\n k:... | trial_gpt4o_0 | {
"original_instruction": "### Question: Implement RSA Key Pair Generation with Optimized Prime Testing.\nThe RSA algorithm provided includes simple prime testing and modular inverse calculations which may not be efficient for large bit sizes. Your task is to enhance the RSA key generation function for improved perfo... | 0.613122 | Data_Structure_45460 | C | [
"miller_rabin_test",
"generate_large_prime",
"extended_gcd",
"modinv_optimized",
"optimized_generate_key"
] | 5 | [
[
"generate_large_prime",
"miller_rabin_test"
],
[
"modinv_optimized",
"extended_gcd"
],
[
"optimized_generate_key",
"generate_large_prime"
],
[
"optimized_generate_key",
"modinv_optimized"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | b8c7b8e67ec5000be868888ae0aaf1b1f5e6fb16 | 6a4cda91e457ea443c635c25677c91f77b167331 | |||
v1.0 | complete | Data_Structure | Data_Structure_45765_C | def distance(x: tuple, y: tuple) -> float:
"""
Computes the Euclidean distance between two vectors x and y.
>>> distance((1.0, 2.0), (1.0, 2.0))
0.0
>>> distance((1.0, 2.0), (4.0, 6.0))
5.0
"""
pass
def nearest_neighbor(x: tuple, tSet: dict, k: int) -> any:
"""
Finds the k nea... | import math
from collections import defaultdict
def distance(x: tuple, y: tuple) -> float:
"""
Computes the Euclidean distance between two vectors x and y.
"""
assert len(x) == len(y), "Vectors must be of the same length."
return math.sqrt(sum((xi - yi) ** 2 for xi, yi in zip(x, y)))
def nearest_n... | from solution import distance, nearest_neighbor
def test_distance_same_vector():
assert distance((1.0, 2.0), (1.0, 2.0)) == 0.0
def test_distance_different_vectors():
assert distance((1.0, 2.0), (4.0, 6.0)) == 5.0
def test_distance_throws_on_different_lengths():
try:
distance((1.0, 2.0), (1.0, 2.... | [] | [
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 distance(x: tuple, y: tuple) -> float:\n \"\"\"\n Returns the Euclidean distance between vectors x and y.\n \"\"\"\n assert len... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with implementing an enhanced nearest neighbor classifier. In addition to the plain nearest neighbor search, you must also incorporate a weighted voting scheme based on the inverse of the distance to each neighbor. The final classification is determined by the vector class th... | 0.717865 | Data_Structure_45765 | C | [
"distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3524e6219ef9f7b7dd248835bd05f52510d92f87 | f44498fd5129058da70a5ce85c2076721c1bcd5c | |||
v1.0 | complete | Data_Structure | Data_Structure_45854_C | from typing import Union
def secure_diffie_hellman(a: int, p: int) -> Union[int, str]:
"""
Implement a Secure Diffie-Hellman Key Exchange with Primality and Primitive Root Check.
Verifies that `p` is a large prime number.
Checks that `a` is a primitive root of `p`.
Completes the Diffie-Hellma... | from typing import Union
from sympy import isprime, mod_inverse
def is_primitive_root(a, p):
"""
Check if a is a primitive root of prime p.
"""
if not isprime(p):
return False
required_set = set(num for num in range(1, p) if gcd(num, p) == 1)
actual_set = set(pow(a, powers, p) for... | import pytest
from solution import secure_diffie_hellman
def test_prime_verification():
assert secure_diffie_hellman(5, 20) == "20 is not a prime number"
assert secure_diffie_hellman(5, 18) == "18 is not a prime number"
def test_primitive_root_verification():
assert secure_diffie_hellman(5, 23) == 2 # As... | [
{
"docstring": "Check if a is a primitive root of prime p.",
"function_declaration": "def is_primitive_root(a, p):",
"function_name": "is_primitive_root",
"parameter_list": "(a, p)"
},
{
"docstring": null,
"function_declaration": "def secure_diffie_hellman(a, p):",
"function_name": "... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Union\nimport random\nimport sympy\n\ndef is_prime(n: int) -> bool:\n return sympy.isprime(n)\n\ndef find_primitive_root(p: int) -> int:... | trial_gpt4o_9 | {
"original_instruction": "### Question: Implement a Secure Diffie-Hellman Key Exchange with Primality and Primitive Root Check\n\n#### Scenario:\nAlice and Bob want to securely share a secret key over an insecure channel using the Diffie-Hellman key exchange algorithm. As part of this process, they need to verify th... | 0.510012 | Data_Structure_45854 | C | [
"is_primitive_root",
"secure_diffie_hellman",
"gcd"
] | 3 | [
[
"is_primitive_root",
"gcd"
],
[
"secure_diffie_hellman",
"is_primitive_root"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | e6b15a95a2b77a56c3d9b3e8d1cf1ff9e5a72148 | fa1d247247885b5b7c8210bae9e79f7d086639ec | |||
v1.0 | complete | Data_Structure | Data_Structure_45986_C | from typing import List
def find_special_numbers(start: int, end: int) -> List[int]:
""" Identify and return a list of numbers within a given range that exhibit the "special number" property.
>>> find_special_numbers(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> find_special_numbers(1, 100)
[1, 2, 3, 4, 5... | from typing import List
def is_special_number(num: int) -> bool:
digit_str = str(num)
total = sum(int(digit_str[i]) ** (i + 1) for i in range(len(digit_str)))
return total == num
def find_special_numbers(start: int, end: int) -> List[int]:
return [num for num in range(start, end + 1) if is_special_num... | from solution import find_special_numbers
def test_single_digit_numbers():
assert find_special_numbers(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_double_digit_numbers():
assert find_special_numbers(10, 100) == [89]
def test_range_including_special_numbers():
assert find_special_numbers(1, 100) == [1,... | [
{
"docstring": null,
"function_declaration": "def is_special_number(num):",
"function_name": "is_special_number",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def find_special_numbers(start, end):",
"function_name": "find_special_numbers",
"parameter... | [
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 is_special_number(num: int) -> bool:\n digit_str = str(num)\n total = sum(int(digit_str[i]) ** (i + 1) for i in range(len... | trial_gpt4o_0 | {
"original_instruction": "#### Problem Statement\nWrite a function named `find_special_numbers` that identifies and returns a list of numbers within a given range that exhibit the \"special number\" property. A \"special number\" is defined as a number whose sum of its digits raised to consecutive powers equals the ... | 0.610435 | Data_Structure_45986 | C | [
"is_special_number",
"find_special_numbers"
] | 2 | [
[
"find_special_numbers",
"is_special_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b757d262a0b5c776c1b9a95622a49b8cd9a64e24 | 409d67b3fe8902b6143c6a4b8afc1b334251c8eb | |||
v1.0 | complete | Data_Structure | Data_Structure_45663_C | from typing import List
def maximum_flow_bfs(adjacency_matrix: List[List[int]]) -> int:
""" Determine the maximum flow in a network using the BFS-based Edmonds-Karp method.
>>> maximum_flow_bfs([
... [0, 16, 13, 0, 0, 0],
... [0, 0, 10, 12, 0, 0],
... [0, 4, 0, 0, 14, 0],
... [... | from collections import deque
def bfs_capacity(residual_graph, source, sink, parent):
visited = [False] * len(residual_graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(residual_graph[u]):
if not visited[v] ... | def test_maximum_flow_bfs_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_maximum_flow_bfs_no_path():
graph = ... | [
{
"docstring": null,
"function_declaration": "def bfs_capacity(residual_graph, source, sink, parent):",
"function_name": "bfs_capacity",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(adjacency_matrix):",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs_capacity(residual_graph, source, sink, parent):\n visited = [False] * len(residual_graph)\n queue = deque([sour... | trial_gpt4o_0 | {
"original_instruction": "### Assessing Maximum Flow Computation\n\n**Objective**:\nDesign an algorithm to determine the maximum flow in a network using the BFS-based Edmonds-Karp method.\n\n**Scenario/Context**:\nYou've been tasked with optimizing the network traffic flow between a source node and sink node in a ci... | 0.611834 | Data_Structure_45663 | C | [
"bfs_capacity",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs_capacity"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 624c3e4f33e00a795954a5754959bcf666e27a39 | 54242e1e7781fdc4082465387d650d75fa6d2d05 | |||
v1.0 | complete | Data_Structure | Data_Structure_44968_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers using the Merge Sort algorithm.
Args:
arr (List[int]): List of integers to sort.
Returns:
List[int]: Sorted list of integers.
Examples:
>>> merge_sort([4, 3, 5, 1, 2])
[1, 2... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers using the Merge Sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left... | from solution import merge_sort
def test_merge_sort():
assert merge_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5]
assert merge_sort([6, 5, 6, 2, 1]) == [1, 2, 5, 6, 6]
assert merge_sort([]) == []
assert merge_sort([1]) == [1]
assert merge_sort([3, 3, 3, 3]) == [3, 3, 3, 3]
assert merge_sort([-1, 0, ... | [
{
"docstring": "Sorts a list of integers using the Merge Sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into one sorted list.",
"function_declaration": "def merge(left, ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n def merge(left: List[int], right: Li... | trial_gpt4o_2 | {
"original_instruction": "### Scenario\nYou are tasked with implementing the Merge Sort algorithm for a list of integers. As part of the implementation, you also need to provide a detailed check for edge cases and optimize the helper functions as necessary.\n\n### Task\nWrite a Python function `merge_sort(arr)` that... | 0.57067 | Data_Structure_44968 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f147ab547e1eb755a986a3693bc4495438afcaf9 | 1eb18a4059c4c330e0c38cc28753d5ed33365b1e | |||
v1.0 | complete | Data_Structure | Data_Structure_45998_C | def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
""" Implement the Radix Sort algorithm to sort a list of non-negative integers.
Optionally print the state of the list after each digit processing iteration if simulation is True.
Args:
arr (List[int]): A list of non-negativ... | 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
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] // exp
output[c... | from solution import radix_sort
def test_radix_sort_empty():
assert radix_sort([]) == []
def test_radix_sort_sorted_elements():
assert radix_sort([1, 2, 3]) == [1, 2, 3]
def test_radix_sort_unsorted_elements():
assert radix_sort([3, 1, 2]) == [1, 2, 3]
def test_radix_sort_with_zeros():
assert radix_... | [
{
"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,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort_for_radix(arr, exp, simulation=False):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # Store count of occurrences in ... | trial_gpt4o_1 | {
"original_instruction": "Radix Sort Implementation\n\n**Scenario**:\nYou work as a software engineer at an e-commerce company that often deals with large datasets, such as a list of transaction amounts that need to be sorted for reporting purposes. To enhance your system's performance, you decide to implement an ef... | 0.651054 | Data_Structure_45998 | C | [
"counting_sort_for_radix",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort_for_radix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | de611848fc4f51dfbfe65c828687d483696ef91d | 64c0f36b77a3d398fac51867332053aba54bf947 | |||
v1.0 | complete | Data_Structure | Data_Structure_45940_C | def calculate_max_flow(capacity: List[List[int]], source: int, sink: int) -> int:
"""Calculates the maximum flow from the source to the sink using Dinic's Algorithm.
Args:
capacity (List[List[int]]): A 2D list representing the maximum capacity of water flow between sectors.
source (int): Th... | from collections import deque
from typing import List, Optional
def bfs(level: List[Optional[int]], capacity: List[List[int]], flow: List[List[int]], source: int, sink: int) -> bool:
"""Performs a BFS to construct level graph."""
queue = deque([source])
level[source] = 0
while queue:
u = queue.... | from solution import calculate_max_flow
def test_calculate_max_flow_basic_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]
]
assert calculate_max_flow(capacity, 0... | [
{
"docstring": "Performs a BFS to construct level graph.",
"function_declaration": "def bfs(level, capacity, flow, source, sink):",
"function_name": "bfs",
"parameter_list": "(level, capacity, flow, source, sink)"
},
{
"docstring": "Sends flow along an augmenting path using DFS.",
"funct... | [
0,
0,
0,
1,
1,
0,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef calculate_max_flow(capacity, source, sink):\n n = len(capacity)\n \n # Residual capacity matrix\n residual_ca... | trial_gpt4o_8 | {
"original_instruction": "### Scenario:\nA city has multiple pipelines that distribute water between different sectors. Each pipeline has a maximum capacity of water flow. We need to determine the maximum possible flow of water from the water plant (source) to the emergency reservoir (sink). You are required to impl... | 0.677126 | Data_Structure_45940 | C | [
"bfs",
"dfs",
"calculate_max_flow"
] | 3 | [
[
"calculate_max_flow",
"bfs"
],
[
"calculate_max_flow",
"dfs"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 43992a25ade9ccfa0203375ace75d3be8ff375f0 | 6a1fbc370a2f8bc0072a193bdea639bb90d6da82 | |||
v1.0 | complete | Data_Structure | Data_Structure_45766_C | def modinv(a: int, m: int) -> int:
""" Compute the modular inverse of a under modulo m using the Extended Euclidean Algorithm.
>>> modinv(3, 11) 4
>>> modinv(10, 17) 12
"""
pass
def is_prime(n: int, k: int = 5) -> bool:
""" Determine if a number is prime using the Miller-Rabin primality test.
... | import random
from typing import Tuple
def modinv(a: int, m: int) -> int:
"""
Compute the modular inverse of a under modulo m using the Extended Euclidean Algorithm.
"""
m0, x0, x1 = m, 0, 1
if m == 1:
return 0
while a > 1:
q = a // m
m, a = a % m, m
x0, x1 ... | from solution import generate_key, encrypt, decrypt, modinv, is_prime
def test_modinv():
assert modinv(3, 11) == 4
def test_is_prime():
assert is_prime(11) == True
assert is_prime(15) == False
def test_generate_key():
n, e, d = generate_key(16)
assert isinstance(n, int)
assert isinstance(e, i... | [
{
"docstring": "Compute the modular inverse of a under modulo m using the Extended Euclidean Algorithm.",
"function_declaration": "def modinv(a, m):",
"function_name": "modinv",
"parameter_list": "(a, m)"
},
{
"docstring": "Determine if a number is prime using the Miller-Rabin primality test... | [
0,
1
] | 1 | medium | 0.5 | {
"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 gcd(a, b):\n while b != 0:\n a, b = b, a % b\n return a\n\ndef modinv(a, m):\n m0, x0, x1 = m, ... | trial_gpt4o_2 | {
"original_instruction": "### RSA Encryption Application\n\n### Problem Statement\n\nYou are tasked with enhancing the performance of an RSA encryption algorithm by implementing an optimized solution for calculating the modular inverse and prime number generation. Using this optimized RSA key generation, encryption,... | 0.583157 | Data_Structure_45766 | C | [
"modinv",
"is_prime",
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt"
] | 7 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_key",
"modinv"
],
[
"generate_prime_number",
"generate_prime_candidate"
],
[
"generate_prime_number",
"is_prime"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | af22433a20e56a4c095ee5194ef552cb2d63553b | 293b4c44955af9b76584798341a0aa46752fe6da | |||
v1.0 | complete | Data_Structure | Data_Structure_45461_C | def optimized_quick_sort(arr: list, simulation: bool=False) -> list:
"""
Implement a function `optimized_quick_sort` that sorts an array of integers using Quick Sort.
To improve against worst-case scenarios, use median-of-three as a pivot selection strategy.
Input:
- `arr`: A list of integers to b... | def median_of_three(arr, low, high):
mid = (low + high) // 2
a, b, c = arr[low], arr[mid], arr[high]
if a > b:
if a < c:
median = low
elif b > c:
median = mid
else:
median = high
else:
if b < c:
median = mid
elif a >... | from solution import optimized_quick_sort
def test_sorted_list():
assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list():
assert optimized_quick_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_identical_elements():
assert optimized_quick_sort([1, 1, 1, 1]) == [1,... | [
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter... | [
1,
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 median_of_three(arr, low, high):\n mid = (low + high) // 2\n a, b, c = arr[low], arr[mid], arr[high]\n if a > b:\n if a < c:\n ... | trial_gpt4o_0 | {
"original_instruction": "### Quick Sort Implementation & Optimization\n\n#### Context\nYou are working on an analytics tool that handles large datasets. Efficiency is crucial given that you sometimes work with millions of records. While Quick Sort is generally efficient, it can degrade to O(n^2) based on pivot choi... | 0.642665 | Data_Structure_45461 | C | [
"median_of_three",
"partition",
"_quick_sort",
"optimized_quick_sort"
] | 4 | [
[
"_quick_sort",
"partition"
],
[
"optimized_quick_sort",
"_quick_sort"
],
[
"partition",
"median_of_three"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | bf9da5dd7888c8cb66a70d97094ab0c60e6e7161 | 5b2a360c0231485c2bf897d42762829cefc2f6d0 | |||
v1.0 | complete | Data_Structure | Data_Structure_45857_C | from typing import List
def find_advanced_words(board: List[List[str]], words: List[str]) -> List[str]:
"""
Given a 2D board of characters and a list of words, returns a list of all words
from the list that are present on the board adhering to constraints.
>>> board = [
>>> ['o','a','a','... | from typing import List
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
self.word = None
def add_word_to_trie(root, word):
node = root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
nod... | from solution import find_advanced_words
def test_example_case():
board = [
['o', 'a', 'a', 'n'],
['e', 't', 'a', 'e'],
['i', 'h', 'k', 'r'],
['i', 'f', 'l', 'v']
]
words = ["oath", "pea", "eat", "rain"]
assert sorted(find_advanced_words(board, words)) == sorted(["oath",... | [] | [
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": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.is_end_of_word = False\n self.word = None # To store the word at en... | trial_gpt4o_1 | {
"original_instruction": "### Word Search with Constraints\n\nGiven a 2D board of characters and a list of words, write a function `find_advanced_words` that returns a list of all words from the list that are present on the board. \n\n#### Special Constraints:\n1. Words must be constructed from letters of sequential... | 0.642315 | Data_Structure_45857 | C | [
"add_word_to_trie",
"find_advanced_words"
] | 2 | [
[
"find_advanced_words",
"add_word_to_trie"
]
] | 1 | [] | false | [
"TrieNode"
] | true | pytest | true | [] | true | 711f92255ffa500252e8ec96a7124e3fa436bae3 | 5e53fd651863e832dae45505f6df63367a5ea782 | |||
v1.0 | complete | Data_Structure | Data_Structure_45844_C | def merge_sort(arr):
""" Merge Sort Algorithm
>>> merge_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
>>> merge_sort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>> merge_sort([])
[]
>>> merge_sort([1])
[1]
>>> merge_sort([1, 1, 1, 1, 1])
[1, 1, 1, 1, 1]
... | def merge_sort(arr):
"""Merge Sort Algorithm"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
"""Merge helper function"""
result = []
left_cursor, right_... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element_list():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_list():
a... | [
{
"docstring": "Merge Sort Algorithm",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merge helper function",
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\" Merge Sort Algorithm \"\"\"\n if len(arr) <= 1:\n return arr\n mid = len(arr) // 2\n left = merge_sort(arr[:m... | trial_gpt4o_2 | {
"original_instruction": "**Context:**\nYou are developing a feature for a software system that processes and sorts large datasets. One of the fundamental requirements is to implement an efficient and reliable sorting mechanism that can handle diverse input sizes and maintain stability in sorting.\n\n**Task:**\nImpl... | 0.646809 | Data_Structure_45844 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 266b76124af52164cf31a7c48b825c42f4d7f11e | 059fd2c8877d3a2ca142324ebb8f85e8d1af1ab0 | |||
v1.0 | complete | Data_Structure | Data_Structure_45484_C | def nearest_neighbor_manhattan(x: tuple, tSet: dict) -> any:
"""
Implement the nearest neighbor classification algorithm using Manhattan distance.
Parameters:
x (tuple): A vector of numerical values representing the point to classify.
tSet (dict): A dictionary where keys are tuples representing... | def manhattan_distance(x, y):
"""
Calculate the Manhattan distance between two vectors x and y.
"""
return sum(abs(a - b) for a, b in zip(x, y))
def nearest_neighbor_manhattan(x: tuple, tSet: dict) -> any:
"""
Find the nearest neighbor of vector x based on Manhattan distance in training set tSe... | from solution import nearest_neighbor_manhattan
def test_nearest_neighbor_single_entry():
tSet = {
(1, 2): 'A'
}
x = (1, 2)
assert nearest_neighbor_manhattan(x, tSet) == 'A'
def test_nearest_neighbor_different_entries():
tSet = {
(1, 2): 'A',
(3, 4): 'B',
(5, 6)... | [
{
"docstring": "Calculate the Manhattan distance between two vectors x and y.",
"function_declaration": "def manhattan_distance(x, y):",
"function_name": "manhattan_distance",
"parameter_list": "(x, y)"
},
{
"docstring": "Find the nearest neighbor of vector x based on Manhattan distance in t... | [
0,
0,
0,
1,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def nearest_neighbor_manhattan(x: tuple, tSet: dict) -> any:\n \"\"\"\n This function finds the classification of the nearest neighbor to the vector x\n... | trial_gpt4o_7 | {
"original_instruction": "### Objective:\nWrite a function implementing the nearest neighbor classification algorithm using Manhattan distance instead of Euclidean distance. \n\n### Function Signature:\n```python\ndef nearest_neighbor_manhattan(x: tuple, tSet: dict) -> any:\n pass\n```\n\n### Input:\n1. `x` (tupl... | 0.6258 | Data_Structure_45484 | C | [
"manhattan_distance",
"nearest_neighbor_manhattan"
] | 2 | [
[
"nearest_neighbor_manhattan",
"manhattan_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c422d937f7c9f81d13a76c9f9eee451840f3e92d | b7366c3ed3fb6e0f5bb41848c193a96a7e8c33c8 | |||
v1.0 | complete | Data_Structure | Data_Structure_46232_C | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
""" Determine whether tree `t` is a subtree of tree `s`.
>>> s = TreeNode(3)
>>> s.left = TreeNode(4)
... | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
if not t:
return True
if not s:
return False
if are_identical(s, t):
return ... | from solution import TreeNode, is_subtree
def test_is_subtree_example1():
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.left.right = TreeNode(2)
t = TreeNode(4)
t.left = TreeNode(1)
t.right = TreeNode(2)
assert is_subtree(s, t) == T... | [] | [
0,
0,
0,
1,
1,
1,
1,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n... | trial_gpt4o_7 | {
"original_instruction": "### Scenario\nYou are given the task of determining whether one binary tree is a subtree of another. A subtree is defined as a node in the main tree along with all of its descendants.\n\n### Problem Statement\nWrite a function `is_subtree(s: TreeNode, t: TreeNode) -> bool` that determines w... | 0.642935 | Data_Structure_46232 | C | [
"is_subtree",
"are_identical"
] | 2 | [
[
"is_subtree",
"are_identical"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | b1cfbc7171ca80b5e78d8fcd2ad8f155ea92efca | a41d8bd8c2509f29c5de19bf9d3bcd8642d8b36b | |||
v1.0 | complete | Data_Structure | Data_Structure_46162_C | from typing import List
def bitonic_sort(arr: List[int], reverse: bool=False) -> List[int]:
"""Implementation of Bitonic Sort Algorithm.
Args:
arr (List[int]): A list of integers where the size is a power of 2.
reverse (bool): A boolean flag that determines the sorting order. If False (default... | from typing import List
def compare_and_swap(arr: List[int], i: int, j: int, ascending: bool):
"""
Compare and swap the elements if they are in the wrong order based on ascending flag.
"""
if (ascending and arr[i] > arr[j]) or (not ascending and arr[i] < arr[j]):
arr[i], arr[j] = arr[j], arr[i]... | import pytest
from solution import bitonic_sort
def test_bitonic_sort_ascending():
assert bitonic_sort([3, 7, 2, 1, 9, 5, 6, 4]) == [1, 2, 3, 4, 5, 6, 7, 9]
def test_bitonic_sort_descending():
assert bitonic_sort([3, 7, 2, 1, 9, 5, 6, 4], reverse=True) == [9, 7, 6, 5, 4, 3, 2, 1]
def test_single_element():
... | [
{
"docstring": "Compare and swap the elements if they are in the wrong order based on ascending flag.",
"function_declaration": "def compare_and_swap(arr, i, j, ascending):",
"function_name": "compare_and_swap",
"parameter_list": "(arr, i, j, ascending)"
},
{
"docstring": "Merge function to ... | [
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 compare_and_swap(arr: List[int], i: int, j: int, direction: bool):\n \"\"\"\n Compares and swaps the elements at indices ... | trial_gpt4o_2 | {
"original_instruction": "Implementation of Bitonic Sort Algorithm\n\n#### Problem Statement\nYou are tasked with implementing the Bitonic Sort algorithm, an efficient parallel sorting algorithm designed for arrays whose sizes are powers of two. Your implementation should handle both ascending and descending order s... | 0.681536 | Data_Structure_46162 | C | [
"compare_and_swap",
"bitonic_merge",
"bitonic_sort_recursive",
"bitonic_sort"
] | 4 | [
[
"bitonic_merge",
"compare_and_swap"
],
[
"bitonic_sort",
"bitonic_sort_recursive"
],
[
"bitonic_sort_recursive",
"bitonic_merge"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | b68e43d12f419e0b43523fc45864ede7319bb274 | fb27fa757834727e0736ee0d06393f1e1929b6d9 | |||
v1.0 | complete | Data_Structure | Data_Structure_45589_C | def custom_heap_sort(arr: [int], use_max_heap: bool, simulation: bool=False) -> [int]:
""" Sorts an array of integers in ascending order using either a max-heap or min-heap, based on a flag. This function efficiently performs heap sort and displays the array at each main step for educational and debugging purposes.... | def heapify(arr, n, i, use_max_heap):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if use_max_heap:
# Max-Heapify
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
else:
# M... | from solution import custom_heap_sort
def test_heap_sort_max_heap():
arr = [3, 2, 5, 1, 7, 8]
assert custom_heap_sort(arr, True) == [1, 2, 3, 5, 7, 8]
def test_heap_sort_min_heap():
arr = [3, 2, 5, 1, 7, 8]
assert custom_heap_sort(arr, False) == [1, 2, 3, 5, 7, 8]
def test_heap_sort_single_element():... | [
{
"docstring": null,
"function_declaration": "def heapify(arr, n, i, use_max_heap):",
"function_name": "heapify",
"parameter_list": "(arr, n, i, use_max_heap)"
},
{
"docstring": null,
"function_declaration": "def build_heap(arr, n, use_max_heap, simulation):",
"function_name": "build... | [
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": "def custom_heap_sort(arr, use_max_heap, simulation=False):\n n = len(arr)\n \n def heapify(arr, n, i):\n if use_max_heap:\n largest... | trial_gpt4o_6 | {
"original_instruction": "### Question\nCreate a function named `custom_heap_sort` that sorts an array of integers in ascending order using either a max-heap or min-heap, based on a flag. This function should efficiently perform heap sort and display the array at each main step for educational and debugging purposes... | 0.632436 | Data_Structure_45589 | C | [
"heapify",
"build_heap",
"custom_heap_sort"
] | 3 | [
[
"build_heap",
"heapify"
],
[
"custom_heap_sort",
"build_heap"
],
[
"custom_heap_sort",
"heapify"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 8217d290a985528312d50e91650ad22112d1a54b | 7413fa24d2e333405ea65da7f59678de5a9e4355 | |||
v1.0 | complete | Data_Structure | Data_Structure_45612_C | def heap_sort(arr, use_max_heap=True):
"""
Heap sort function that sorts an array using max-heap or min-heap.
Args:
arr (List[int]): The list of integers to be sorted.
use_max_heap (bool): If True, use max-heap sort. If False, use min-heap sort.
Returns:
List[int]: Sorted list of integers.... | def heapify(arr, n, i, use_max_heap):
"""
To heapify a subtree rooted with node i which is an index in arr[]. n is size of heap
"""
if use_max_heap:
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left c... | from solution import heap_sort
def test_heap_sort_empty():
assert heap_sort([], True) == []
assert heap_sort([], False) == []
def test_heap_sort_single_element():
assert heap_sort([1], True) == [1]
assert heap_sort([1], False) == [1]
def test_heap_sort_multiple_elements_max_heap():
assert heap_so... | [
{
"docstring": "To heapify a subtree rooted with node i which is an index in arr[]. n is size of heap",
"function_declaration": "def heapify(arr, n, i, use_max_heap):",
"function_name": "heapify",
"parameter_list": "(arr, n, i, use_max_heap)"
},
{
"docstring": "Heap sort function that sorts ... | [
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 heap_sort(arr, use_max_heap=True):\n def heapify(arr, n, i, compare):\n largest = i\n l = 2 * i + 1\n r = 2 * i + 2\n \n ... | trial_gpt4o_2 | {
"original_instruction": "### Heap Sort Challenge\n\nHeap Sort is a comparison-based sorting algorithm that leverages the properties of a binary heap (a complete binary tree where each node is greater than its children in a max heap, or smaller than its children in a min heap). \n\nYour task is to implement the `hea... | 0.613182 | Data_Structure_45612 | C | [
"heapify",
"heap_sort"
] | 2 | [
[
"heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 42b0f24430e97e93025dcc9c06e949330985051e | ea65242d73472d3f582398377f14642d04328329 | |||
v1.0 | complete | Data_Structure | Data_Structure_46427_C | def merge_sort(arr):
"""
Sorts an array using the Merge Sort algorithm.
Parameters:
arr (list): A list of elements to be sorted.
Returns:
list: A new sorted list containing the elements from arr in ascending order.
"""
def merge(left, right):
"""
Merges two sorted arrays i... | def merge_sort(arr):
"""
Sorts an array using the Merge Sort algorithm.
Parameters:
arr (list): A list of elements to be sorted.
Returns:
list: A new sorted list containing the elements from arr in ascending order.
"""
if len(arr) <= 1:
return arr
mid = len(arr... | from solution import merge_sort, merge
def test_merge_sort_basic():
arr = [38, 27, 43, 3, 9, 82, 10]
assert merge_sort(arr) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_single_element():
arr = [1]
assert merge_sort(arr) == [1]
def test_merge_sort_sorted():
arr = [1, 2, 3, 4, 5]
assert me... | [
{
"docstring": "Sorts an array using the Merge Sort algorithm.\n\nParameters:\narr (list): A list of elements to be sorted.\n\nReturns:\nlist: A new sorted list containing the elements from arr in ascending order.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"para... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array using the Merge Sort algorithm.\n \n Parameters:\n arr (list): A list of elements to be sorted.\... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Strategy and Implementation\n\nMerge Sort is a well-known sorting algorithm that follows the Divide and Conquer strategy. In this task, you are required to implement this sorting algorithm. The algorithm involves three core steps:\n1. **Divide**: Recursively split the array i... | 0.642989 | Data_Structure_46427 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1fdb701b6bd5431eb96c76720f3e61934ecca509 | eaec0332e6c0dad1765f5b05109612a29c943df9 | |||
v1.0 | complete | Data_Structure | Data_Structure_46151_C | from typing import List, Union
def shell_sort_with_mixed_types(arr: List[Union[int, str]]) -> List[Union[int, str]]:
"""
Sorts an array containing mixed types (integers and strings) such that
integers come first in ascending order, followed by strings in lexicographical order.
"""
def test_shell... | from typing import List, Union
def shell_sort_with_mixed_types(arr: List[Union[int, str]]) -> List[Union[int, str]]:
"""
Sorts an array containing mixed types (integers and strings) such that
integers come first in ascending order, followed by strings in lexicographical order.
"""
n = len(arr)
... | def test_shell_sort_with_mixed_types():
assert shell_sort_with_mixed_types([3, "banana", 1, "apple", 5, "cherry"]) == [1, 3, 5, "apple", "banana", "cherry"]
assert shell_sort_with_mixed_types([7, 2, 3, "a", "z", "m"]) == [2, 3, 7, "a", "m", "z"]
assert shell_sort_with_mixed_types([10, "apple", -1, "banana",... | [
{
"docstring": "Sorts an array containing mixed types (integers and strings) such that \nintegers come first in ascending order, followed by strings in lexicographical order.",
"function_declaration": "def shell_sort_with_mixed_types(arr):",
"function_name": "shell_sort_with_mixed_types",
"parameter... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Union\n\ndef shell_sort_with_mixed_types(arr: List[Union[int, str]]) -> List[Union[int, str]]:\n n = len(arr)\n gap = n // 2\n ... | trial_gpt4o_2 | {
"original_instruction": "### Shell Sort Implementation and Adaptation\n\n**Context**: You have to implement the Shell Sort algorithm, but with a twist: you need to sort an array where multiple element types are present (integers, strings).\n\n**Task**: Write a function `shell_sort_with_mixed_types(arr: List[Union[i... | 0.630468 | Data_Structure_46151 | C | [
"shell_sort_with_mixed_types",
"compare"
] | 2 | [
[
"shell_sort_with_mixed_types",
"compare"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 2c2f0d91ccf8411b9ddcc11fde53aa653a44a5d5 | 301040c63503cbd6865b1d84921b7140e35acc39 | |||
v1.0 | complete | Data_Structure | Data_Structure_46241_C | from typing import List
def palindromic_partitions(s: str) -> List[List[str]]:
"""
Find all possible ways to partition the input string into non-empty palindromic substrings.
>>> palindromic_partitions("aab")
[['a', 'a', 'b'], ['aa', 'b']]
>>> palindromic_partitions("abcbab")
[['a', ... | from typing import List
def is_palindrome(s: str) -> bool:
"""
Helper function to check if the input string is a palindrome.
"""
return s == s[::-1]
def palindromic_partitions(s: str) -> List[List[str]]:
"""
Function to find all palindromic partitions of the input string.
"""
def backt... | from solution import palindromic_partitions
def test_single_character():
assert palindromic_partitions("a") == [["a"]]
def test_empty_string():
assert palindromic_partitions("") == [[]]
def test_no_palindromic_substring():
assert palindromic_partitions("abc") == [["a", "b", "c"]]
def test_multiple_parti... | [
{
"docstring": "Helper function to check if the input string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Function to find all palindromic partitions of the input string.",
"function_decla... | [
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 palindromic_partitions(s: str):\n \"\"\"\n Returns all possible ways to partition input string into palindromic substrings.\n \"\"\"\n def is_... | trial_gpt4o_1 | {
"original_instruction": "### Palindromic Partition Finder\n\n#### Context\nYou are a software developer responsible for implementing a feature in a text processing application aimed at revealing all possible ways to partition input text into palindromic substrings. A palindrome is a string that reads the same forwa... | 0.695722 | Data_Structure_46241 | C | [
"is_palindrome",
"palindromic_partitions"
] | 2 | [
[
"palindromic_partitions",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cd20b6ba29267fb26a38fa13983150fdfd315919 | 2a427d21c7ab39494f6a90c76a81997ab492d2a6 | |||
v1.0 | complete | Data_Structure | Data_Structure_46333_C | def gnome_sort(arr):
"""
Sorts an array using the Gnome sort algorithm.
Parameters:
arr (list): The list of integers to sort.
Returns:
list: The sorted list in ascending order.
"""
# Your implementation here
import random
import timeit
import matplotlib.pyplot as plt
def analyze_gnom... | def gnome_sort(arr):
"""
Sorts an array using the Gnome sort algorithm.
Parameters:
arr (list): The list of integers to sort.
Returns:
list: The sorted list in ascending order.
"""
n = len(arr)
index = 0
while index < n:
if index == 0 or arr[index] >= arr[index ... | from solution import gnome_sort
def test_gnome_sort_empty():
assert gnome_sort([]) == []
def test_gnome_sort_single_element():
assert gnome_sort([1]) == [1]
def test_gnome_sort_sorted():
assert gnome_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_gnome_sort_reverse():
assert gnome_sort([5, 4, 3, ... | [
{
"docstring": "Sorts an array using the Gnome sort algorithm.\n\nParameters:\narr (list): The list of integers to sort.\n\nReturns:\nlist: The sorted list in ascending order.",
"function_declaration": "def gnome_sort(arr):",
"function_name": "gnome_sort",
"parameter_list": "(arr)"
},
{
"doc... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gnome_sort(arr):\n \"\"\"\n Sorts the input list using Gnome Sort algorithm in ascending order.\n \"\"\"\n n = len(arr)\n index = 0\n wh... | trial_gpt4o_1 | {
"original_instruction": "### Gnome Sort Implementation and Analysis Challenge\n\nYou are provided with a simple sorting algorithm known as Gnome Sort. To test your understanding of sorting algorithms and their practical application, you are required to implement a function based on the provided code snippet and ana... | 0.608749 | Data_Structure_46333 | C | [
"gnome_sort",
"analyze_gnome_sort_performance"
] | 2 | [
[
"analyze_gnome_sort_performance",
"gnome_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib"
] | false | f119d12c16510c3e57148b73b7dcffdd3ac70cc6 | dd3853c3b0a4a4bf8961a0db435b1ca229729c4c | |||
v1.0 | complete | Data_Structure | Data_Structure_46292_C | import random
from typing import Dict, List
def simulate_markov_chain(chain: Dict[str, Dict[str, float]], initial_state: str, steps: int) -> List[str]:
""" Simulates the Markov chain from an initial state for a specified number of steps
and returns the sequence of visited states.
>>> simulate_markov_chain... | import random
def simulate_markov_chain(chain, initial_state, steps):
state = initial_state
sequence = [state]
for _ in range(steps):
next_state = random.choices(list(chain[state].keys()), list(chain[state].values()))[0]
sequence.append(next_state)
state = next_state
r... | from solution import simulate_markov_chain, state_visits
def test_simulate_markov_chain_single_step():
chain = {'A': {'A': 1.0}}
result = simulate_markov_chain(chain, 'A', 1)
assert result == ['A', 'A']
def test_simulate_markov_chain_multiple_steps():
chain = {'A': {'A': 0.5, 'B': 0.5}, 'B': {'A': 1.0... | [
{
"docstring": null,
"function_declaration": "def simulate_markov_chain(chain, initial_state, steps):",
"function_name": "simulate_markov_chain",
"parameter_list": "(chain, initial_state, steps)"
},
{
"docstring": null,
"function_declaration": "def state_visits(chain, initial_state, step... | [
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 simulate_markov_chain(chain, initial_state, steps):\n \"\"\"\n Simulate the Markov chain for a specified number of steps starting f... | trial_gpt4o_2 | {
"original_instruction": "### Question: Markov Chain Simulation and Analysis\n\n#### Scenario\nGiven a Markov chain described by a dictionary, you are tasked with simulating the Markov chain from an initial state and analyzing certain properties of the resulting sequence.\n\n#### Task\n1. Implement a function `simul... | 0.56653 | Data_Structure_46292 | C | [
"simulate_markov_chain",
"state_visits"
] | 2 | [
[
"state_visits",
"simulate_markov_chain"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c72a8620232c7b4c2e20fb0ecd80a12c50d431c2 | ec907b45cce7670cb66ff458900f358438c49f39 | |||
v1.0 | complete | Data_Structure | Data_Structure_46154_C | def bfs(residual_graph, source, sink, parent):
"""
Returns True if there is a path from source to sink in residual graph.
"""
pass
def maximum_flow_bfs(adjacency_matrix: List[List[int]]) -> int:
"""You are given a directed graph where each node represents a point in the network and each edge has a ... | from collections import deque
def bfs(residual_graph, source, sink, parent):
"""
Returns True if there is a path from source to sink in residual graph.
"""
visited = [False] * len(residual_graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft... | from solution import maximum_flow_bfs
def test_example_case():
graph = [[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]]
assert maximum_flow_bfs(graph) == 23
def test_s... | [
{
"docstring": "Returns True if there is a path from source to sink in residual graph.",
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": "Returns the maximum flow fr... | [
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 bfs(residual_graph, source, sink, parent):\n visited = [False] * len(residual_graph)\n queue = deque([source])\n ... | trial_gpt4o_1 | {
"original_instruction": "You are given a directed graph where each node represents a point in the network and each edge has a capacity, representing how much can flow through that edge. Implement an optimized version of the maximum flow problem using the BFS search strategy to ensure better path selection.\n\n### I... | 0.556535 | Data_Structure_46154 | C | [
"bfs",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 06e65280ba75f2726fcb6d93d5daa9beb9baeac1 | 539d2206765315fde5b4ac21f329068e7ce8d8a5 | |||
v1.0 | complete | Data_Structure | Data_Structure_46259_C | def diffie_hellman_key_exchange_enhanced(a: int, p: int) -> bool:
""" Implement the Diffie-Hellman key exchange enhanced version.
This function should:
- Validate the prime number `p`.
- Validate `a` as a primitive root of `p`.
- Execute the key exchange ensuring all checks pass correctly.
... | 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 gcd(a, b):
while b:
a, b = b, ... | from solution import diffie_hellman_key_exchange_enhanced
def test_diffie_hellman_valid_case():
assert diffie_hellman_key_exchange_enhanced(5, 23) == True
def test_diffie_hellman_invalid_prime():
assert diffie_hellman_key_exchange_enhanced(5, 21) == False
def test_diffie_hellman_invalid_primitive_root():
... | [
{
"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,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5... | trial_gpt4o_2 | {
"original_instruction": "### Diffie-Hellman Key Exchange Enhanced\nThe following outlines a scenario where improvements are needed in the Diffie-Hellman key exchange algorithm implementation.\n\n**Scenario:** \nTwo entities, Alice and Bob, wish to securely establish a shared secret key through an insecure network. ... | 0.474438 | Data_Structure_46259 | C | [
"is_prime",
"gcd",
"is_primitive_root",
"diffie_hellman_key_exchange_enhanced"
] | 4 | [
[
"diffie_hellman_key_exchange_enhanced",
"is_prime"
],
[
"diffie_hellman_key_exchange_enhanced",
"is_primitive_root"
],
[
"is_primitive_root",
"gcd"
],
[
"is_primitive_root",
"is_prime"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 66a7776bcf98eab3161969baaba7c63cbeda5014 | 4ac2c2bf848e78d04d68810cb7a2764f1f2f4171 | |||
v1.0 | complete | Data_Structure | Data_Structure_46264_C | from typing import List
def adaptive_search(array: List[int], search_key: int) -> int:
""" Combine Interpolation Search and Binary Search based on the distribution of the dataset.
>>> adaptive_search([-25, -12, -1, 10, 12, 15, 20, 41, 55], -1) == 2
>>> adaptive_search([5, 10, 12, 14, 17, 20, 21], 55) ... | from typing import List
def interpolation_search(array: List[int], search_key: int) -> int:
low = 0
high = len(array) - 1
while low <= high and search_key >= array[low] and search_key <= array[high]:
if low == high:
if array[low] == search_key:
return low
... | def test_adaptive_search():
assert adaptive_search([-25, -12, -1, 10, 12, 15, 20, 41, 55], -1) == 2
assert adaptive_search([5, 10, 12, 14, 17, 20, 21], 55) == -1
assert adaptive_search([5, 10, 12, 14, 17, 20, 21], -5) == -1
assert adaptive_search([], 12) == -1
assert adaptive_search([10], 10) == 0
... | [
{
"docstring": null,
"function_declaration": "def interpolation_search(array, search_key):",
"function_name": "interpolation_search",
"parameter_list": "(array, search_key)"
},
{
"docstring": null,
"function_declaration": "def binary_search(array, search_key):",
"function_name": "bin... | [
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 binary_search(array: List[int], search_key: int) -> int:\n left, right = 0, len(array) - 1\n \n while left <= right:\n... | trial_gpt4o_2 | {
"original_instruction": "#### Context\nIn the world of search algorithms, efficiency is crucial, especially when dealing with large datasets. Interpolation Search, often optimized for uniformly distributed arrays, can outperform traditional search algorithms under specific conditions.\n\nFor this assessment, you wi... | 0.568902 | Data_Structure_46264 | C | [
"interpolation_search",
"binary_search",
"is_uniform",
"adaptive_search"
] | 4 | [
[
"adaptive_search",
"binary_search"
],
[
"adaptive_search",
"interpolation_search"
],
[
"adaptive_search",
"is_uniform"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 5d633f9a891923c45c81bb489a47138a66a801ca | d0e76e48120868f128975ac4ce2adcb3384b3aac | |||
v1.0 | complete | Data_Structure | Data_Structure_45374_C | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def deserialize(data: str) -> TreeNode:
"""
Decodes your encoded data to tree.
"""
if not data:
return None
nodes = iter(data.split())
root = TreeNode(next(nodes))
queu... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def deserialize(data: str) -> TreeNode:
"""
Decodes your encoded data to tree.
"""
if not data:
return None
nodes = iter(data.split())
root = TreeNode(next(nodes))
queu... | from solution import are_trees_identical
def test_identical_trees():
serialized_tree1 = "1 2 # # 3 # #"
serialized_tree2 = "1 2 # # 3 # #"
assert are_trees_identical(serialized_tree1, serialized_tree2) == True
def test_different_tree_structure():
serialized_tree1 = "1 2 # # 3 # #"
serialized_tree2... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef deserialize(data):\n if not d... | trial_gpt4o_1 | {
"original_instruction": "#### Objective\nImplement a function that determines if two binary trees are structurally identical. Two binary trees are structurally identical if they have the same structure and nodes have the same values.\n\n#### Input/Output\n- **Input**: Two serialized strings representing two binary ... | 0.517177 | Data_Structure_45374 | C | [
"deserialize",
"are_trees_identical"
] | 2 | [
[
"are_trees_identical",
"deserialize"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 8be727d23ed3592f214467532c96a4f9ae777e5b | b3cf650e0c1115a57e96336ae21fea38db52db92 | |||
v1.0 | complete | Data_Structure | Data_Structure_46067_C | from typing import List
def optimized_merge_sort(arr: List[int], k: int) -> List[int]:
"""
Implement the merge sort algorithm with optimizations for large arrays
and insertion sort for small subarrays.
Args:
arr: A list of integers to be sorted.
k: An integer threshold for switch... | from typing import List
def insertion_sort(arr: List[int], left: int, right: int) -> None:
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def merge(arr: List[int], lef... | def test_single_element():
arr = [1]
k = 10
assert optimized_merge_sort(arr, k) == [1]
def test_empty_array():
arr = []
k = 10
assert optimized_merge_sort(arr, k) == []
def test_already_sorted():
arr = [1, 2, 3, 4, 5]
k = 10
assert optimized_merge_sort(arr, k) == [1, 2, 3, 4, 5]
d... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def merge(arr, left, mid, right):",
"function_name": "merge",
"paramete... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[int], left: int, right: int) -> None:\n for i in range(left + 1, right + 1):\n key = arr[i]\... | trial_gpt4o_0 | {
"original_instruction": "### Question\nYou are tasked with implementing a merge sort algorithm, but with certain optimizations and special requirements. This will test your understanding of the algorithm’s nuances and your ability to make improvements.\n\n#### Requirements:\n1. Implement the merge sort algorithm in... | 0.612684 | Data_Structure_46067 | C | [
"insertion_sort",
"merge",
"optimized_merge_sort_helper",
"optimized_merge_sort"
] | 4 | [
[
"optimized_merge_sort",
"optimized_merge_sort_helper"
],
[
"optimized_merge_sort_helper",
"insertion_sort"
],
[
"optimized_merge_sort_helper",
"merge"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 6689c8d3d183207fadaa95c5a9dd685b61abdfea | e65732799bbe32a3478f53a6db02d7b104b7f607 | |||
v1.0 | complete | Data_Structure | Data_Structure_46428_C | class TreeNode:
def __init__(self, val: int = 0, left: 'TreeNode' = None, right: 'TreeNode' = None):
self.val = val
self.left = left
self.right = right
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
""" Determine if tree `t` is a subtree of tree `s`.
>>> is_subtree(TreeNode(3, Tr... | class TreeNode:
def __init__(self, val: int = 0, left: 'TreeNode' = None, right: 'TreeNode' = None):
self.val = val
self.left = left
self.right = right
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
if not s:
return False
if is_same_tree(s, t):
return True
ret... | from solution import TreeNode, is_subtree, is_same_tree
def test_is_subtree_example1():
s = TreeNode(3, TreeNode(4, TreeNode(1), TreeNode(2)), TreeNode(5))
t = TreeNode(4, TreeNode(1), TreeNode(2))
assert is_subtree(s, t) == True
def test_is_subtree_example2():
s = TreeNode(3, TreeNode(4, TreeNode(1),... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_2 | {
"original_instruction": "Subtree Validation\n\n**Context**: \nYou are working on ensuring the structural integrity of hierarchical data in a large database system. Your specific task is to write a function to determine if a given tree `t` is a subtree of another tree `s`.\n\n**Problem Statement**: \nWrite a functio... | 0.529055 | Data_Structure_46428 | C | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 153041c63b90f7f9d48f4f642ac3ddc316403604 | eb050958f642d7b31ab2e0a7b061667b43cd3d3f | |||
v1.0 | complete | Data_Structure | Data_Structure_46646_C | from typing import List
def insertion_sort_optimized(array: List[int]) -> List[int]:
"""
Sorts an array of integers using the Insertion Sort algorithm with binary search optimization for inserting elements.
>>> insertion_sort_optimized([12, 11, 13, 5, 6])
[5, 6, 11, 12, 13]
>>> insertion_... | from typing import List
def search_insert(arr: List[int], val: int, start: int, end: int) -> int:
"""
Returns the index at which val should be inserted into arr to maintain sorted order.
This function performs binary search in the subarray arr[start:end].
"""
while start < end:
mid = (start... | from solution import insertion_sort_optimized
def test_already_sorted():
assert insertion_sort_optimized([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted():
assert insertion_sort_optimized([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_mixed_values():
assert insertion_sort_optimized([12, 11, 13,... | [
{
"docstring": "Returns the index at which val should be inserted into arr to maintain sorted order.\nThis function performs binary search in the subarray arr[start:end].",
"function_declaration": "def search_insert(arr, val, start, end):",
"function_name": "search_insert",
"parameter_list": "(arr, ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Helper function to find the index where ... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort Implementation with Optimization\n\n#### Objective\nYou are tasked with implementing a function that sorts an array using the Insertion Sort algorithm. To optimize the insertion process, you should use binary search to determine the appropriate position to insert each ele... | 0.645753 | Data_Structure_46646 | C | [
"search_insert",
"insertion_sort_optimized"
] | 2 | [
[
"insertion_sort_optimized",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c5c29f6cd9072e05c4ff5a9f53b46b88fc9745dc | 06ae4fc960ae32855426f72ab59953393ba8d5fc | |||
v1.0 | complete | Data_Structure | Data_Structure_46506_C | def search_insert(array, value, end):
"""
This function helps to find the position where the value should be inserted
in the array[0:end] to maintain the sorted order.
"""
for i in range(end):
if array[i] > value:
return i
return end
def insertion_sort(array):
""" Sorts ... | def search_insert(array, value, end):
"""
This function helps to find the position where the value should be inserted
in the array[0:end] to maintain the sorted order.
"""
for i in range(end):
if array[i] > value:
return i
return end
def insertion_sort(array):
"""
So... | from solution import insertion_sort
def test_insertion_sort_with_positive_numbers():
assert insertion_sort([4, 3, 2, 1]) == [1, 2, 3, 4]
assert insertion_sort([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13]
def test_insertion_sort_with_mixed_numbers():
assert insertion_sort([1, 3, 2, 5, 6, 4]) == [1, 2, 3, 4, 5... | [
{
"docstring": "This function helps to find the position where the value should be inserted\nin the array[0:end] to maintain the sorted order.",
"function_declaration": "def search_insert(array, value, end):",
"function_name": "search_insert",
"parameter_list": "(array, value, end)"
},
{
"do... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insertion_sort(array):\n def search_insert(sub_array, value):\n for i in range(len(sub_array)):\n if sub_array[i] > value:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort Helper Function Implementation\n\n#### Objective:\nDesign a function that uses the given `search_insert` helper method to implement the Insertion Sort algorithm.\n\n#### Description:\nWrite a Python function `insertion_sort(array)` that takes an array of integers and sort... | 0.671153 | Data_Structure_46506 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 58ce820b0232315a4b398104cb266c5be7f94de6 | db0609755f2f99722911b40030da174bd7834775 | |||
v1.0 | complete | Data_Structure | Data_Structure_46218_C | def stoogesort(arr, l, h):
"""Sorts an array using the Stooge Sort algorithm.
Args:
arr (List[int]): The array of integers to be sorted.
l (int): The starting index of the subarray to be sorted.
h (int): The ending index of the subarray to be sorted.
Returns:
None: ... | def stoogesort(arr, l, h):
if l >= h:
return
# If first element is greater than last, swap them
if arr[l] > arr[h]:
arr[l], arr[h] = arr[h], arr[l]
# If there are more than 2 elements in the array
if h - l + 1 > 2:
t = (h - l + 1) // 3
# Recursively sort first 2/3 ... | from solution import sort_patient_ids
def test_sort_empty_list():
assert sort_patient_ids([]) == []
def test_sort_single_element():
assert sort_patient_ids([1]) == [1]
def test_sort_sorted_list():
assert sort_patient_ids([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_sort_reverse_list():
assert sort_p... | [
{
"docstring": null,
"function_declaration": "def stoogesort(arr, l, h):",
"function_name": "stoogesort",
"parameter_list": "(arr, l, h)"
},
{
"docstring": null,
"function_declaration": "def sort_patient_ids(patient_ids):",
"function_name": "sort_patient_ids",
"parameter_list": "... | [
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 stoogesort(arr, l, h):\n \"\"\"\n Recursive function to perform Stooge Sort on a subarray from index l to h.\n \"\"\"\n if l >= h:\n re... | trial_gpt4o_2 | {
"original_instruction": "### Stooge Sort Implementation and Analysis\n\n**Scenario**:\nYou have been presented with a list of patient IDs that need to be sorted chronologically based on their timestamps of record creation. The list of IDs might contain duplicates, and the sorting needs to maintain the sequence of i... | 0.564712 | Data_Structure_46218 | C | [
"stoogesort",
"sort_patient_ids"
] | 2 | [
[
"sort_patient_ids",
"stoogesort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 83aea36ef4fdde681bdcc60a8f59c1fb1fdb3e5a | 976fdb66b6786cb5d35b9b8f3c54dec413f19ac1 | |||
v1.0 | complete | Data_Structure | Data_Structure_46534_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Implements Merge Sort algorithm to sort an array of integers in non-decreasing order.
:param arr: A list of integers to be sorted.
:return: A list of integers sorted in non-decreasing order.
""" | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers using Merge Sort algorithm.
- The function is stable and maintains O(n log n) time complexity.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
... | from solution import merge_sort
def test_merge_sort_example1():
arr = [4, 2, 5, 1, 6, 3]
assert merge_sort(arr) == [1, 2, 3, 4, 5, 6]
def test_merge_sort_example2():
arr = []
assert merge_sort(arr) == []
def test_merge_sort_example3():
arr = [7, -3, 4, -1, 6, -5]
assert merge_sort(arr) == [-5... | [
{
"docstring": "Sorts an array of integers using Merge Sort algorithm.\n- The function is stable and maintains O(n log n) time complexity.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists int... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n # Divide step\n mid = len(arr) //... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Assessment Question\n\n**Objective**:\nYou are tasked with implementing a sorting algorithm called Merge Sort. This algorithm should take an array of integers as input and return the array sorted in non-decreasing order. \n\n**Input Format**:\nA single list of integers `arr` ... | 0.673553 | Data_Structure_46534 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2fdc488a0ebe42f45d25141f87736b0d6b27341f | f83f0a0fff5a80f2081ab7d94c7f460bd80a066e | |||
v1.0 | complete | Data_Structure | Data_Structure_46273_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(s: Optional[TreeNode], t: Optional[TreeNode]) -> bool:
""" Implement a function to check whether tree `t` is a subtree of tree `s`.
Args:
s (O... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
if not s:
return not t
if is_identical(s, t):
return True
return is_subtree(s.left, t) or is_sub... | from solution import TreeNode, is_subtree
def test_subtree_present():
# Tree s
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.left.right = TreeNode(2)
# Tree t
t = TreeNode(4)
t.left = TreeNode(1)
t.right = TreeNode(2)
assert... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_2 | {
"original_instruction": "### Tree Subtree Check Problem\n\n**Objective**: Implement a function to check whether tree `t` is a subtree of tree `s`.\n\n**Function Signature**:\n```python\ndef is_subtree(s: Optional[TreeNode], t: Optional[TreeNode]) -> bool:\n```\n\n**Input**:\n- `s`: The root node of a binary tree.\n... | 0.626122 | Data_Structure_46273 | C | [
"is_subtree",
"is_identical"
] | 2 | [
[
"is_subtree",
"is_identical"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 48dcf8f3748301765f8ff56976303388ea461747 | 9feb1a0fec020e9da1f9df2b52ef0e98fce4d126 | |||
v1.0 | complete | Data_Structure | Data_Structure_46412_C | import random
def bogo_sort(arr, simulation=False):
"""
Perform Bogo Sort on an array with optional simulation to print intermediate steps.
Parameters:
arr (list): List of elements to sort.
simulation (bool): If true, print intermediate array states after each shuffle.
Returns:
list: Sort... | import random
def bogo_sort(arr, simulation=False):
"""
Perform Bogo Sort on an array with optional simulation to print intermediate steps.
Parameters:
arr (list): List of elements to sort.
simulation (bool): If true, print intermediate array states after each shuffle.
Returns:
list: ... | from solution import bogo_sort, compare_sorts
def test_bogo_sort_empty_array():
assert bogo_sort([]) == []
def test_bogo_sort_single_element():
assert bogo_sort([1]) == [1]
def test_bogo_sort_sorted_array():
assert bogo_sort([1, 2, 3]) == [1, 2, 3]
def test_bogo_sort_unsorted_array():
assert bogo_so... | [
{
"docstring": "Perform Bogo Sort on an array with optional simulation to print intermediate steps.\n\nParameters:\narr (list): List of elements to sort.\nsimulation (bool): If true, print intermediate array states after each shuffle.\n\nReturns:\nlist: Sorted list of elements.",
"function_declaration": "de... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef bogo_sort(arr, simulation=False):\n \"\"\"\n Perform Bogo Sort on an array with optional simulation to print intermediate steps.\n ... | trial_gpt4o_0 | {
"original_instruction": "### Bogo Sort: Implementation and Performance Testing\n\nAs a crossover between coding challenge and learning exercise, this question will test your understanding of randomized algorithms and their analysis. You are provided with an extremely inefficient sorting algorithm known as **Bogo So... | 0.539018 | Data_Structure_46412 | C | [
"bogo_sort",
"compare_sorts"
] | 2 | [
[
"compare_sorts",
"bogo_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dd5094e35a96ba761e2bce961e2244141538efa2 | e963d6af07dd853b69167e23f38b03f2af62caae | |||
v1.0 | complete | Data_Structure | Data_Structure_46450_C | from typing import List
def heapify(arr: List[int], n: int, i: int):
"""
Maintains the heap property of a max-heap.
:param arr: List[int] - The array representation of the heap.
:param n: int - The size of the heap.
:param i: int - The index of the element to heapify.
"""
pass
def uni... | from typing import List
def heapify(arr: List[int], n: int, i: int):
'''
To maintain the heap property of a max-heap
'''
largest = i # Initialize largest as root
left = 2 * i + 1 # left = 2*i + 1
right = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is greater than ... | from solution import unique_file_sort
def test_unique_file_sort_example_1():
input = [9, 4, 7, 1, -2, 6, 5]
output = [9, 7, 6, 5, 4, 1, -2]
assert unique_file_sort(input) == output
def test_unique_file_sort_example_2_empty():
input = []
output = []
assert unique_file_sort(input) == output
def... | [
{
"docstring": "To maintain the heap property of a max-heap",
"function_declaration": "def heapify(arr, n, i):",
"function_name": "heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Performs heap sort to sort the array in descending order",
"function_declaration": "def unique_f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef heapify(arr: List[int], n: int, i: int):\n \"\"\"\n Function to maintain the max-heap property for a push down operation.... | trial_gpt4o_2 | {
"original_instruction": "**Unique File Sort**\n\n**Scenario**:\nYou are part of a software development team that handles the storage of numerous files with varying sizes. Your task is to create an efficient sorting algorithm to sort these files by their sizes. Instead of simple sorting, you will use heap sort.\n\n*... | 0.585633 | Data_Structure_46450 | C | [
"heapify",
"unique_file_sort"
] | 2 | [
[
"unique_file_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d10a11aa514ae00441191744825da206daf2087e | ad56fb9a91ca62dd241040d12bd976aa30f7edc4 | |||
v1.0 | complete | Data_Structure | Data_Structure_45981_C | def multiply_matrices(multiplicand, multiplier):
"""
Multiplies two given matrices using Strassen's algorithm if they are conformable
and returns their product. If the matrices are not conformable, it returns None.
Args:
multiplicand: Two-dimensional list of integers representing the first matr... | def add_matrix(A, B):
"""
Adds two matrices element-wise.
"""
n = len(A)
result = [[A[i][j] + B[i][j] for j in range(n)] for i in range(n)]
return result
def subtract_matrix(A, B):
"""
Subtracts matrix B from matrix A element-wise.
"""
n = len(A)
result = [[A[i][j] - B[i][j]... | from solution import multiply_matrices
def test_multiply_matrices_basic_case():
multiplicand = [
[1, 2],
[3, 4]
]
multiplier = [
[2, 0],
[1, 2]
]
expected = [
[4, 4],
[10, 8]
]
assert multiply_matrices(multiplicand, multiplier) == expected
de... | [
{
"docstring": "Adds two matrices element-wise.",
"function_declaration": "def add_matrix(A, B):",
"function_name": "add_matrix",
"parameter_list": "(A, B)"
},
{
"docstring": "Subtracts matrix B from matrix A element-wise.",
"function_declaration": "def subtract_matrix(A, B):",
"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": "def add_matrix(A, B):\n \"\"\"\n Adds two matrices A and B.\n \"\"\"\n n = len(A)\n C = [[0] * n for _ in range(n)]\n for i in range(n):\n ... | trial_gpt4o_1 | {
"original_instruction": "You are provided with a partial implementation of a matrix multiplication algorithm. The current implementation multiplies two matrices and returns their product. However, the existing code may raise an exception if the matrices are not conformable (i.e., the number of columns in the first ... | 0.506698 | Data_Structure_45981 | C | [
"add_matrix",
"subtract_matrix",
"strassen_mult",
"multiply_matrices"
] | 4 | [
[
"multiply_matrices",
"strassen_mult"
],
[
"strassen_mult",
"add_matrix"
],
[
"strassen_mult",
"subtract_matrix"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | b87b09c61c17f3e0bc26994817bccb20d1857846 | 4d92d2847620ce2408ddae4dff16499172ccdd1d | |||
v1.0 | complete | Data_Structure | Data_Structure_46608_C | def insertion_sort(arr):
"""
Helper function to sort array using insertion sort.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def bucket_sort(arr)... | def insertion_sort(arr):
"""
Helper function to sort array using insertion sort.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def bucket_sort(arr)... | from solution import bucket_sort
def test_empty_array():
assert bucket_sort([]) == []
def test_single_element_array():
assert bucket_sort([0.5]) == [0.5]
def test_sorted_array():
assert bucket_sort([0.1, 0.4, 0.6, 0.7, 0.9]) == [0.1, 0.4, 0.6, 0.7, 0.9]
def test_reverse_sorted_array():
assert bucket... | [
{
"docstring": "Helper function to sort array using insertion sort.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts an array of floating-point numbers in the range [0, 1) using bucket sort.",
"fun... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bucket_sort(arr):\n ''' Bucket Sort\n Complexity: O(n^2) in the worst case\n Average Time Complexity: O(n)\n '''\n if len(arr) == 0... | trial_gpt4o_2 | {
"original_instruction": "### Bucket Sort Implementation\n\n**Scenario**: \nYou are given the task of implementing the Bucket Sort algorithm to sort an array of floating-point numbers in the range [0, 1). Bucket Sort is particularly effective in this case due to the uniform distribution characteristic. \n\n**Task**:... | 0.648289 | Data_Structure_46608 | C | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 712896db40d94cfd396bb946d6993d88ed52b1e9 | 73b6a523292bce38900263b330fa349a5230ccb1 | |||
v1.0 | complete | Data_Structure | Data_Structure_46859_C | def contain_string_optimized(haystack: str, needle: str) -> int:
"""Uses the KMP algorithm to find the index of the first occurrence
of the needle in the haystack. Returns -1 if not found.
>>> contain_string_optimized("abxabcabcaby", "abcaby") == 6
>>> contain_string_optimized("hello", "ll") == 2
... | def build_lps(needle):
"""
Builds the longest prefix which is also suffix array (lps) for the KMP algorithm.
"""
lps = [0] * len(needle)
length = 0 # length of the previous longest prefix suffix
i = 1
while i < len(needle):
if needle[i] == needle[length]:
length += 1
... | from solution import contain_string_optimized
def test_contain_string_optimized_found():
assert contain_string_optimized("abxabcabcaby", "abcaby") == 6
assert contain_string_optimized("hello", "ll") == 2
assert contain_string_optimized("aaaaa", "bba") == -1
assert contain_string_optimized("aaabaaaabaaa... | [
{
"docstring": "Builds the longest prefix which is also suffix array (lps) for the KMP algorithm.",
"function_declaration": "def build_lps(needle):",
"function_name": "build_lps",
"parameter_list": "(needle)"
},
{
"docstring": "Uses the KMP algorithm to find the index of the first occurrence... | [
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 build_lps(needle):\n \"\"\"\n Builds the longest prefix which is also suffix array (lps) for the KMP algorithm.\n \"\"\"\n lps = [0] * len(nee... | trial_gpt4o_0 | {
"original_instruction": "You have been tasked to extend the function `contain_string` to increase its efficiency. The current implementation performs a brute-force search to find the index of the first occurrence of a substring (needle) within a larger string (haystack). However, this approach can be slow for large... | 0.603002 | Data_Structure_46859 | C | [
"build_lps",
"contain_string_optimized"
] | 2 | [
[
"contain_string_optimized",
"build_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dc5669ad8cfed833734cad4704d468170f13cc3d | 5ad93d86160a15b490622a054ca31182e0f94d4c | |||
v1.0 | complete | Data_Structure | Data_Structure_46512_C | def merge_sort(arr):
"""
Helper function to perform merge sort on an array.
"""
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i = j = k = 0
... | def merge_sort(arr):
"""
Helper function to perform merge sort on an array.
"""
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i = j = k = 0
... | def test_merge_sort():
assert merge_sort([4, 2, 7, 1, 3]) == [1, 2, 3, 4, 7]
assert merge_sort([15, -2, 8, 5, 0]) == [-2, 0, 5, 8, 15]
assert merge_sort([]) == []
assert merge_sort([1]) == [1]
assert merge_sort([5, 5, 5]) == [5, 5, 5]
def test_advanced_bucket_sort():
assert advanced_bucket_sort... | [
{
"docstring": "Helper function to perform merge sort on an array.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def advanced_bucket_sort(arr):",
"function_name": "advanced_b... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n left_half = arr[:mid]\n right_half = arr[mid:]\n \n merg... | trial_gpt4o_1 | {
"original_instruction": "### Question: Advanced Bucket Sort Implementation\n\nYou are tasked with implementing an advanced bucket sort function that uses a dynamic approach to bucket creation and a more efficient nested sorting algorithm. The goal is to handle large datasets and varying distributions effectively.\n... | 0.619706 | Data_Structure_46512 | C | [
"merge_sort",
"advanced_bucket_sort"
] | 2 | [
[
"advanced_bucket_sort",
"merge_sort"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 3d6a04f7c7e1e5812493bb62042f616a4ad76062 | 6f7dd6cee14d1a37875cfa315208786a6aa61111 | |||
v1.0 | complete | Data_Structure | Data_Structure_46784_C | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr: list, simulation: bool=False) -> list:
"""
Sorts the provided array using Bogo So... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr, simulation=False):
"""
Sorts the provided array using Bogo Sort.
Parameters:... | from solution import bogo_sort
def test_empty_list():
assert bogo_sort([]) == []
def test_single_element_list():
assert bogo_sort([1]) == [1]
def test_sorted_list():
assert bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list():
assert bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4,... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the provided array using Bogo Sort.\n\nParameters:\narr (list): A list of integers.\nsimulation (... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef bogo_sort(arr: list, simulation: bool=False) -> list:\n \"\"\"\n Sorts the provided array using Bogo Sort.\n \n Parameters:\n... | trial_gpt4o_1 | {
"original_instruction": "You have learned about various sorting algorithms and their efficiencies. One of the least efficient sorting algorithms is the Bogo Sort, which relies on random permutations of the list until it gets sorted. Despite its impracticality, it provides a good exercise to understand the concept o... | 0.623466 | Data_Structure_46784 | C | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2a1037c36bb18dfdfc8eb858634deaf92a543d9f | 7d53ceb3499266f6cddfdb3781cb3939eb21c7ba | |||
v1.0 | complete | Data_Structure | Data_Structure_46736_C | [Completion Task in Python]
from typing import List
def invert_matrix(matrix: List[List[float]]) -> List[List[float]]:
"""
Invert a given n x n matrix.
Args:
matrix: A list of lists of floats representing an n x n matrix (2 <= n <= 10).
Returns:
The inverted matrix as a list of list... | from typing import List
def get_matrix_minor(matrix: List[List[float]], i: int, j: int) -> List[List[float]]:
return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]
def get_matrix_determinant(matrix: List[List[float]]) -> float:
# Base case for 2x2 matrix
if len(matrix) == 2:
return m... | from solution import invert_matrix
def test_invert_2x2_matrix():
matrix = [
[4, 7],
[2, 6]
]
expected = [
[0.6, -0.7],
[-0.2, 0.4]
]
assert invert_matrix(matrix) == expected
def test_invert_3x3_matrix():
matrix = [
[1, 2, 3],
[0, 1, 4],
[... | [
{
"docstring": null,
"function_declaration": "def get_matrix_minor(matrix, i, j):",
"function_name": "get_matrix_minor",
"parameter_list": "(matrix, i, j)"
},
{
"docstring": null,
"function_declaration": "def get_matrix_determinant(matrix):",
"function_name": "get_matrix_determinant"... | [
0,
0,
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 determinant(matrix: List[List[float]], n: int) -> float:\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0... | trial_gpt4o_2 | {
"original_instruction": "#### Objective\nWrite a function to invert a given `n x n` matrix. Your implementation should particularly focus on matrices larger than `2 x 2`, utilizing the fundamental principles of matrix inversion as analyzed above. Ensure your code handles edge cases and invalid inputs appropriately.... | 0.555436 | Data_Structure_46736 | C | [
"get_matrix_minor",
"get_matrix_determinant",
"get_matrix_inverse",
"invert_matrix"
] | 4 | [
[
"get_matrix_determinant",
"get_matrix_minor"
],
[
"get_matrix_inverse",
"get_matrix_determinant"
],
[
"get_matrix_inverse",
"get_matrix_minor"
],
[
"invert_matrix",
"get_matrix_inverse"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 671d9b060148df14ce398f218d777124fefa14dd | 4cd62ccd37d5b88da128115024925363043a0958 | |||
v1.0 | complete | Data_Structure | Data_Structure_46708_C | from typing import List
def max_water_flow(capacity: List[List[int]], source: int, sink: int) -> int:
"""
Implement a maximum flow algorithm for a city's water distribution network.
Given the capacities of the pipes (edges) between different facilities (nodes),
determine the maximum amount of water t... | from typing import List
from collections import deque
def bfs(residual_capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:
visited = [False] * len(residual_capacity)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
... | from solution import max_water_flow
def test_max_water_flow_example():
capacity = [
[0, 10, 10, 0, 0, 0],
[0, 0, 1, 10, 0, 0],
[0, 0, 0, 0, 10, 0],
[0, 0, 0, 0, 0, 10],
[0, 0, 0, 0, 0, 10],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert max_water_flo... | [
{
"docstring": null,
"function_declaration": "def bfs(residual_capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def max_water_flow(capacity, source, sink):",
"func... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bfs(capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n \"\"\"\n Returns True if there is a ... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with implementing a maximum flow algorithm for an application that models a city's water distribution network. Given the capacities of the pipes (edges) between different facilities (nodes), your objective is to determine the maximum amount of water that can be transported fr... | 0.682234 | Data_Structure_46708 | C | [
"bfs",
"max_water_flow"
] | 2 | [
[
"max_water_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f42495ada7351f3b9d82807559f2b7f1d3586912 | 7be48b05e41efdadcf4e99cf94e1014fcbe036c6 | |||
v1.0 | complete | Data_Structure | Data_Structure_46616_C | def calculate_determinant(matrix: List[List[float]]) -> float:
"""
Compute the determinant of a given square matrix.
>>> calculate_determinant([[4, 6], [3, 8]]) == 14
>>> calculate_determinant([[6, 1, 1], [4, -2, 5], [2, 8, 7]]) == -306
>>> calculate_determinant([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) ==... | def calculate_determinant(matrix):
"""
Computes the determinant of a given square matrix.
"""
# Base case for 2x2 matrix
if len(matrix) == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
determinant = 0
for c in range(len(matrix)):
determinant += ((-1) **... | def test_calculate_determinant_2x2():
matrix = [
[4, 6],
[3, 8]
]
assert calculate_determinant(matrix) == 14
def test_calculate_determinant_3x3():
matrix = [
[6, 1, 1],
[4, -2, 5],
[2, 8, 7]
]
assert calculate_determinant(matrix) == -306
def test_calcula... | [
{
"docstring": "Computes the determinant of a given square matrix.",
"function_declaration": "def calculate_determinant(matrix):",
"function_name": "calculate_determinant",
"parameter_list": "(matrix)"
},
{
"docstring": "Extracts the minor of the matrix by removing the specified row and colu... | [
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 calculate_determinant(matrix):\n \"\"\"\n Returns the determinant of a given square matrix.\n \"\"\"\n n = len(matrix)\n \n if n == 2:\n... | trial_gpt4o_2 | {
"original_instruction": "### Matrix Operations: Determinant Calculator and Minor Matrix Extractor\n\n#### Objective:\nImplement functions to calculate the determinant of a matrix and extract minors, which are fundamental steps in more complex algorithms, such as matrix inversion.\n\n#### Task:\n1. Implement a funct... | 0.507752 | Data_Structure_46616 | C | [
"calculate_determinant",
"extract_minor"
] | 2 | [
[
"calculate_determinant",
"extract_minor"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | b4ea95da5f0f6c71f2d26151c9d9e9ff6330e8cd | 400649b020f7807697ff5a0ff38f662d33e0aa99 | |||
v1.0 | complete | Data_Structure | Data_Structure_46462_C | from typing import List
def update(bit_tree: List[int], n: int, i: int, val: int) -> None:
"""
Updates the Fenwick Tree by adding `val` at index `i`.
"""
pass
def get_sum(bit_tree: List[int], i: int) -> int:
"""
Returns the prefix sum from the start of the array to index `i`.
"""
pass
... | from typing import List
def update(bit_tree: List[int], n: int, i: int, val: int) -> None:
"""
Updates the Fenwick Tree by adding `val` at index `i`.
"""
i += 1 # Fenwick Tree is 1-indexed internally
while i <= n:
bit_tree[i] += val
i += i & -i
def get_sum(bit_tree: List[int], i: ... | import pytest
from solution import update, get_sum, construct
def test_construct():
arr = [3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3]
bit_tree = construct(arr)
prefix_sums = [3, 5, 4, 10, 15, 19, 16, 19, 26, 28, 31]
for i, sum_val in enumerate(prefix_sums):
assert get_sum(bit_tree, i) == sum_val
def t... | [
{
"docstring": "Updates the Fenwick Tree by adding `val` at index `i`.",
"function_declaration": "def update(bit_tree, n, i, val):",
"function_name": "update",
"parameter_list": "(bit_tree, n, i, val)"
},
{
"docstring": "Returns the prefix sum from the start of the array to index `i`.",
... | [
0,
0,
0,
1,
1,
0,
1,
0,
1
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def update(bit_tree, n, i, val):\n i += 1 # Fenwick Tree is 1-based index.\n while i <= n:\n bit_tree[i] += val\n i += (i & -i)\n\ndef ge... | trial_gpt4o_9 | {
"original_instruction": "Given an array of integers, implement a data structure that supports the following operations efficiently:\n\n1. **Update**: Update the value of an element in the array.\n2. **Prefix Sum**: Calculate the sum of the elements from the beginning of the array to a given index.\n\nYou need to im... | 0.494995 | Data_Structure_46462 | C | [
"update",
"get_sum",
"construct"
] | 3 | [
[
"construct",
"update"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2102eb819ee43feb8c764a8c8bd8c8650f53ef2e | ddf9c3ba7454055cee25b4a5cbe81b3decb265b3 | |||
v1.0 | complete | Data_Structure | Data_Structure_46625_C | def find_digit_powered_numbers(low: int, high: int) -> List[int]:
""" Implement a function to find all numbers within a given range that can be expressed as the sum of their digits each raised to consecutive powers.
>>> find_digit_powered_numbers(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> find_digit_powered... | def sum_of_digits_to_consecutive_powers(n):
digits = [int(d) for d in str(n)]
return sum(d**(i+1) for i, d in enumerate(digits))
def find_digit_powered_numbers(low, high):
result = []
for n in range(low, high):
if n == sum_of_digits_to_consecutive_powers(n):
result.append(n)
ret... | from solution import find_digit_powered_numbers
def test_single_digit_range():
assert find_digit_powered_numbers(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_double_digit_range():
assert find_digit_powered_numbers(10, 100) == [89]
def test_edge_case_lower_bound():
assert find_digit_powered_numbers(89, ... | [
{
"docstring": null,
"function_declaration": "def sum_of_digits_to_consecutive_powers(n):",
"function_name": "sum_of_digits_to_consecutive_powers",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def find_digit_powered_numbers(low, high):",
"function_name": "... | [
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 find_digit_powered_numbers(low, high):\n \"\"\"\n Returns a list of numbers between low and high (inclusive) that can be expressed\n as the sum o... | trial_gpt4o_9 | {
"original_instruction": "### Question\n\n### Check Digit-Powered Numbers\n\nYour task is to implement a function `find_digit_powered_numbers(low, high)` that takes two integers `low` and `high` as input parameters and returns a list of all numbers within this range (inclusive) that can be expressed as the sum of th... | 0.594907 | Data_Structure_46625 | C | [
"sum_of_digits_to_consecutive_powers",
"find_digit_powered_numbers"
] | 2 | [
[
"find_digit_powered_numbers",
"sum_of_digits_to_consecutive_powers"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1349eba411ae4f3bf08332b75ec95416d7f23cc1 | c916cb7510dad92e2071350fb36efd855cc93761 | |||
v1.0 | complete | Data_Structure | Data_Structure_46975_C | class RBNode:
def __init__(self, val, color, left=None, right=None, parent=None):
self.val = val
self.color = color
self.left = left
self.right = right
self.parent = parent
class RBTree:
def __init__(self):
self.NIL_LEAF = RBNode(val=None, color=0)
self.r... | class RBNode:
def __init__(self, val, color, left=None, right=None, parent=None):
self.val = val
self.color = color
self.left = left
self.right = right
self.parent = parent
class RBTree:
def __init__(self):
self.NIL_LEAF = RBNode(val=None, color=0)
self.r... | import pytest
from solution import RBNode, RBTree, find_inorder_successor
def build_test_tree():
tree = RBTree()
nodes = {
11: RBNode(11, 1),
2: RBNode(2, 1),
14: RBNode(14, 1),
1: RBNode(1, 1),
7: RBNode(7, 1),
15: RBNode(15, 1),
5: RBNode(5, 1),
... | [] | [
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": "class RBNode:\n def __init__(self, key, color, left=None, right=None, parent=None):\n self.key = key\n self.color = color # 1 for Red, 0 for... | trial_gpt4o_6 | {
"original_instruction": "You are given an implementation of a Red-Black Tree. This self-balancing binary search tree structure ensures that the tree remains balanced with standard operations performed in O(log n) time complexity.\n\nYour task is to enhance the Red-Black Tree by implementing an additional function c... | 0.478378 | Data_Structure_46975 | C | [
"find_inorder_successor",
"find_minimum"
] | 2 | [
[
"find_inorder_successor",
"find_minimum"
]
] | 1 | [] | false | [
"RBNode",
"RBTree"
] | true | pytest | true | [] | true | 6d3e1926750b9b87536ce18f860b41d214c97388 | 0321fb4f7046336f40a0445a5f7433617bdf6733 | |||
v1.0 | complete | Data_Structure | Data_Structure_46405_C | def merge_sort(arr):
""" Sort an unsorted list of integers using the Merge Sort algorithm.
>>> merge_sort([5, 3, 8, 4, 2, 7, 6, 1])
[1, 2, 3, 4, 5, 6, 7, 8]
>>> merge_sort([1])
[1]
>>> merge_sort([2, 1])
[1, 2]
>>> merge_sort([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> merge_sort([5, 4,... | def merge_sort(arr):
# Base case for recursion
if len(arr) <= 1:
return arr
mid = len(arr) // 2
# Recursively split the arrays
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
# Create a merged array with sorted order
merged = []
merge(left, righ... | from solution import merge_sort
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_two_elements():
assert merge_sort([2, 1]) == [1, 2]
def test_merge_sort_random_order():
assert merge_sort([5, 3, 8, 4, 2, 7, 6, 1]) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_merge_sort_alre... | [
{
"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 # Base case for recursion\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n \n # Recursively split t... | trial_gpt4o_2 | {
"original_instruction": "### Merge Sort Coding Challenge\n\nYou are given an unsorted list of integers. Your task is to implement the Merge Sort algorithm to sort the list in ascending order. The implementation should follow the principles of Merge Sort and must handle various edge cases efficiently.\n\nYour implem... | 0.652004 | Data_Structure_46405 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ef88f7cf415c599286c0791281dec27d1a7beb9a | 0918847b320e85071094f5c68aab2a69b390395d | |||
v1.0 | complete | Data_Structure | Data_Structure_46610_C | from typing import List
def dna_pattern_search(dna: str, pattern: str) -> List[int]:
"""
Implement a function that efficiently searches for patterns within a DNA sequence using the Knuth-Morris-Pratt (KMP) string matching algorithm.
Args:
dna (str): The DNA sequence to search within.
pattern (str)... | from typing import List
def compute_lps_array(pattern: str) -> List[int]:
"""
KMP algorithm helper function that preprocesses the pattern to produce the longest prefix suffix (LPS) array.
"""
lps = [0] * len(pattern)
length = 0
i = 1
while i < len(pattern):
if pattern[i] == pat... | from solution import dna_pattern_search
def test_dna_pattern_search_case1():
assert dna_pattern_search("ACGTACGTGACG", "ACG") == [0, 4, 9]
def test_dna_pattern_search_case2():
assert dna_pattern_search("GATTACA", "GATT") == [0]
def test_dna_pattern_search_case3():
assert dna_pattern_search("AGCTAGC", "GG... | [
{
"docstring": "KMP algorithm helper function that preprocesses the pattern to produce the longest prefix suffix (LPS) array.",
"function_declaration": "def compute_lps_array(pattern):",
"function_name": "compute_lps_array",
"parameter_list": "(pattern)"
},
{
"docstring": "Function to search... | [
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 compute_lps_array(pattern: str) -> List[int]:\n \"\"\"\n KMP algorithm helper function that preprocesses the pattern to p... | trial_gpt4o_0 | {
"original_instruction": "You have been hired as a software engineer by a company that specializes in DNA sequence analysis. As part of their analytical toolset, you are required to implement a function that efficiently searches for patterns within a DNA sequence using the Knuth-Morris-Pratt (KMP) string matching al... | 0.573391 | Data_Structure_46610 | C | [
"compute_lps_array",
"dna_pattern_search"
] | 2 | [
[
"dna_pattern_search",
"compute_lps_array"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f8eacb2dc27526b0f15039f88cabfc600ed12217 | b3388d3adf31c0d3c34cd540a0a4e8ff1fe733c9 | |||
v1.0 | complete | Data_Structure | Data_Structure_46339_C | from typing import List
def parallel_bitonic_sort(arr: List[int], reverse: bool = False) -> List[int]:
""" Enhance the provided Bitonic Sort algorithm by incorporating Python's multiprocessing capabilities to sort large arrays efficiently.
The size of the array will always be a power of two.
>>> paral... | import multiprocessing
from typing import List
def compare_and_swap(arr: List[int], i: int, j: int, direction: bool):
if direction == (arr[i] > arr[j]):
arr[i], arr[j] = arr[j], arr[i]
def bitonic_merge(arr: List[int], low: int, cnt: int, direction: bool):
if cnt > 1:
k = cnt // 2
for ... | from solution import parallel_bitonic_sort
def test_parallel_bitonic_sort_basic():
arr = [3, 7, 2, 5, 1, 6, 4, 8]
assert parallel_bitonic_sort(arr) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_parallel_bitonic_sort_reverse():
arr = [3, 7, 2, 5, 1, 6, 4, 8]
assert parallel_bitonic_sort(arr, reverse=True) == [8... | [
{
"docstring": null,
"function_declaration": "def compare_and_swap(arr, i, j, direction):",
"function_name": "compare_and_swap",
"parameter_list": "(arr, i, j, direction)"
},
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, low, cnt, direction):",
"function_name":... | [
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 multiprocessing\nfrom typing import List\n\ndef compare_and_swap(arr: List[int], i: int, j: int, direction: bool):\n if direction == (arr[i] > arr[j... | trial_gpt4o_0 | {
"original_instruction": "## Bitonic Sort Enhancement Challenge\n\n### Objective\nThe task is to optimize the given Bitonic Sort algorithm by introducing a parallel processing approach. This will improve the runtime performance over large input sizes. The provided bitonic sort algorithm works well, but does not util... | 0.643649 | Data_Structure_46339 | C | [
"compare_and_swap",
"bitonic_merge",
"bitonic_sort",
"parallel_bitonic_sort"
] | 4 | [
[
"bitonic_merge",
"compare_and_swap"
],
[
"bitonic_sort",
"bitonic_merge"
],
[
"parallel_bitonic_sort",
"bitonic_merge"
],
[
"parallel_bitonic_sort",
"bitonic_sort"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 13026dea71f245d3a29a1b30b4c19fd7166911f4 | f2d0d558a8e01cbd7b5b69fcbac6f2efaa6b19ee | |||
v1.0 | complete | Data_Structure | Data_Structure_46940_C | from typing import List
def merge_sort_inplace(arr: List[int]) -> None:
""" Sorts an array of integers in non-decreasing order using in-place merge sort.
>>> arr = [4, 2, 5, 1, 3]
>>> merge_sort_inplace(arr)
>>> arr
[1, 2, 3, 4, 5]
>>> arr = [10, -1, 2, 5, 0]
>>> merge_sort_inplace(arr)
... | from typing import List
def merge(arr: List[int], start: int, mid: int, end: int) -> None:
"""
Merges two sorted halves of the array in place.
"""
start2 = mid + 1
# If the direct merge is already sorted
if arr[mid] <= arr[start2]:
return
# Two pointers to maintain start of both... | import pytest
from solution import merge_sort_inplace
def test_merge_sort_inplace_with_positive_numbers():
arr = [4, 2, 5, 1, 3]
merge_sort_inplace(arr)
assert arr == [1, 2, 3, 4, 5]
def test_merge_sort_inplace_with_mixed_numbers():
arr = [10, -1, 2, 5, 0]
merge_sort_inplace(arr)
assert arr ==... | [
{
"docstring": "Merges two sorted halves of the array in place.",
"function_declaration": "def merge(arr, start, mid, end):",
"function_name": "merge",
"parameter_list": "(arr, start, mid, end)"
},
{
"docstring": null,
"function_declaration": "def merge_sort_inplace(arr, l=0, r=None):",
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort_inplace(arr: List[int]) -> None:\n \"\"\"\n Perform in-place merge sort on the given array.\n \"\"\"\n d... | trial_gpt4o_2 | {
"original_instruction": "Implement In-Place Merge Sort\n\nYou are tasked to implement the merge sort algorithm with minimal space usage by merging the sorted halves within the original array without using additional subarrays.\n\n#### Problem Statement\n\nWrite a function `merge_sort_inplace(arr)` that sorts an arr... | 0.660796 | Data_Structure_46940 | C | [
"merge",
"merge_sort_inplace"
] | 2 | [
[
"merge_sort_inplace",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 251ed3eee6490c8a506c3b1ebf798bd211ae7c90 | 07311119055bd4efa43ec34896a786cd6014ad13 | |||
v1.0 | complete | Data_Structure | Data_Structure_47124_C | from typing import List
def longest_common_prefix_binary_search(strs: List[str]) -> str:
""" Finds the longest common prefix string amongst an array of strings using binary search.
>>> longest_common_prefix_binary_search(["flower", "flow", "flight"])
"fl"
>>> longest_common_prefix_binary_search(["dog",... | from typing import List
def is_common_prefix(strs: List[str], length: int) -> bool:
"""
Check if a specific length of prefix is common among all strings.
"""
prefix = strs[0][:length]
return all(s.startswith(prefix) for s in strs)
def longest_common_prefix_binary_search(strs: List[str]) -> str:
... | from solution import (
longest_common_prefix_binary_search,
longest_common_prefix_v1,
longest_common_prefix_v2,
longest_common_prefix_v3
)
import time
def test_longest_common_prefix():
test_cases = [
(["flower", "flow", "flight"], "fl"),
(["dog", "racecar", "car"], ""),
([],... | [
{
"docstring": "Check if a specific length of prefix is common among all strings.",
"function_declaration": "def is_common_prefix(strs, length):",
"function_name": "is_common_prefix",
"parameter_list": "(strs, length)"
},
{
"docstring": "Finds the longest common prefix string amongst an arra... | [
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 longest_common_prefix_binary_search(strs: List[str]) -> str:\n if not strs:\n return \"\"\n \n # Find the minim... | trial_gpt4o_1 | {
"original_instruction": "**Problem Statement**:\n\nGiven an array of strings, write a function to find the longest common prefix string amongst them. If there is no common prefix, return an empty string.\n\nYou are provided with three existing solutions using different algorithms: Horizontal Scanning, Vertical Scan... | 0.607417 | Data_Structure_47124 | C | [
"is_common_prefix",
"longest_common_prefix_binary_search",
"longest_common_prefix_v1",
"longest_common_prefix_v2",
"longest_common_prefix_v3"
] | 5 | [
[
"longest_common_prefix_binary_search",
"is_common_prefix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bd10ed6091c37de35653b3bf009464394626c72d | b74a4d4fe29c747c0a2c2f4d2e5c22d2d92ee9e2 | |||
v1.0 | complete | Data_Structure | Data_Structure_46289_C | from typing import List
def maximum_flow_dfs(adjacency_matrix: List[List[int]]) -> int:
"""
Determine the maximum flow in a directed graph using Depth-First Search method.
Parameters:
adjacency_matrix (List[List[int]]): A 2D list representing the capacities of the directed graph.
Returns:
int... | from typing import List
def dfs(graph: List[List[int]], source: int, sink: int, path: List[bool], parent: List[int]) -> bool:
visited = [False] * len(graph)
stack = [source]
visited[source] = True
while stack:
u = stack.pop()
for v in range(len(graph)):
if visited[v] ==... | from solution import maximum_flow_dfs
def test_maximum_flow_simple_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_dfs(graph) == 23
def test_... | [
{
"docstring": null,
"function_declaration": "def dfs(graph, source, sink, path, parent):",
"function_name": "dfs",
"parameter_list": "(graph, source, sink, path, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_dfs(adjacency_matrix):",
"function_name": "max... | [
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 maximum_flow_dfs(adjacency_matrix: List[List[int]]) -> int:\n def dfs(source, sink, path):\n if source == sink:\n ... | trial_gpt4o_2 | {
"original_instruction": "<|Analysis Begin|>\n\n**Algorithm/Data Structure**: The algorithm used here is for calculating the **maximum flow** in a flow network using the **Depth-First Search (DFS) method**. This is a specific implementation focusing on finding the maximum amount of \"flow\" that can be pushed from a... | 0.594114 | Data_Structure_46289 | C | [
"dfs",
"maximum_flow_dfs"
] | 2 | [
[
"maximum_flow_dfs",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 36e5bc85185938e863b20d88b708a866534f2ab7 | b96beee0abb9cacc62042392772f1f3fc2849a0d | |||
v1.0 | complete | Data_Structure | Data_Structure_47471_C | from typing import List
def prime_in_range(start: int, end: int) -> List[int]:
""" Returns a list of all prime numbers within the range [start, end] inclusive.
>>> prime_in_range(10, 50)
[11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> prime_in_range(14, 16)
[]
>>> prime_in_range(29, 29)
[2... | from typing import List
def is_prime(n: int) -> bool:
"""
Helper function to determine if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) ... | from solution import prime_in_range
def test_prime_in_range_all_primes():
assert prime_in_range(10, 50) == [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
def test_prime_in_range_no_primes():
assert prime_in_range(14, 16) == []
def test_prime_in_range_single_element_prime():
assert prime_in_range(29, 29) ==... | [
{
"docstring": "Helper function to determine if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers within the range [start, end] inclusive.",
"function_declaration": ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % ... | trial_gpt4o_1 | {
"original_instruction": "You've been tasked with creating a function to identify prime numbers within a given range efficiently. Your function will be part of a larger application that relies heavily on prime number calculations.\n\nImplement a function `prime_in_range(start: int, end: int) -> List[int]` that will ... | 0.663895 | Data_Structure_47471 | C | [
"is_prime",
"prime_in_range"
] | 2 | [
[
"prime_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f9d51ec09ec7e026f136ffe33177c4654c5e0f22 | 3f9f2f464972affaea95673efa51a0a1bcc285a9 | |||
v1.0 | complete | Data_Structure | Data_Structure_47398_C | from typing import List
def pancake_sort(arr: List[int]) -> List[int]:
"""Sort the array using Pancake Sorting algorithm.
>>> pancake_sort([3, 2, 4, 1])
[1, 2, 3, 4]
>>> pancake_sort([1, 2, 3, 4])
[1, 2, 3, 4]
>>> pancake_sort([4, 3, 2, 1])
[1, 2, 3, 4]
>>> pancake_sort([1])
[1]
... | from typing import List
def flip(arr: List[int], k: int) -> None:
"""Reverses the order of the first k elements in the array."""
arr[:k] = arr[:k][::-1]
def find_max_index(arr: List[int], n: int) -> int:
"""Finds the index of the maximum element in arr[0..n-1]."""
max_index = 0
for i in range(1, n... | from solution import pancake_sort
def test_pancake_sort_simple():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
def test_pancake_sort_already_sorted():
assert pancake_sort([1, 2, 3, 4]) == [1, 2, 3, 4]
def test_pancake_sort_reverse_sorted():
assert pancake_sort([4, 3, 2, 1]) == [1, 2, 3, 4]
def test... | [
{
"docstring": "Reverses the order of the first k elements in the array.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Finds the index of the maximum element in arr[0..n-1].",
"function_declaration": "def find_max_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef flip(arr: List[int], k: int) -> None:\n \"\"\"\n Helper function to reverse the order of the first k elements in the arra... | trial_gpt4o_2 | {
"original_instruction": "You are given an unsorted array of integers. You need to implement the `pancake_sort` function, which sorts the array using Pancake Sorting algorithm. Your implementation should sort the array in ascending order using the process of repeatedly flipping portions of the array, similar to sort... | 0.777955 | Data_Structure_47398 | C | [
"flip",
"find_max_index",
"pancake_sort"
] | 3 | [
[
"pancake_sort",
"find_max_index"
],
[
"pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d08e9133e5202a19c20fc420a78830740b0373c4 | 381aaabc164c6574129ef0f3840ae9531673eb9e | |||
v1.0 | complete | Data_Structure | Data_Structure_46752_C | def search_insert(sorted_list, value):
"""
Helper function to find the insertion index for a value in a sorted list.
:param sorted_list: List of sorted integers.
:param value: Integer value to be inserted.
:return: Index at which `value` should be inserted to keep the list sorted.
"""
pass
... | def search_insert(sorted_list, value):
"""
Helper function to find the insertion index for a value in a sorted list.
:param sorted_list: List of sorted integers.
:param value: Integer value to be inserted.
:return: Index at which `value` should be inserted to keep the list sorted.
"""
left, ... | from solution import insertion_sort
def test_empty_array():
assert insertion_sort([]) == []
def test_single_element_array():
assert insertion_sort([1]) == [1]
def test_sorted_array():
assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert insertion_sort([5,... | [
{
"docstring": "Helper function to find the insertion index for a value in a sorted list.\n:param sorted_list: List of sorted integers.\n:param value: Integer value to be inserted.\n:return: Index at which `value` should be inserted to keep the list sorted.",
"function_declaration": "def search_insert(sorte... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(sorted_array, target):\n \"\"\"\n Helper function to find the position where `target` should be \n inserted in the sorted subarray ... | trial_gpt4o_2 | {
"original_instruction": "### Insertion Sort Algorithm Implementation\n\n**Objective**: Implement the full insertion sort algorithm utilizing the provided `search_insert` helper function. \n\n### Scenario\nYou are given an unsorted array and need to sort it using insertion sort. To optimize the insertion process, yo... | 0.666898 | Data_Structure_46752 | C | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6b6ef0505e8a96244968d4d858a8ab2575349409 | c9766cc1b98690cdda6bf1f61c9b20542eea7f37 | |||
v1.0 | complete | Data_Structure | Data_Structure_46793_C | def multiply(A, B):
""" Multiplies two matrices A and B
>>> multiply([[1, 2], [3, 4]], [[1, 0], [0, 1]])
[[1, 2], [3, 4]]
>>> multiply([[2, 1], [1, 2]], [[0, 1], [1, 0]])
[[1, 2], [2, 1]]
"""
def identity(d):
""" Returns the identity matrix of size d x d
>>> identity(2)
[[1, 0],... | def multiply(A, B):
"""
Multiplies two matrices A and B
"""
d = len(A)
result = [[0] * d for _ in range(d)]
for i in range(d):
for j in range(d):
for k in range(d):
result[i][j] += A[i][k] * B[k][j]
return result
def identity(d):
"""
Returns the i... | from solution import multiply, identity, matrix_exponentiation, matrix_power_sequence
def test_multiply():
assert multiply([[1, 2], [3, 4]], [[1, 0], [0, 1]]) == [[1, 2], [3, 4]]
assert multiply([[2, 1], [1, 2]], [[0, 1], [1, 0]]) == [[1, 2], [2, 1]]
def test_identity():
assert identity(2) == [[1, 0], [0,... | [
{
"docstring": "Multiplies two matrices A and B",
"function_declaration": "def multiply(A, B):",
"function_name": "multiply",
"parameter_list": "(A, B)"
},
{
"docstring": "Returns the identity matrix of size d x d",
"function_declaration": "def identity(d):",
"function_name": "identi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B\n \"\"\"\n d = len(A)\n result = [[0] * d for _ in range(d)]\n for i in range... | trial_gpt4o_0 | {
"original_instruction": "### Matrix Power Computation\n\nYou are given three functions that perform matrix operations: `multiply` for matrix multiplication, `identity` for generating an identity matrix, and `matrix_exponentiation` for computing the power of a matrix.\n\nYour task is to implement a function `matrix_... | 0.532027 | Data_Structure_46793 | C | [
"multiply",
"identity",
"matrix_exponentiation",
"matrix_power_sequence"
] | 4 | [
[
"matrix_exponentiation",
"identity"
],
[
"matrix_exponentiation",
"multiply"
],
[
"matrix_power_sequence",
"matrix_exponentiation"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 2a41ae61e0e48b5284bd0385f4a8f3af3262afb5 | 56a402db4e689b7bc795c0606674e5eb3cc980c5 | |||
v1.0 | complete | Data_Structure | Data_Structure_46817_C | def compute_max_flow(capacity: List[List[int]], source: int, sink: int) -> int:
""" Computes the maximum flow from the source to the sink in a given network using the Edmonds-Karp algorithm.
Args:
capacity (List[List[int]]): A 2D list representing the capacity of edges in the network.
source (int):... | from typing import List
from collections import deque
def bfs(residual_capacity, source, sink, parent):
"""
A Breadth-First Search (BFS) based method to find if there is a path from source to sink in residual graph.
Also fills parent[] to store the path.
"""
visited = [False] * len(residual_capacit... | def test_max_flow_simple():
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 compute_max_flow(capacity, source, sink) == 23
def test_... | [
{
"docstring": "A Breadth-First Search (BFS) based method to find if there is a path from source to sink in residual graph.\nAlso fills parent[] to store the path.",
"function_declaration": "def bfs(residual_capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_capa... | [
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": "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_7 | {
"original_instruction": "### Maximum Flow in a Network\n\n**Context**:\nYou are managing a network where you need to optimize the maximum flow from a source node to a sink node. You have been provided with three algorithms for calculating the maximum flow in a network: Ford-Fulkerson (using DFS), Edmonds-Karp (usin... | 0.529234 | Data_Structure_46817 | C | [
"bfs",
"edmonds_karp"
] | 2 | [
[
"edmonds_karp",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 7aba3a37dfed1b51b3cb996719d45edd7dcb52cf | a8b50e1760bc8107a4d775356923b0c92f49cf9a | |||
v1.0 | complete | Data_Structure | Data_Structure_47625_C | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if the array is sorted.
"""
pass
def bogo_sort(arr: List[int]) -> List[int]:
"""
Sorts the given array using the Bogo Sort algorithm.
Example Usage:
>>> bogo_sort([3, 1, 2])
... | import random
from typing import List
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 bogo_sort(arr: List[int]) -> List[int]:
"""
Sorts the... | from solution import bogo_sort
def test_bogo_sort_sorted_array():
arr = [1, 2, 3, 4, 5]
assert bogo_sort(arr) == [1, 2, 3, 4, 5]
def test_bogo_sort_reverse_sorted_array():
arr = [5, 4, 3, 2, 1]
assert bogo_sort(arr) == [1, 2, 3, 4, 5]
def test_bogo_sort_random_array():
arr = [3, 1, 2]
assert ... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the given array using the Bogo Sort algorithm.",
"function_declaration": "def bogo_sort(arr):... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Check if the array is sorted in non-decreasing order.\n \... | trial_gpt4o_2 | {
"original_instruction": "### Bogo Sort Implementation Challenge\n\n#### Context\nBogo Sort, also whimsically known as Monkey Sort or Stupid Sort, is a highly ineffective and impractical sorting algorithm that permutes an array randomly until it is sorted. While its conceptual simplicity is intriguing, its execution... | 0.679894 | Data_Structure_47625 | C | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f6a2cfb278fb3e307afdd9429bb628d1e8f151af | 8f88cdeafe6c0511ea2cb99612349fba45a43fce | |||
v1.0 | complete | Data_Structure | Data_Structure_46792_C | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if an array is sorted.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def improved_bogo_sort(arr: List[int]) -> List[int]:
"""
Sort the input array using an improved ver... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if an array is sorted.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def improved_bogo_sort(arr: List[int]) -> List[int]:
"""
Sort the input array using an improved ver... | from solution import improved_bogo_sort
def test_improved_bogo_sort_already_sorted():
assert improved_bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_improved_bogo_sort_reversed():
assert improved_bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_improved_bogo_sort_random_order():
assert impr... | [
{
"docstring": "Helper function to check if an array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sort the input array using an improved version of bogo sort.",
"function_declaration": "def improved... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef improved_bogo_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Improved version of Bogo Sort that minimizes t... | trial_gpt4o_2 | {
"original_instruction": "#### Bogo Sort Improvement Challenge\n\nYou are given an unsorted array `arr` of integers. Your task is to implement an improved version of Bogo Sort that minimizes the number of shuffles required on average. The new algorithm should introduce optimizations, such as:\n1. Pre-check for eleme... | 0.618578 | Data_Structure_46792 | C | [
"is_sorted",
"improved_bogo_sort"
] | 2 | [
[
"improved_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cf1893b2bd3fffd82460d5259664b9346536087d | 540c77e9a9ca0285fc1982b0d0d4d014e9937a23 | |||
v1.0 | complete | Data_Structure | Data_Structure_47530_C | from typing import List, Tuple
def pancake_sort_with_flips(arr: List[int]) -> Tuple[List[int], List[int]]:
"""
Sorts an array using the pancake sort method and returns a tuple containing the sorted array and the sequence of flips (indices) performed.
>>> pancake_sort_with_flips([3, 2, 4, 1])
([1,... | from typing import List, Tuple
def flip(arr: List[int], k: int) -> None:
"""Reverses the order of the first k elements in the array."""
arr[:k] = arr[:k][::-1]
def pancake_sort_with_flips(arr: List[int]) -> Tuple[List[int], List[int]]:
res = []
n = len(arr)
for size in range(n, 1, -1):
... | from solution import pancake_sort_with_flips
def test_regular_list():
arr = [3, 2, 4, 1]
sorted_arr, flips = pancake_sort_with_flips(arr)
assert sorted_arr == [1, 2, 3, 4]
# Check if final array is sorted
assert sorted_arr == sorted(arr)
def test_empty_list():
arr = []
sorted_arr, flips = ... | [
{
"docstring": "Reverses the order of the first k elements in the array.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": null,
"function_declaration": "def pancake_sort_with_flips(arr):",
"function_name": "pancake... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef flip(arr: List[int], k: int) -> None:\n arr[:k] = reversed(arr[:k])\n\ndef pancake_sort_with_flips(arr: List[int]) ->... | trial_gpt4o_3 | {
"original_instruction": "### Pancake Sort Implementation and Analysis\n\n**Context**:\nPancake sorting is an analogy-based sorting method where you sort an array just like how a chef would arrange a pile of pancakes by flipping them with a spatula. Your task is to use the principles of Pancake Sort to sort an array... | 0.703131 | Data_Structure_47530 | C | [
"flip",
"pancake_sort_with_flips"
] | 2 | [
[
"pancake_sort_with_flips",
"flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 847527ab02db0678fceddcc9fdfc6ac7ffac5e4d | 5f794fe60bb6bb696e156224544cd7804eb233d4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.