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 | instruct | Data_Structure | Data_Structure_27878_I | You are given an array of integers and the task is to implement a function that sorts the given array using the Bucket Sort algorithm. However, within each bucket, use the Quick Sort algorithm instead of Insertion Sort to improve the performance.
### Function Signature
```python
def bucket_sort(arr: List[int]) -> List... | from typing import List
def quick_sort(arr: List[int]) -> List[int]:
"""Helper function to perform Quick Sort."""
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
... | from solution import bucket_sort
def test_bucket_sort_general_case():
assert bucket_sort([4, 1, 7, 3, 5, 2, 6, 8]) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_bucket_sort_empty():
assert bucket_sort([]) == []
def test_bucket_sort_single_element():
assert bucket_sort([42]) == [42]
def test_bucket_sort_all_same_... | [
{
"docstring": "Helper function to perform Quick Sort.",
"function_declaration": "def quick_sort(arr):",
"function_name": "quick_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Function to perform Bucket Sort with Quick Sort inside each bucket.",
"function_declaration": "def bucket_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": "from typing import List\n\ndef quick_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left =... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027878",
"row_id": 27878,
"seed_ids": "[26]"
} | 0.547351 | Data_Structure_27878 | I | [
"quick_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"quick_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3d9807cec0d186320ff95d4bd9c34470f995c0ff | 5ed92452103aaeba70316e31daa5d29a14d1bcfd | |||
v1.0 | instruct | Data_Structure | Data_Structure_27885_I | Design and implement a function to sort an array using a variation of Heap Sort. Specifically, you are required to write a function `hybrid_heap_sort` that dynamically chooses between max-heap sort or min-heap sort based on the initial ordering of the array. If more than half of the array elements are already sorted in... | def hybrid_heap_sort(arr):
if len(arr) <= 1:
return arr
# Determine if more than half the array is sorted in ascending order
sorted_count = sum(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
if sorted_count >= len(arr) // 2:
return min_heap_sort(arr)
else:
return max_hea... | import pytest
from solution import hybrid_heap_sort
def test_hybrid_heap_sort_empty():
assert hybrid_heap_sort([]) == []
def test_hybrid_heap_sort_single_element():
assert hybrid_heap_sort([1]) == [1]
def test_hybrid_heap_sort_sorted_asc():
assert hybrid_heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def... | [
{
"docstring": null,
"function_declaration": "def hybrid_heap_sort(arr):",
"function_name": "hybrid_heap_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def max_heap_sort(arr):",
"function_name": "max_heap_sort",
"parameter_list": "(arr)"
},
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def hybrid_heap_sort(arr):\n \"\"\"\n Sorts an array using a hybrid heap sort algorithm.\n Chooses min-heap sort if more than half of the elements ar... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027885",
"row_id": 27885,
"seed_ids": "[8]"
} | 0.62109 | Data_Structure_27885 | I | [
"hybrid_heap_sort",
"max_heap_sort",
"min_heap_sort"
] | 3 | [
[
"hybrid_heap_sort",
"max_heap_sort"
],
[
"hybrid_heap_sort",
"min_heap_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 88b8878bfc0d511ba815c8b94aa927b678c4fef2 | 3c09904daf52b27ebeb37dd5df4f8553470e75cd | |||
v1.0 | instruct | Data_Structure | Data_Structure_27899_I | You are tasked with developing a function that takes two non-negative integers and returns both their Greatest Common Divisor (GCD) and Least Common Multiple (LCM). The solution will test your understanding of the Euclidean algorithm, binary operations, and handling of edge cases in integer inputs.
#### Function Signa... | def gcd(a, b):
"""
Returns the Greatest Common Divisor (GCD) of integers a and b using the Euclidean Algorithm.
"""
while b:
a, b = b, a % b
return a
def gcd_and_lcm(a: int, b: int) -> (int, int):
"""
Computes the Greatest Common Divisor and Least Common Multiple of integers a and b... | from solution import gcd_and_lcm
def test_gcd_and_lcm_both_non_zero():
assert gcd_and_lcm(15, 25) == (5, 75)
assert gcd_and_lcm(18, 24) == (6, 72)
assert gcd_and_lcm(21, 14) == (7, 42)
def test_gcd_and_lcm_one_zero():
assert gcd_and_lcm(0, 10) == (10, 0)
assert gcd_and_lcm(20, 0) == (20, 0)
... | [
{
"docstring": "Returns the Greatest Common Divisor (GCD) of integers a and b using the Euclidean Algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the Greatest Common Divisor and Least Common Multiple of 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": "def gcd_and_lcm(a: int, b: int) -> (int, int):\n \"\"\"\n Computes the Greatest Common Divisor and Least Common Multiple of integers a and b.\n\n Arg... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027899",
"row_id": 27899,
"seed_ids": "[166]"
} | 0.768237 | Data_Structure_27899 | I | [
"gcd",
"gcd_and_lcm"
] | 2 | [
[
"gcd_and_lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2b1d00089459300b2ec9a6b655c60e3114dcba50 | edd47bb9bb49a4c6d0f4566d52cb9faf4e2e4aca | |||
v1.0 | instruct | Data_Structure | Data_Structure_27931_I | ### Diffie-Hellman and Primality Utility Implementation
In this exercise, you will enhance the provided Diffie-Hellman Key Exchange implementation along with accompanying mathematical utilities. The purpose is to assess your understanding of both cryptographic protocols and fundamental mathematical computations.
####... | from typing import List, Optional
import math
def prime_check(num: int) -> bool:
"""
Checks if a given 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 %... | import pytest
from solution import prime_check, find_order, euler_totient, find_primitive_root, diffie_hellman_key_exchange
def test_prime_check():
assert prime_check(7) == True
assert prime_check(18) == False
assert prime_check(1) == False
assert prime_check(2) == True
def test_find_order():
asse... | [
{
"docstring": "Checks if a given number is prime.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Finds the order of element 'a' modulo 'n'.",
"function_declaration": "def find_order(a, n):",
"function_n... | [
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef prime_check(num: int) -> bool:\n \"\"\"\n Checks if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if nu... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00027931",
"row_id": 27931,
"seed_ids": "[146]"
} | 0.533577 | Data_Structure_27931 | I | [
"prime_check",
"find_order",
"euler_totient",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 5 | [
[
"diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"diffie_hellman_key_exchange",
"prime_check"
],
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"prime_check"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 9053aa66e199574ea8c5dd993bf95d30b36f698e | 3b71e08bdca37921d0075965cf36907263b96d50 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27950_I | You are provided with a function for generating prime numbers less than a given integer \( n \) using a modified version of the Sieve of Eratosthenes algorithm. Your task is to extend this functionality in the following ways:
1. **Prime Count**: Write a function `count_primes(n)` which uses `get_primes(n)` and returns... | def get_primes(n):
"""
Return a list of all prime numbers less than n
"""
if n <= 2:
return []
sieve = [True] * n
sieve[0] = sieve[1] = False
for start in range(2, int(n**0.5) + 1):
if sieve[start]:
for i in range(start*start, n, start):
sieve[i]... | from solution import count_primes, sum_primes
def test_count_primes():
assert count_primes(10) == 4 # primes: [2, 3, 5, 7]
assert count_primes(20) == 8 # primes: [2, 3, 5, 7, 11, 13, 17, 19]
assert count_primes(2) == 0 # primes: []
assert count_primes(50) == 15 # primes: [2, 3, 5, 7, 11, 13, 17, 19... | [
{
"docstring": "Return a list of all prime numbers less than n",
"function_declaration": "def get_primes(n):",
"function_name": "get_primes",
"parameter_list": "(n)"
},
{
"docstring": "Returns the count of prime numbers less than n",
"function_declaration": "def count_primes(n):",
"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": "def get_primes(n):\n \"\"\"\n Returns a list of prime numbers less than n using the Sieve of Eratosthenes algorithm.\n \"\"\"\n is_prime = [True] ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027950",
"row_id": 27950,
"seed_ids": "[133]"
} | 0.754547 | Data_Structure_27950 | I | [
"get_primes",
"count_primes",
"sum_primes"
] | 3 | [
[
"count_primes",
"get_primes"
],
[
"sum_primes",
"get_primes"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6b52b354571a40d9c5c0e20e5dedfecbf84c5cdf | 64422b3342e80c1195071543124ac318d69fbe25 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28003_I | ### Merge Sort Implementation
Given an array of integers, implement the Merge Sort algorithm to sort the array in non-decreasing order.
#### Function Signature
```python
def merge_sort(arr: List[int]) -> List[int]:
```
#### Input
- `arr`: A list of integers (1 <= len(arr) <= 10^5), where each integer fits within th... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Merge Sort implementation that sorts an array in non-decreasing order.
"""
# Base case: a list of zero or one elements is already sorted
if len(arr) <= 1:
return arr
# Recursive case: split the list into two subli... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_multiple_elements():
assert merge_sort([34, 7, 23, 32, 5, 62]) == [5, 7, 23, 32, 34, 62]
assert merge_sort([2, 3, 5, 5, 7, 7... | [
{
"docstring": "Merge Sort implementation that sorts an array in non-decreasing order.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into one sorted list.",
"function_declaration": "de... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n # Find the middle point\n mid... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028003",
"row_id": 28003,
"seed_ids": "[12]"
} | 0.675071 | Data_Structure_28003 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9a43b9398f4ed8e272be5c75374370d1efbc8258 | dbb9c5a8acc4166def54958611e58888b5d22497 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28004_I | ### Binary Tree Construction and Inorder Traversal
Given two arrays representing the preorder and postorder traversal of a full binary tree, write a function to construct the binary tree and return its inorder traversal as a list.
A full binary tree has the property that every node has either 0 or 2 children.
### In... | from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(preorder, postorder):
"""
Helper function to build the binary tree.
"""
if not preorder or not postorder:
retu... | import pytest
from solution import binary_tree_inorder
def test_example_1():
preorder = [1, 2, 4, 8, 9, 5, 3, 6, 7]
postorder = [8, 9, 4, 5, 2, 6, 7, 3, 1]
expected = [8, 4, 9, 2, 5, 1, 6, 3, 7]
assert binary_tree_inorder(preorder, postorder) == expected
def test_example_2():
preorder = [1, 2, 3]
... | [] | [
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\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n s... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00028004",
"row_id": 28004,
"seed_ids": "[300]"
} | 0.552074 | Data_Structure_28004 | I | [
"build_tree",
"inorder_traversal",
"binary_tree_inorder"
] | 3 | [
[
"binary_tree_inorder",
"build_tree"
],
[
"binary_tree_inorder",
"inorder_traversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | f50f8b76c6e3ea13667d9a20d43445547486f119 | ab669602500acf330534c9ef78b482294ff7f284 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28036_I | You are given an unsorted list of integers and your task is to implement the insertion sort algorithm to sort the list in ascending order. However, instead of performing a linear search to find the correct position for an element, you are to use the provided `search_insert` function that uses binary search to find the ... | from typing import List
def search_insert(array: List[int], value: int, start: int, end: int) -> int:
"""
Uses binary search to find the index where value should be inserted to keep the array sorted between start and end.
"""
while start < end:
mid = (start + end) // 2
if array[mid] < v... | from solution import insertion_sort
def test_insertion_sort_example1():
assert insertion_sort([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12]
def test_insertion_sort_empty():
assert insertion_sort([]) == []
def test_insertion_sort_all_identical():
assert insertion_sort([1, 1, 1, 1, 1]) == [1, 1... | [
{
"docstring": "Uses binary search to find the index where value should be inserted to keep the array sorted between start and end.",
"function_declaration": "def search_insert(array, value, start, end):",
"function_name": "search_insert",
"parameter_list": "(array, value, start, end)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], value: int) -> int:\n \"\"\"\n Searches for the insert index for 'value' using binary sea... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028036",
"row_id": 28036,
"seed_ids": "[199]"
} | 0.583352 | Data_Structure_28036 | I | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d1cf065d8e6721a563f05cc8497d589650be5408 | 8973b1f4bf2695e661debe755bd6d7b046c1be8a | |||
v1.0 | instruct | Data_Structure | Data_Structure_28056_I | ### Question: Efficient Insertion Sort Implementation
You are tasked with implementing the insertion sort algorithm for a list of integers, but with a twist: instead of using a linear search to find the position where a new element should be inserted, you will use binary search as outlined in the provided code snippet... | from typing import List
def search_insert(arr: List[int], value: int, hi: int) -> int:
lo = 0
while lo < hi:
mid = (lo + hi) // 2
if arr[mid] < value:
lo = mid + 1
else:
hi = mid
return lo
def insertion_sort(arr: List[int]) -> None:
for i in range(1, len... | from solution import insertion_sort
def test_insertion_sort_sorted_list():
arr = [1, 2, 3, 4, 5]
insertion_sort(arr)
assert arr == [1, 2, 3, 4, 5]
def test_insertion_sort_reverse_sorted_list():
arr = [5, 4, 3, 2, 1]
insertion_sort(arr)
assert arr == [1, 2, 3, 4, 5]
def test_insertion_sort_ran... | [
{
"docstring": null,
"function_declaration": "def search_insert(arr, value, hi):",
"function_name": "search_insert",
"parameter_list": "(arr, value, hi)"
},
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(arr: List[int], left: int, right: int, key: int) -> int:\n while left < right:\n mid = (left + right) /... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028056",
"row_id": 28056,
"seed_ids": "[199]"
} | 0.566644 | Data_Structure_28056 | I | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d6f9d223d7587df37ad71d46501990c960049f83 | f369393ecfa37e5bbd5b00939651a44ad927b450 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28067_I | ### Bucket Sort Implementation Challenge
#### Objective:
Implement the Bucket Sort algorithm to effectively sort a given list of floating-point numbers.
#### Problem Statement:
You are given a list of floating-point numbers \(arr\) where each element is uniformly distributed in the range [0, 1). Sort the list using t... | from typing import List
def insertion_sort(arr: List[float]) -> List[float]:
"""
A helper function to perform insertion sort on a list.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
... | from solution import bucket_sort
def test_bucket_sort_example():
assert bucket_sort([0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]) == [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
def test_bucket_sort_empty():
assert bucket_sort([]) == []
def test_bucket_sort_single_element():
... | [
{
"docstring": "A helper function to perform insertion sort on a list.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Perform bucket sort on a list of floating-point numbers in the range [0, 1).",
"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": "from typing import List\n\ndef insertion_sort(bucket):\n \"\"\"\n Sorts a bucket using insertion sort.\n \"\"\"\n for i in range(1, len(bucket)):\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028067",
"row_id": 28067,
"seed_ids": "[26]"
} | 0.54605 | Data_Structure_28067 | I | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d1f399b092a4a8edff9e07517684dab9ae23bb4c | bd7e1e031c01c4ac819358b732affd69fee85a1a | |||
v1.0 | instruct | Data_Structure | Data_Structure_28070_I | You are tasked with implementing a function that computes the **Least Common Multiple (LCM)** of two non-negative integers using the **Greatest Common Divisor (GCD)** algorithm, but with bitwise operations for efficiency.
Write a function `efficient_lcm(a, b)` that takes two non-negative integers `a` and `b`, and ret... | def gcd(a: int, b: int) -> int:
while b != 0:
a, b = b, a % b
return a
def efficient_lcm(a: int, b: int) -> int:
if a == 0 or b == 0:
return 0
return (a * b) // gcd(a, b) | from solution import efficient_lcm, gcd
def test_gcd():
assert gcd(12, 18) == 6
assert gcd(7, 5) == 1
assert gcd(0, 5) == 5
assert gcd(10, 0) == 10
assert gcd(48, 18) == 6
assert gcd(20, 5) == 5
def test_efficient_lcm():
assert efficient_lcm(12, 18) == 36
assert efficient_lcm(0, 5) == ... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def efficient_lcm(a, b):",
"function_name": "efficient_lcm",
"parameter_list": "(a, b)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def efficient_lcm(a: int, b: int) -> int:\n def gcd(x, y):\n while y:\n x, y = y, x % y\n return x\n\n if a == 0 or b == 0:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00028070",
"row_id": 28070,
"seed_ids": "[166]"
} | 0.640912 | Data_Structure_28070 | I | [
"gcd",
"efficient_lcm"
] | 2 | [
[
"efficient_lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3a3980aba2291401f022e3f5d163932a00a5b9ce | 1fa3c88199684820d15b8750e6a2b17805df05c1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28087_I | **Matrix Inversion Challenge**
You are tasked with implementing an algorithm to compute the inverse of a given n x n matrix. This problem will assess your understanding of matrix operations, recursive determinant calculation, and optimization of matrix traversals.
### Problem Statement
Write a function `invert_matrix... | def get_matrix_minor(matrix, row, col):
return [r[:col] + r[col+1:] for r in (matrix[:row] + matrix[row+1:])]
def get_matrix_determinant(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 +... | from solution import invert_matrix
def test_valid_2x2_matrix():
matrix = [
[4, 7],
[2, 6]
]
expected = [
[0.6, -0.7],
[-0.2, 0.4]
]
result = invert_matrix(matrix)
assert result == expected
def test_not_a_matrix():
result = invert_matrix(123)
assert resu... | [
{
"docstring": null,
"function_declaration": "def get_matrix_minor(matrix, row, col):",
"function_name": "get_matrix_minor",
"parameter_list": "(matrix, row, col)"
},
{
"docstring": null,
"function_declaration": "def get_matrix_determinant(matrix):",
"function_name": "get_matrix_dete... | [
0,
0,
0,
0,
1,
0,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def invert_matrix(matrix):\n def determinant(m):\n # Base cases for 2x2 matrix\n if len(m) == 2:\n return m[0][0] * m[1][1] - m[0]... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00028087",
"row_id": 28087,
"seed_ids": "[347]"
} | 0.589971 | Data_Structure_28087 | I | [
"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 | c51b6851ad9a4c1f161befa0345ae40571bbae03 | a724ecf5fe0453d57d762c531266b44cc0c92a31 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28091_I | ### Bit Manipulation Enhanced Function
In this task, you will use the basic bit manipulation operations to create a more complex function. This function should take an integer `num` and a list of tuples `operations`, where each tuple contains three values indicating the type of operation (get, set, clear, or update), t... | def get_bit(num, pos):
"""
Return 1 if the bit at 'pos' is set (1), otherwise return 0.
"""
return (num >> pos) & 1
def set_bit(num, pos):
"""
Return an integer with the bit at 'pos' set to 1.
"""
return num | (1 << pos)
def clear_bit(num, pos):
"""
Return an integer with the b... | def test_get_operations():
num = 29 # Binary: 11101
operations = [
('get', 0, 0), # Should return 1
('get', 2, 0), # Should return 1
('get', 3, 0), # Should return 1
('get', 4, 0), # Should return 1
('get', 5, 0) # Should return 0 (out of range but logically 0... | [
{
"docstring": "Return 1 if the bit at 'pos' is set (1), otherwise return 0.",
"function_declaration": "def get_bit(num, pos):",
"function_name": "get_bit",
"parameter_list": "(num, pos)"
},
{
"docstring": "Return an integer with the bit at 'pos' set to 1.",
"function_declaration": "def ... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def process_bits(num: int, operations: list[tuple[str, int, int]]) -> list[int]:\n def get_bit(num, bit_position):\n return (num >> bit_position) & ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028091",
"row_id": 28091,
"seed_ids": "[212]"
} | 0.684866 | Data_Structure_28091 | I | [
"get_bit",
"set_bit",
"clear_bit",
"update_bit",
"process_bits"
] | 5 | [
[
"process_bits",
"clear_bit"
],
[
"process_bits",
"get_bit"
],
[
"process_bits",
"set_bit"
],
[
"process_bits",
"update_bit"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 3b29a0222eb55eceda5296229a920853e3ae45fc | d1d30a70860ced5b72ae6df5e8ae0c33e260d2aa | |||
v1.0 | instruct | Data_Structure | Data_Structure_28186_I | ### Coding Assessment: Maximum Flow in a Network
#### Scenario:
You are given a directed graph representing a simplified model of a city's traffic network, where intersections are represented as nodes and roads as edges with specific capacity limits (the maximum number of vehicles that can traverse a road). Your task ... | from collections import deque
from typing import List
def bfs(rGraph, s, t, parent):
visited = [False] * len(rGraph)
queue = deque([s])
visited[s] = True
while queue:
u = queue.popleft()
for ind, val in enumerate(rGraph[u]):
if visited[ind] == False and val > 0:
... | import pytest
from solution import compute_maximum_flow
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 compute_maximum_flow(graph) == 23
... | [
{
"docstring": null,
"function_declaration": "def bfs(rGraph, s, t, parent):",
"function_name": "bfs",
"parameter_list": "(rGraph, s, t, parent)"
},
{
"docstring": null,
"function_declaration": "def compute_maximum_flow(adjacency_matrix):",
"function_name": "compute_maximum_flow",
... | [
0,
0,
0,
0,
1,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(rGraph, s, t, parent):\n visited = [False] * len(rGraph)\n queue = deque()\n \n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00028186",
"row_id": 28186,
"seed_ids": "[229]"
} | 0.623732 | Data_Structure_28186 | I | [
"bfs",
"compute_maximum_flow"
] | 2 | [
[
"compute_maximum_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5c9f0a546f5355f57522afa04286d5f60752dcc0 | 633809381f610501f60aa7d37d3446b27f3c9130 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28203_I | ### Problem Description
Implement a function `optimized_insertion_sort` that sorts an array using the Insertion Sort algorithm. In this implementation, you should optimize the sorting process by using binary search to find the position where the current element should be inserted. This optimization should help in redu... | def binary_search(arr, val, start, end):
if start == end:
if arr[start] > val:
return start
else:
return start + 1
if start > end:
return start
mid = (start + end) // 2
if arr[mid] < val:
return binary_search(arr, val, mid + 1, end)
elif arr[m... | from solution import optimized_insertion_sort
def test_optimized_insertion_sort():
# Test with a general case
assert optimized_insertion_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
# Test with an empty list
assert optimized_insertion_sort([]) == []
# Test with a single element list
ass... | [
{
"docstring": null,
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": null,
"function_declaration": "def optimized_insertion_sort(arr):",
"function_name": "optimized_inse... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binary_search(arr, val, start, end):\n \"\"\"\n Helper function to perform a binary search for inserting an element.\n \"\"\"\n if start == en... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028203",
"row_id": 28203,
"seed_ids": "[7]"
} | 0.648639 | Data_Structure_28203 | I | [
"binary_search",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9297d92b2221ff596f46286386a15908eee68220 | b3acd5357b300b76e89e14e6ea901dc9955a2834 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28206_I | **Network Maximum Flow**
Network flow problems are commonly encountered in various fields and require precise calculation of the maximum possible flow from a source to a sink in a given network. You are provided with the code implementations of three maximum flow algorithms: Ford-Fulkerson, Edmonds-Karp, and Dinic's a... | from collections import deque
def ford_fulkerson(capacity, source, sink):
n = len(capacity)
flow = 0
parent = [-1] * n
def bfs(s, t):
visited = [False] * n
queue = deque([s])
visited[s] = True
while queue:
u = queue.popleft()
for v in range(n):
... | import pytest
from solution import network_max_flow
def test_network_max_flow_ford_fulkerson():
capacity = [
[0, 16, 13, 0, 0, 0],
[16, 0, 10, 12, 0, 0],
[13, 4, 0, 0, 14, 0],
[0, 12, 9, 0, 0, 20],
[0, 0, 14, 7, 0, 4],
[0, 0, 0, 20, 4, 0]
]
assert network_max... | [
{
"docstring": null,
"function_declaration": "def ford_fulkerson(capacity, source, sink):",
"function_name": "ford_fulkerson",
"parameter_list": "(capacity, source, sink)"
},
{
"docstring": null,
"function_declaration": "def edmonds_karp(capacity, source, sink):",
"function_name": "e... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\n# Ford-Fulkerson Algorithm using Depth First Search (DFS)\ndef ford_fulkerson(capacity, source, sink):\n n = len(capacity)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028206",
"row_id": 28206,
"seed_ids": "[240]"
} | 0.568983 | Data_Structure_28206 | I | [
"ford_fulkerson",
"edmonds_karp",
"dinic",
"network_max_flow"
] | 4 | [
[
"network_max_flow",
"dinic"
],
[
"network_max_flow",
"edmonds_karp"
],
[
"network_max_flow",
"ford_fulkerson"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 0676ef88d7676c85a1b5e4e7835917f388f1b143 | 24a3a8c07f18a946685505b05601757fcbb79746 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28215_I | ### Radix Sort Implementation and Analysis
#### Scenario
You are tasked with writing an efficient sorting algorithm for a large finance application. The input consists of millions of records, each identified by a unique transaction ID, which is a non-negative integer.
#### Task
Implement the Radix Sort algorithm to s... | from typing import List
def counting_sort_for_radix(arr, exp, simulation=False):
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]
for i in range(n... | from solution import radix_sort
def test_radix_sort_basics():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
assert radix_sort([5, 2, 2, 8, 3]) == [2, 2, 3, 5, 8]
assert radix_sort([]) == []
assert radix_sort([123456789]) == [123456789]
def test_radix_sort_ed... | [
{
"docstring": null,
"function_declaration": "def counting_sort_for_radix(arr, exp, simulation=False):",
"function_name": "counting_sort_for_radix",
"parameter_list": "(arr, exp, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort_for_radix(arr, exp, simulation=False):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \n f... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00028215",
"row_id": 28215,
"seed_ids": "[15]"
} | 0.623577 | Data_Structure_28215 | I | [
"counting_sort_for_radix",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort_for_radix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 963f9b460c87a9dafc2c328dfab07aa7f6a62ad3 | 92c212765bbcf6ff1aa0fecf4a651cd23b6c7793 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28222_I | ### Scenario
You are working on an e-commerce platform where you need to process a list of product prices for sorting in ascending order. You have learned about Heap Sort and are tasked to implement both Max-Heap Sort and Min-Heap Sort for this purpose.
### Problem Statement
Your task is to implement the heap sort al... | def max_heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
... | def test_heap_sorts():
# Test array
arr1 = [10, 5, 3, 15, 8]
arr2 = [7, 14, 2, 18, 4, 11]
arr3 = [-3, -5, -10, -2, -4]
arr4 = [3, 1, 2, 3, 1, 2]
arr5 = [1]
# Expected results
sorted1 = [3, 5, 8, 10, 15]
sorted2 = [2, 4, 7, 11, 14, 18]
sorted3 = [-10, -5, -4, -3, -2]
sort... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": null,
"function_declaration": "def max_heap_sort(arr):",
"function_name": "max_heap_sort",
"parameter_list": "(arr)"
},
... | [
0,
0,
0,
1,
0,
1,
1,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_heapify(arr, n, i):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n and arr[left] > arr[largest]:\n largest = ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00028222",
"row_id": 28222,
"seed_ids": "[8]"
} | 0.654167 | Data_Structure_28222 | I | [
"max_heapify",
"max_heap_sort",
"min_heapify",
"min_heap_sort"
] | 4 | [
[
"max_heap_sort",
"max_heapify"
],
[
"min_heap_sort",
"min_heapify"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 8058532c8116d7173904de4ab91af203625e561c | 3509245a21f99c261e98ee01493f3a272f96a368 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28316_I | ### Question
Alice and Bob want to securely share a secret key using the Diffie-Hellman key exchange algorithm. You are provided with the following functions to help you build the system:
1. `prime_check(num)`: Checks if a number is a prime.
2. `find_primitive_root(n)`: Finds all primitive roots of a given number `n`.
... | import random
def prime_check(num):
"""
Check if a number is a 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 ... | from solution import secure_key_exchange, prime_check, find_primitive_root
def test_secure_key_exchange_valid():
result = secure_key_exchange(2, 11)
assert isinstance(result, tuple)
assert len(result) == 2
assert result[0] == result[1]
def test_secure_key_exchange_invalid_p():
result = secure_key_... | [
{
"docstring": "Check if a number is a prime.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Calculates Euler's totient function of n.",
"function_declaration": "def euler_totient(n):",
"function_name": ... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef prime_check(num):\n \"\"\"\n Check if a number is a prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00028316",
"row_id": 28316,
"seed_ids": "[146]"
} | 0.489472 | Data_Structure_28316 | I | [
"prime_check",
"euler_totient",
"find_primitive_root",
"secure_key_exchange"
] | 4 | [
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"prime_check"
],
[
"secure_key_exchange",
"find_primitive_root"
],
[
"secure_key_exchange",
"prime_check"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | c18420836adcf41033d4bb172ff359e11a7740c2 | 46ee551cfee72d25ceebf17389b5e3a8754baeca | |||
v1.0 | instruct | Data_Structure | Data_Structure_28337_I | #### Context
You are tasked with implementing and enhancing an existing algorithm, the Exchange Sort. However, given its inefficiency for large datasets, your goal is to adapt or combine it with another efficient sorting algorithm.
#### Requirements
Write two functions:
1. **exchange_sort**: Enhance the provided Excha... | def exchange_sort(arr):
"""
Exchanges elements to sort the array.
"""
n = len(arr)
for i in range(n - 1):
for j in range(i + 1, n):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr
def merge_sort(arr):
"""
Implements merge sort algorithm... | from solution import exchange_sort, merge_sort, hybrid_sort
def test_exchange_sort_empty_array():
assert exchange_sort([]) == []
def test_exchange_sort_single_element():
assert exchange_sort([5]) == [5]
def test_exchange_sort_sorted_array():
assert exchange_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def t... | [
{
"docstring": "Exchanges elements to sort the array.",
"function_declaration": "def exchange_sort(arr):",
"function_name": "exchange_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Implements merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def exchange_sort(arr):\n n = len(arr)\n for i in range(n-1):\n for j in range(i+1, n):\n if arr[i] > arr[j]:\n arr[i],... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00028337",
"row_id": 28337,
"seed_ids": "[28]"
} | 0.523741 | Data_Structure_28337 | I | [
"exchange_sort",
"merge_sort",
"hybrid_sort"
] | 3 | [
[
"hybrid_sort",
"exchange_sort"
],
[
"hybrid_sort",
"merge_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0ef9cddf3752815d7f5a850fb9c9e7ae6f0c7b1c | 337c891aa2cfeb6183caf4d8c06a1fdb1a5fec25 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28392_I | **Question**:
### Context
In certain applications like data serialization and graphics, it is common to reconstruct data structures from their traversal outputs. One such problem is reconstructing a full binary tree from its preorder and postorder traversal outputs.
### Task
Given arrays representing the preorder and... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def construct_tree_helper(pre, post, pre_start, pre_end, post_start, post_end, post_map):
if pre_start > pre_end or post_start > post_end:
return None
root = TreeNode(pre[pre_start])
i... | from solution import construct_tree
def test_construct_tree_simple():
pre = [1, 2, 3]
post = [2, 3, 1]
assert construct_tree(pre, post) == [2, 1, 3]
def test_construct_tree_full_binary():
pre = [1, 2, 4, 5, 3, 6, 7]
post = [4, 5, 2, 6, 7, 3, 1]
assert construct_tree(pre, post) == [4, 2, 5, 1, ... | [] | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n \"\"\"Definition for a binary tree node.\"\"\"\n def __init__(self, x):\n self.val = x\n self.left = None\n self.... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00028392",
"row_id": 28392,
"seed_ids": "[300]"
} | 0.594144 | Data_Structure_28392 | I | [
"construct_tree_helper",
"inorder_traversal",
"construct_tree"
] | 3 | [
[
"construct_tree",
"construct_tree_helper"
],
[
"construct_tree",
"inorder_traversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 7b5463eafeea25ec0d0f6eea7b2f7ec3e35ab850 | 92e16848af0c9aa4d9d00d83b3bd81fa08b930de | |||
v1.0 | instruct | Data_Structure | Data_Structure_28404_I | #### Scenario
You are tasked with building a library that efficiently handles calculations for mathematical properties and relationships involving integers. The core functions include computing the greatest common divisor (GCD) using both iterative and bitwise methods, least common multiple (LCM), and counting the numb... | def improved_gcd(a: int, b: int) -> int:
""" Compute the greatest common divisor using Euclid's algorithm. """
if a <= 0 or b <= 0:
raise ValueError('Both inputs must be positive integers.')
while b:
a, b = b, a % b
return a
def efficient_lcm(a: int, b: int) -> int:
""" Compute the ... | from solution import improved_gcd, efficient_lcm, trailing_zero_count, gcd_with_bitwise
def test_improved_gcd():
assert improved_gcd(25, 15) == 5
assert improved_gcd(48, 18) == 6
try:
improved_gcd(-1, 15)
except ValueError as e:
assert str(e) == 'Both inputs must be positive integers.'
... | [
{
"docstring": "Compute the greatest common divisor using Euclid's algorithm. ",
"function_declaration": "def improved_gcd(a, b):",
"function_name": "improved_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Compute the least common multiple using the GCD function. ",
"function_declar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def improved_gcd(a: int, b: int) -> int:\n \"\"\" Compute the greatest common divisor using Euclid's algorithm. \"\"\"\n if a <= 0 or b <= 0:\n r... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00028404",
"row_id": 28404,
"seed_ids": "[166]"
} | 0.599867 | Data_Structure_28404 | I | [
"improved_gcd",
"efficient_lcm",
"trailing_zero_count",
"gcd_with_bitwise",
"__builtin_ctz"
] | 5 | [
[
"efficient_lcm",
"improved_gcd"
],
[
"gcd_with_bitwise",
"__builtin_ctz"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8772b0573e02f9308fcfd91c951ee4b3f8d8826a | c9a7f7135905f4914429cf11eaba6434ea87779f | |||
v1.0 | instruct | Data_Structure | Data_Structure_28505_I | ### Factorial Calculation with Extended Functionality
#### Scenario
A researcher working with large numbers in combinatorial problems frequently needs to compute factorials. However, due to the size of the numbers, the results often need to be taken modulo a specific value to avoid overflow. You are asked to implement... | def custom_factorial(n: int, approach: str, mod: int = None) -> int:
if not isinstance(n, int) or n < 0:
raise ValueError("n must be a non-negative integer.")
if mod is not None and (not isinstance(mod, int) or mod <= 0):
raise ValueError("mod must be a positive integer.")
if appro... | from solution import custom_factorial
def test_custom_factorial_iterative():
assert custom_factorial(5, "iterative") == 120
def test_custom_factorial_recursive():
assert custom_factorial(5, "recursive") == 120
def test_custom_factorial_iterative_with_mod():
assert custom_factorial(5, "iterative", 3) == 0... | [
{
"docstring": null,
"function_declaration": "def custom_factorial(n, approach, mod=None):",
"function_name": "custom_factorial",
"parameter_list": "(n, approach, mod=None)"
},
{
"docstring": null,
"function_declaration": "def _factorial_iterative(n, mod=None):",
"function_name": "_f... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def custom_factorial(n: int, approach: str, mod: int = None) -> int:\n # Auxiliary function for iterative calculation\n def iterative_factorial(n, mod):... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028505",
"row_id": 28505,
"seed_ids": "[139]"
} | 0.665118 | Data_Structure_28505 | I | [
"custom_factorial",
"_factorial_iterative",
"_factorial_recursive"
] | 3 | [
[
"custom_factorial",
"_factorial_iterative"
],
[
"custom_factorial",
"_factorial_recursive"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fdda0f5295ef70cfb849e8a5de9ecbc1aa30788a | 67a61162dc3d4a9aa5cab0f3675d19b51f84f364 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28514_I | ### Bucket Sort Implementation
#### Scenario
Imagine you have been given an array of floating-point numbers between 0 and 1, and you need to sort these numbers. The values are assumed to be uniformly distributed.
### Task
Implement a function `bucket_sort_floats` that performs the bucket sort, utilizing the provided ... | def bucket_sort_floats(arr):
''' Bucket Sort for floating point numbers between 0 and 1 '''
num_buckets = len(arr)
if num_buckets <= 1:
return arr
buckets = [[] for _ in range(num_buckets)]
for value in arr:
index = int(value * num_buckets)
buckets[index].append(value)
so... | from solution import bucket_sort_floats
def test_bucket_sort_floats_basic():
assert bucket_sort_floats([0.34, 0.23, 0.55, 0.14, 0.95]) == [0.14, 0.23, 0.34, 0.55, 0.95]
def test_bucket_sort_floats_duplicates():
assert bucket_sort_floats([0.5, 0.5, 0.5, 0.5]) == [0.5, 0.5, 0.5, 0.5]
def test_bucket_sort_float... | [
{
"docstring": "Bucket Sort for floating point numbers between 0 and 1 ",
"function_declaration": "def bucket_sort_floats(arr):",
"function_name": "bucket_sort_floats",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def next_sort(arr):",
"function_name": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bucket_sort_floats(arr):\n ''' Bucket Sort for floating point numbers between 0 and 1 '''\n if not arr:\n return []\n \n num_buckets = ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00028514",
"row_id": 28514,
"seed_ids": "[26]"
} | 0.567641 | Data_Structure_28514 | I | [
"bucket_sort_floats",
"next_sort"
] | 2 | [
[
"bucket_sort_floats",
"next_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 64f968431ce2f609f6536998f58ec200bef9aece | 70d9de46bc364a11b9415ce125b2b7388145d36a | |||
v1.0 | instruct | Data_Structure | Data_Structure_28516_I | ### Coding Challenge: Bogo Sort Simulation and Alternatives
#### Context
You are tasked with implementing an inefficient, theoretical algorithm called Bogo Sort. This is mainly for educational purposes to understand why certain algorithms are impractical. In the real world, we would never use Bogo Sort due to its extr... | import random
import time
def is_sorted(arr):
"""
Helper function to check if 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):
"""
This function sorts an array using Bogo Sort algor... | from solution import bogo_sort, compare_sorts
def test_bogo_sort_already_sorted():
assert bogo_sort([1, 2, 3], simulation=False) == [1, 2, 3]
def test_bogo_sort_reverse_order():
assert bogo_sort([3, 2, 1], simulation=False) == [1, 2, 3]
def test_bogo_sort_random_order():
arr = [2, 3, 1]
sorted_arr = ... | [
{
"docstring": "Helper function to check if array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "This function sorts an array using Bogo Sort algorithm with an option for simulation.\n\n:param arr: List[i... | [
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\nimport time\n\ndef is_sorted(arr):\n \"\"\"\n Check if the array is sorted.\n \"\"\"\n for i in range(len(arr) - 1):\n if ar... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00028516",
"row_id": 28516,
"seed_ids": "[16]"
} | 0.522205 | Data_Structure_28516 | I | [
"is_sorted",
"bogo_sort",
"compare_sorts"
] | 3 | [
[
"bogo_sort",
"is_sorted"
],
[
"compare_sorts",
"bogo_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 804e2f00f7993d1c0a7cd7f7ef6ae31c7089c48d | 0d9f4b1c9a4b9341d4333da0dc6785c12bc61eca | |||
v1.0 | instruct | Data_Structure | Data_Structure_28523_I | You are tasked with implementing a function for a binary search tree (BST). The function will insert a list of values into a BST and then perform an in-order traversal to produce a sorted list of the values.
### Requirements
1. Implement a function `insert_into_bst(root, val)` to insert a new value into the BST.
2. Im... | class TreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
def insert_into_bst(root: TreeNode, val: int) -> TreeNode:
"""
Inserts a value into the BST and returns the root of the tree.
If the tree is empty, it creates a new root.
"""
if ... | from solution import TreeNode, insert_into_bst, in_order_traversal, construct_bst_from_list
def test_insert_into_bst():
root = insert_into_bst(None, 10)
assert root.val == 10
root = insert_into_bst(root, 5)
root = insert_into_bst(root, 15)
root = insert_into_bst(root, 3)
root = insert_into_bst(... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0):\n self.val = val\n self.left = None\n self.right = None\n\ndef insert_into_bst(root: Tree... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028523",
"row_id": 28523,
"seed_ids": "[287]"
} | 0.53599 | Data_Structure_28523 | I | [
"insert_into_bst",
"in_order_traversal",
"construct_bst_from_list"
] | 3 | [
[
"construct_bst_from_list",
"in_order_traversal"
],
[
"construct_bst_from_list",
"insert_into_bst"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 62a1a99cf69ed29f12ed59382d42a4d14a916054 | 8e7da81c8ca691cbf4b803580ea14c08ff1a628f | |||
v1.0 | instruct | Data_Structure | Data_Structure_28559_I | ### Coding Assessment Task
**Scenario**:
You are a software engineer working on a system where you need to sort a large set of floating-point numbers that are mostly well distributed. To ensure efficient sorting, you decide to implement the Bucket Sort algorithm.
**Task**:
Implement the Bucket Sort algorithm to sort ... | from typing import List
def bucket_sort(arr: List[float]) -> List[float]:
n = len(arr)
if n == 0:
return arr
# Create buckets
buckets = [[] for _ in range(n)]
# Distribute input array values into buckets
for num in arr:
index = int(num * n)
buckets[index].appen... | from solution import bucket_sort
def test_bucket_sort_with_example():
arr = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]
expected = [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
assert bucket_sort(arr) == expected
def test_bucket_sort_empty_array():
arr = []
expected... | [
{
"docstring": null,
"function_declaration": "def bucket_sort(arr):",
"function_name": "bucket_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[float]) -> List[float]:\n \"\"\"\n Sorts a list using the insertion sort algorithm.\n \"\"\"\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028559",
"row_id": 28559,
"seed_ids": "[26]"
} | 0.537126 | Data_Structure_28559 | I | [
"bucket_sort",
"insertion_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | de6da020ab575f6b67258351f10b089dc9cf5352 | 9d9ce065eddbb17d5b386e646d518e0f2b293509 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28635_I | ### Context:
You are assigned to optimize the processing of large datasets of non-negative integers. To this end, you have decided to implement the Radix Sort, a non-comparative sorting algorithm known for its efficiency with certain datasets.
### Question:
Implement a function `optimized_radix_sort` to sort an array ... | from typing import List
def optimized_radix_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of non-negative integers using the radix sort algorithm.
"""
if not arr: # Early exit for empty array
return arr
# Find the maximum number to know number of digits
max_val = max(arr)
... | from solution import optimized_radix_sort
def test_empty_array():
assert optimized_radix_sort([]) == []
def test_single_element():
assert optimized_radix_sort([5]) == [5]
def test_multiple_elements():
assert optimized_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
... | [
{
"docstring": "Sorts a list of non-negative integers using the radix sort algorithm.",
"function_declaration": "def optimized_radix_sort(arr):",
"function_name": "optimized_radix_sort",
"parameter_list": "(arr)"
},
{
"docstring": "A function to do counting sort of arr[] according to the dig... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef optimized_radix_sort(arr: List[int]) -> List[int]:\n if not arr:\n return []\n\n # Get the maximum number to deter... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028635",
"row_id": 28635,
"seed_ids": "[15]"
} | 0.632771 | Data_Structure_28635 | I | [
"optimized_radix_sort",
"counting_sort"
] | 2 | [
[
"optimized_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ad43c809df77fbd07e3934a62df1b9da2bd84ce3 | a4321a3776d02c8f44e67bf5fecec660d7655ee6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28689_I | ### Question: Markov Chain Path Generator
You are given a Markov chain represented as a dictionary, where keys are states and values are dictionaries that map possible next states to their transition probabilities. Your task is to implement a function that generates a finite path through the Markov chain, starting fro... | import random
def generate_markov_path(chain, initial_state, steps):
"""
Generates a path through a Markov chain.
:param chain: dictionary where keys are states and values are dictionaries of transition probabilities.
:param initial_state: string representing the starting state.
:param steps: ... | import pytest
from solution import generate_markov_path
def test_generate_markov_path_basic():
chain = {
'A': {'A': 0.6, 'E': 0.4},
'E': {'A': 0.7, 'E': 0.3}
}
path = generate_markov_path(chain, 'A', 5)
assert len(path) == 6
assert path[0] == 'A'
def test_generate_markov_path_to_se... | [
{
"docstring": "Generates a path through a Markov chain.\n\n:param chain: dictionary where keys are states and values are dictionaries of transition probabilities.\n:param initial_state: string representing the starting state.\n:param steps: integer specifying the number of transitions.\n:return: list of states... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_markov_path(chain, initial_state, steps):\n \"\"\"\n Generates a path through a Markov chain.\n \n :param chain: dic... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00028689",
"row_id": 28689,
"seed_ids": "[232]"
} | 0.547746 | Data_Structure_28689 | I | [
"generate_markov_path",
"_choose_next_state"
] | 2 | [
[
"generate_markov_path",
"_choose_next_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b1c356b0d2f9dd77a7a15de5e91a9a661273ca5c | 8a9b866bdd394521a8134125920f24d1acc3e819 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28706_I | ### Sort Even Indexed Elements in Descending Order Using Merge Sort
**Problem Statement**:
Your task is to implement a function that sorts the elements at even indices in an array in descending order, while leaving the elements at odd indices unchanged. Use the Merge Sort algorithm for sorting.
**Function Signature*... | from typing import List
def merge_sort_desc(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort_desc(arr[:mid])
right = merge_sort_desc(arr[mid:])
return merge_desc(left, right)
def merge_desc(left: List[int], right: List[int]) -> List[int]:
... | def test_sort_even_indices_desc_all_even():
assert sort_even_indices_desc([10, 3, 2, 7, 6, 5, 4, 1]) == [10, 3, 6, 7, 4, 5, 2, 1]
def test_sort_even_indices_desc_empty():
assert sort_even_indices_desc([]) == []
def test_sort_even_indices_desc_single_element():
assert sort_even_indices_desc([5]) == [5]
de... | [
{
"docstring": null,
"function_declaration": "def merge_sort_desc(arr):",
"function_name": "merge_sort_desc",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge_desc(left, right):",
"function_name": "merge_desc",
"parameter_list": "(left, right)"... | [
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 merge_sort_desc(arr: List[int]) -> List[int]:\n if len(arr) > 1:\n mid = len(arr) // 2\n left_half = arr[:mid]... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028706",
"row_id": 28706,
"seed_ids": "[12]"
} | 0.772527 | Data_Structure_28706 | I | [
"merge_sort_desc",
"merge_desc",
"sort_even_indices_desc"
] | 3 | [
[
"merge_sort_desc",
"merge_desc"
],
[
"sort_even_indices_desc",
"merge_sort_desc"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 7b6c5d4b9b238c04b7600ccd1b31ad5272e26cec | b3b1539473c13dd39dc27ac1bf52e2691e870880 | |||
v1.0 | instruct | Data_Structure | Data_Structure_28902_I | ### Problem Description
You are provided with a number of utility functions dealing with integers that require efficient computation of specific quantities. Using the provided utility functions `gcd_bit`, `lcm`, and `trailing_zero`, solve the following problem:
#### Problem Statement
Given an array of positive integer... | from math import gcd
from functools import reduce
def gcd_bit(a, b):
"""
Computes the greatest common divisor using bitwise operations.
"""
if b == 0:
return a
return gcd_bit(b, a % b)
def lcm(a, b):
"""
Computes the least common multiple of a and b.
"""
return a * b // gcd... | from solution import gcd_bit, lcm, trailing_zero, gcd_of_list, lcm_of_list, compute_statistics
def test_gcd_bit():
assert gcd_bit(10, 20) == 10
assert gcd_bit(14, 28) == 14
assert gcd_bit(9, 28) == 1
def test_lcm():
assert lcm(10, 20) == 20
assert lcm(3, 7) == 21
assert lcm(6, 8) == 24
def te... | [
{
"docstring": "Computes the greatest common divisor using bitwise operations.",
"function_declaration": "def gcd_bit(a, b):",
"function_name": "gcd_bit",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the least common multiple of a and b.",
"function_declaration": "def lcm(a, b)... | [
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 math import gcd\nfrom functools import reduce\n\ndef gcd_bit(a, b):\n \"\"\"\n Computes the greatest common divisor using bitwise operations.\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00028902",
"row_id": 28902,
"seed_ids": "[166]"
} | 0.706888 | Data_Structure_28902 | I | [
"gcd_bit",
"lcm",
"trailing_zero",
"gcd_of_list",
"lcm_of_list",
"compute_statistics"
] | 6 | [
[
"compute_statistics",
"gcd_of_list"
],
[
"compute_statistics",
"lcm_of_list"
],
[
"compute_statistics",
"trailing_zero"
],
[
"gcd_of_list",
"gcd_bit"
],
[
"lcm_of_list",
"lcm"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 070ae48658389874819e7b36fc79d22ba265092a | e1df9b71aac2d6ba14cfb38235db5ad182679b4e | |||
v1.0 | instruct | Data_Structure | Data_Structure_28974_I | ### Encryption Examination
We want to simulate a simple secure messaging system using RSA asymmetric encryption. Given RSA's complexity and implementation constraints, your task is to:
1. Implement an efficient primality test for generating large primes.
2. Optimize the modular inverse calculation for performance.
3.... | import random
def is_prime(num: int) -> bool:
"""
Returns True if num is a prime number, otherwise False.
Uses the Miller-Rabin primality test.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
def miller_ra... | from solution import is_prime, optimized_modinv, encrypt_string, decrypt_string, generate_key
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(29) == True
assert is_prime(97) == True
assert is_prime(100001) == False
def test... | [
{
"docstring": "Returns True if num is a prime number, otherwise False.\nUses the Miller-Rabin primality test.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the modular inverse of a modulus m using the Extend... | [
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": "def is_prime(num):\n \"\"\"\n Checks if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00028974",
"row_id": 28974,
"seed_ids": "[154]"
} | 0.478215 | Data_Structure_28974 | I | [
"is_prime",
"optimized_modinv",
"encrypt_string",
"decrypt_string",
"generate_key"
] | 5 | [
[
"generate_key",
"is_prime"
],
[
"generate_key",
"optimized_modinv"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | eb8cf0531b1deddc35c78c5478e442e1b3a4776c | b1623c5520355ca75cb8837d6459b7671bfd8f59 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29009_I | #### Context
You are developing a performance-optimized system for managing a sorted list of transaction records in a financial application. One crucial aspect is efficiently inserting new transactions in the correct order to maintain the sorted structure of the list. Your task is to implement a function that inserts a... | def search_insert(sorted_list, value):
"""
Helper function to find the position to insert the value.
"""
left, right = 0, len(sorted_list)
while left < right:
mid = (left + right) // 2
if sorted_list[mid] < value:
left = mid + 1
else:
right = mid
... | from solution import insert_into_sorted_list
def test_insert_middle():
sorted_list = [1, 3, 5, 6]
value = 5
assert insert_into_sorted_list(sorted_list, value) == [1, 3, 5, 5, 6]
def test_insert_beginning():
sorted_list = [1, 3, 5, 6]
value = 0
assert insert_into_sorted_list(sorted_list, value)... | [
{
"docstring": "Helper function to find the position to insert the value.",
"function_declaration": "def search_insert(sorted_list, value):",
"function_name": "search_insert",
"parameter_list": "(sorted_list, value)"
},
{
"docstring": "Inserts value into sorted_list maintaining the sorted or... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from bisect import bisect_left\n\ndef insert_into_sorted_list(sorted_list, value):\n \"\"\"\n Inserts value into sorted_list maintaining the sorted orde... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029009",
"row_id": 29009,
"seed_ids": "[199]"
} | 0.598772 | Data_Structure_29009 | I | [
"search_insert",
"insert_into_sorted_list"
] | 2 | [
[
"insert_into_sorted_list",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d9ea2dc32c056e01b7dc145f739fcf200901fcfa | c01915facc20317e6c2798c68c52c3843a7d44b9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29029_I | ### RSA Encryption Coding Challenge
#### Scenario
You are tasked with implementing an RSA encryption system for secure communications. The company requires you to develop functions that can generate RSA keys, encrypt data using the public key, and decrypt data using the private key.
#### Problem Description
Implement... | import random
from typing import Tuple, Optional
import sympy
def generate_prime(bits: int) -> int:
return sympy.randprime(2**(bits-1), 2**bits)
def gcd(a, b):
while b:
a, b = b, a % b
return a
def extended_gcd(a, b):
if a == 0:
return b, 0, 1
gcd, x1, y1 = extended_gcd(b % a, a)
... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16, seed=42)
assert isinstance(n, int) and isinstance(e, int) and isinstance(d, int)
assert gcd(e, (n - 1 - (e - 1) % (n - 1))) == 1
def test_encrypt_decrypt():
n, e, d = generate_key(16)
data = 20
... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bits):",
"function_name": "generate_prime",
"parameter_list": "(bits)"
},
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": n... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import Tuple, Optional\n\ndef generate_prime_candidate(length: int) -> int:\n # Generate random odd integer\n p = random.getr... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029029",
"row_id": 29029,
"seed_ids": "[154]"
} | 0.659231 | Data_Structure_29029 | I | [
"generate_prime",
"gcd",
"extended_gcd",
"mod_inverse",
"generate_key",
"encrypt",
"decrypt"
] | 7 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"generate_prime"
],
[
"generate_key",
"mod_inverse"
],
[
"mod_inverse",
"extended_gcd"
]
] | 4 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 620a81953eb75216c749fd90641821d53a763290 | 49c3a59be4e20a4e775c44356caf52d8b8debc14 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29059_I | You are given two non-negative integers `N` and `M` representing the respective lengths of the `haystack` and `needle` strings. You need to write a function `optimized_strStr(haystack, needle)` that returns the index of the first occurrence of the needle in the haystack, or -1 if the needle is not part of the haystack.... | def computeLPSArray(needle):
"""
Helper function to compute the Longest Prefix Suffix (LPS) array for KMP algorithm.
"""
m = len(needle)
lps = [0] * m
length = 0 # length of the previous longest prefix suffix
i = 1
while i < m:
if needle[i] == needle[length]:
length... | from solution import optimized_strStr
def test_optimized_strStr():
assert optimized_strStr("hello", "ll") == 2
assert optimized_strStr("aaaaa", "bba") == -1
assert optimized_strStr("", "") == 0
assert optimized_strStr("mississippi", "pi") == 9
assert optimized_strStr("mississippi", "issi") == 1
... | [
{
"docstring": "Helper function to compute the Longest Prefix Suffix (LPS) array for KMP algorithm.",
"function_declaration": "def computeLPSArray(needle):",
"function_name": "computeLPSArray",
"parameter_list": "(needle)"
},
{
"docstring": "Finds the first occurrence of the needle in haysta... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_strStr(haystack, needle):\n \"\"\"\n Returns the index of the first occurrence of the needle in the haystack, or -1 if the needle is not p... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029059",
"row_id": 29059,
"seed_ids": "[86]"
} | 0.59777 | Data_Structure_29059 | I | [
"computeLPSArray",
"optimized_strStr"
] | 2 | [
[
"optimized_strStr",
"computeLPSArray"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | da45d5a0ac631ffe0f4c2872823d3a5449f91c75 | 4d83a81c6e1186eaed526d2e6dd13c7413d5d67f | |||
v1.0 | instruct | Data_Structure | Data_Structure_29063_I | Verifying Strongly Connected Components
**Scenario**: You are working on a network analysis tool that inspects directed networks represented as graphs. One of the core functionalities is to verify whether the network graph is strongly connected. This means checking if there is a path from any node to every other node ... | from typing import List, Tuple
def dfs(graph, start, visited):
stack = [start]
while stack:
node = stack.pop()
if not visited[node]:
visited[node] = True
for neighbor in graph[node]:
if not visited[neighbor]:
stack.append(neighbor)
de... | from solution import is_graph_strongly_connected
def test_example_cases():
assert is_graph_strongly_connected(5, [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 1)]) == True
assert is_graph_strongly_connected(5, [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4)]) == False
def test_single_node_graph():
assert is_graph_... | [
{
"docstring": null,
"function_declaration": "def dfs(graph, start, visited):",
"function_name": "dfs",
"parameter_list": "(graph, start, visited)"
},
{
"docstring": null,
"function_declaration": "def is_graph_strongly_connected(vertex_count, edges):",
"function_name": "is_graph_stro... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef dfs(graph, start, visited):\n stack = [start]\n while stack:\n node = stack.pop()\n if not visited[n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00029063",
"row_id": 29063,
"seed_ids": "[225]"
} | 0.616601 | Data_Structure_29063 | I | [
"dfs",
"is_graph_strongly_connected"
] | 2 | [
[
"is_graph_strongly_connected",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 218e380c4734f3923bc71bbe746ce528a4788b09 | f04d997b0cd7b087361a6577cae4bad1ec8b6aa1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29086_I | Maximum Flow Problem
#### Context:
You are given a directed graph represented as an `n x n` adjacency matrix, where each element `graph[i][j]` represents the capacity of a directed edge from node `i` to node `j`. Your task is to compute the maximum possible flow from the source node (node 0) to the sink node (node n-1... | from collections import deque
def bfs_capacity(graph, source, sink, parent):
"""
Returns True if there is an augmenting path from source to sink in residual graph.
Also fills parent[] to store the path.
"""
visited = [False] * len(graph)
queue = deque([source])
visited[source] = True
... | from solution import max_flow
def test_graph_with_direct_path():
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 max_flow(graph) == 23
def test_graph_w... | [
{
"docstring": "Returns True if there is an augmenting path from source to sink in residual graph.\nAlso fills parent[] to store the path.",
"function_declaration": "def bfs_capacity(graph, source, sink, parent):",
"function_name": "bfs_capacity",
"parameter_list": "(graph, source, sink, parent)"
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List\n\ndef bfs_find_path(graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n v... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029086",
"row_id": 29086,
"seed_ids": "[229]"
} | 0.681328 | Data_Structure_29086 | I | [
"bfs_capacity",
"max_flow"
] | 2 | [
[
"max_flow",
"bfs_capacity"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4d908a8fe2d0b6365a644d1b7a3d04acde233f21 | 55a1c97bddc8aa9d931828d9c83bf5d06f90289b | |||
v1.0 | instruct | Data_Structure | Data_Structure_29109_I | **Context:** Suppose you have been hired by a tech company to optimize their data processing system. One of their requirements is to enhance the performance of the sorting sub-routine in their system. The current system uses a heap sort algorithm and you are required to improve it by implementing the best strategies us... | import heapq
def hybrid_heap_sort(arr):
"""
Perform a hybrid heap sort using both max-heap and min-heap.
The first half of sorting is done using max-heap (building heap),
and the second half using min-heap (extracting elements in sorted order).
"""
n = len(arr)
if n <= 1:
retur... | from solution import hybrid_heap_sort
def test_hybrid_heap_sort_empty():
assert hybrid_heap_sort([]) == []
def test_hybrid_heap_sort_single_element():
assert hybrid_heap_sort([1]) == [1]
def test_hybrid_heap_sort_sorted_array():
assert hybrid_heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_hybrid... | [
{
"docstring": "Perform a hybrid heap sort using both max-heap and min-heap.\nThe first half of sorting is done using max-heap (building heap),\nand the second half using min-heap (extracting elements in sorted order).",
"function_declaration": "def hybrid_heap_sort(arr):",
"function_name": "hybrid_heap... | [
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 heapify(arr, n, i, min_heap=False):\n \"\"\"\n Helper function to maintain the heap property.\n It works as a min-heap or max-heap based on the m... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029109",
"row_id": 29109,
"seed_ids": "[8]"
} | 0.617617 | Data_Structure_29109 | I | [
"hybrid_heap_sort",
"heapify"
] | 2 | [
[
"hybrid_heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 142b4b953149b0059853773a09fb78281fa07594 | 40a5647292b7be1bb96e8fe83e3e06d22e2b7fac | |||
v1.0 | instruct | Data_Structure | Data_Structure_29168_I | #### Scenario
You are part of a team working on a project to implement cryptographic protocols in a secure communication system. To ensure the correct functioning of your protocol, you need to solve systems of simultaneous linear congruences efficiently.
### Problem Statement
Write a function `solve_chinese_remainder_... | from typing import List
from functools import reduce
from math import gcd
def modular_inverse(a, m):
m0, x0, x1 = m, 0, 1
while a > 1:
q = a // m
m, a = a % m, m
x0, x1 = x1 - q * x0, x0
return x1 + m0 if x1 < 0 else x1
def solve_chinese_remainder_optimized(nums: List[int], rems: L... | from solution import solve_chinese_remainder_optimized
def test_basic_functionality():
nums = [3, 5, 7]
rems = [2, 3, 2]
assert solve_chinese_remainder_optimized(nums, rems) == 23
def test_single_congruence():
nums = [7]
rems = [5]
assert solve_chinese_remainder_optimized(nums, rems) == 5
def... | [
{
"docstring": null,
"function_declaration": "def modular_inverse(a, m):",
"function_name": "modular_inverse",
"parameter_list": "(a, m)"
},
{
"docstring": null,
"function_declaration": "def solve_chinese_remainder_optimized(nums, rems):",
"function_name": "solve_chinese_remainder_op... | [
0,
0,
0,
0,
0,
1,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom functools import reduce\nimport math\n\ndef solve_chinese_remainder_optimized(nums: List[int], rems: List[int]) -> int:\n if ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00029168",
"row_id": 29168,
"seed_ids": "[158]"
} | 0.606063 | Data_Structure_29168 | I | [
"modular_inverse",
"solve_chinese_remainder_optimized"
] | 2 | [
[
"solve_chinese_remainder_optimized",
"modular_inverse"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | db6a2c64a04ce975ae0d4ec8ad2a46cdafd1b742 | 8c975f5ebacea217307de3a6b231f773a8dae8be | |||
v1.0 | instruct | Data_Structure | Data_Structure_29183_I | #### Context
Given the critical role of the Greatest Common Divisor (GCD) in many mathematical and real-world applications, understanding its calculation and optimization is essential. In this task, you will implement a function that computes the GCD using both traditional and optimized bitwise methods individually, an... | def gcd(a, b):
"""
Compute the GCD using Euclid's Algorithm.
"""
while b:
a, b = b, a % b
return abs(a)
def gcd_bit(a, b):
"""
Compute the GCD using the Bitwise GCD Algorithm.
"""
a, b = abs(a), abs(b)
if a == 0:
return b
if b == 0:
return a
... | from solution import gcd, gcd_bit, validate_gcd_methods
def test_gcd():
assert gcd(48, 18) == 6
assert gcd(56, 98) == 14
assert gcd(72, 120) == 24
assert gcd(81, 153) == 9
assert gcd(101, 103) == 1
def test_gcd_bit():
assert gcd_bit(48, 18) == 6
assert gcd_bit(56, 98) == 14
assert gcd_... | [
{
"docstring": "Compute the GCD using Euclid's Algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Compute the GCD using the Bitwise GCD Algorithm.",
"function_declaration": "def gcd_bit(a, b):",
"function_name"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"\n Returns the Greatest Common Divisor (GCD) of a and b using Euclid's Algorithm.\n \"\"\"\n while b:\n a, b = b, a ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029183",
"row_id": 29183,
"seed_ids": "[166]"
} | 0.708777 | Data_Structure_29183 | I | [
"gcd",
"gcd_bit",
"validate_gcd_methods"
] | 3 | [
[
"validate_gcd_methods",
"gcd"
],
[
"validate_gcd_methods",
"gcd_bit"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ea4998899fbce342e49f355780d57a08f62dce6a | c8e8d63366831960b6b6f8aeb0188c59841e9c75 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29225_I | ### Diffie-Hellman Key Exchange Validation
In the context of secure communication, the Diffie-Hellman key exchange is used to allow two parties to securely share a symmetric key over an insecure channel. Based on the following code snippets and your understanding:
1. `def prime_check(num):` : Check if a number is pri... | import random
def prime_check(num):
"""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 False
... | import pytest
from solution import prime_check, find_primitive_root, alice_private_key, bob_private_key, alice_public_key, bob_public_key, alice_shared_key, bob_shared_key, diffie_hellman_key_exchange
def test_prime_check():
assert prime_check(2) == True
assert prime_check(4) == False
assert prime_check(23... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Find primitive roots modulo n.",
"function_declaration": "def find_primitive_root(n):",
"function_name": "find_p... | [
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": "import random\n\ndef prime_check(num):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n elif num <= 3:\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00029225",
"row_id": 29225,
"seed_ids": "[146]"
} | 0.480465 | Data_Structure_29225 | I | [
"prime_check",
"find_primitive_root",
"alice_private_key",
"bob_private_key",
"alice_public_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"diffie_hellman_key_exchange"
] | 9 | [
[
"diffie_hellman_key_exchange",
"alice_private_key"
],
[
"diffie_hellman_key_exchange",
"alice_public_key"
],
[
"diffie_hellman_key_exchange",
"alice_shared_key"
],
[
"diffie_hellman_key_exchange",
"bob_private_key"
],
[
"diffie_hellman_key_exchange",
"bob_pu... | 9 | [] | false | [] | false | pytest | true | [] | true | b99db158c42f07223b1bf770bb7b428ed436bc6f | d2c6f57deb7fdbcbc9c4732436b10338737017eb | |||
v1.0 | instruct | Data_Structure | Data_Structure_29304_I | **Given Task**:
You are required to implement the ternary search algorithm and then extend it to find the boundary indices of a given key in a sorted array. Specifically, find the first and the last occurrence indices of the key.
**Scenario**:
You are given a sorted array of integers and a key. Typically, this could b... | def ternary_search(arr, key, left, right):
while right >= left:
mid1 = left + (right - left) // 3
mid2 = right - (right - left) // 3
if arr[mid1] == key:
return mid1
if arr[mid2] == key:
return mid2
if key < arr[mid1]:
rig... | from solution import find_first_and_last_occurrence
def test_find_first_and_last_occurrence():
assert find_first_and_last_occurrence([1, 2, 2, 2, 3, 4, 5], 2) == (1, 3)
assert find_first_and_last_occurrence([1, 1, 1, 1, 1], 1) == (0, 4)
assert find_first_and_last_occurrence([1, 2, 3, 4, 5], 6) == (-1, -1)
... | [
{
"docstring": null,
"function_declaration": "def ternary_search(arr, key, left, right):",
"function_name": "ternary_search",
"parameter_list": "(arr, key, left, right)"
},
{
"docstring": null,
"function_declaration": "def find_first_occurrence(arr, key, index):",
"function_name": "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": "def ternary_search(arr, key, left, right):\n while right >= left:\n mid1 = left + (right - left) // 3\n mid2 = right - (right - left) // 3\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00029304",
"row_id": 29304,
"seed_ids": "[193]"
} | 0.568849 | Data_Structure_29304 | I | [
"ternary_search",
"find_first_occurrence",
"find_last_occurrence",
"find_first_and_last_occurrence"
] | 4 | [
[
"find_first_and_last_occurrence",
"find_first_occurrence"
],
[
"find_first_and_last_occurrence",
"find_last_occurrence"
],
[
"find_first_and_last_occurrence",
"ternary_search"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | b6a8a180a192b9253b847487b0de1c4f5d3162b1 | 52e809660c7beb992b402cb583c366fdebfad591 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29319_I | **Context**: You are analyzing ecological models and require an efficient method to model exponential growth using matrix exponentiation. You've been provided with a basic framework for matrix multiplication and identity matrix generation.
However, an essential component is missing — a more optimized approach to matr... | def matrix_multiply(mat1, mat2):
"""
Multiplies two square matrices mat1 and mat2.
"""
n = len(mat1)
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += mat1[i][k] * mat2[k][j]
return result
def id... | def test_matrix_exponentiation():
mat1 = [
[1, 2],
[3, 4]
]
n1 = 2
output1 = matrix_exponentiation(mat1, n1)
expected1 = [
[7, 10],
[15, 22]
]
assert output1 == expected1
mat2 = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
n2 = 5
... | [
{
"docstring": "Multiplies two square matrices mat1 and mat2.",
"function_declaration": "def matrix_multiply(mat1, mat2):",
"function_name": "matrix_multiply",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": "Generates an identity matrix of given size.",
"function_declaration": "def i... | [
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_multiply(mat1, mat2):\n \"\"\"\n Multiplies two matrices mat1 and mat2.\n \"\"\"\n n = len(mat1)\n m = len(mat2[0])\n p = len(mat... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029319",
"row_id": 29319,
"seed_ids": "[340]"
} | 0.414615 | Data_Structure_29319 | I | [
"matrix_multiply",
"identity_matrix",
"matrix_exponentiation"
] | 3 | [
[
"matrix_exponentiation",
"identity_matrix"
],
[
"matrix_exponentiation",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | f5a399c37b2ab3d313595a4da48713ff033048da | 3749a2b7a83127df7d8f3a1ddbcae66dde0e811f | |||
v1.0 | instruct | Data_Structure | Data_Structure_29355_I | ### Scenario
You are provided with an array of integers that need to be sorted using a custom sorting method based on heap properties. You have learned Max Heap Sort and Min Heap Sort algorithms, and now it's your task to implement an advanced sorting mechanism combining principles from both.
### Task
Implement a func... | def heapify(arr, n, i, reverse=False):
"""
To heapify a subtree rooted with node i which is an index in arr.
n is size of heap. If reverse is True, it creates a min heap else max heap.
"""
largest_smallest = i
left = 2 * i + 1
right = 2 * i + 2
if reverse:
if left < n and a... | from solution import custom_heap_sort
def test_example_case():
input_array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
assert custom_heap_sort(input_array) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
def test_single_element():
input_array = [1]
assert custom_heap_sort(input_array) == [1]
def test_empty_array():
... | [
{
"docstring": "To heapify a subtree rooted with node i which is an index in arr.\nn is size of heap. If reverse is True, it creates a min heap else max heap.",
"function_declaration": "def heapify(arr, n, i, reverse=False):",
"function_name": "heapify",
"parameter_list": "(arr, n, i, reverse=False)... | [
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 custom_heap_sort(arr):\n \"\"\"\n Sort an array using a custom heap sort mechanism.\n \n Parameters:\n arr (list[int]): The input array... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029355",
"row_id": 29355,
"seed_ids": "[8]"
} | 0.67398 | Data_Structure_29355 | I | [
"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 | 7e37463f5fb6cb79d07d6597047e8552cb488cb2 | 655dea6bc6299bdccccd0b4a48e3a1d99fde4e49 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29395_I | You are given an array of integers that needs to be sorted. However, instead of using an efficient sorting algorithm, you are tasked to implement the Bogo Sort algorithm to demonstrate an extreme case of algorithm inefficiency.
#### Function Signature
```python
def bogo_sort(arr: List[int]) -> List[int]:
```
#### In... | 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):
"""
Sorts an array using the highly inefficient Bogo Sort algorithm.
"""
... | from solution import bogo_sort
import pytest
def test_bogo_sort_already_sorted():
assert bogo_sort([1, 2, 3]) == [1, 2, 3]
def test_bogo_sort_reverse_sorted():
assert bogo_sort([3, 2, 1]) == [1, 2, 3]
def test_bogo_sort_random_order():
assert bogo_sort([4, 1, 3, 2]) == [1, 2, 3, 4]
def test_bogo_sort_si... | [
{
"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 an array using the highly inefficient Bogo Sort algorithm.",
"function_declaration": "def bog... | [
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 Helper function to check if the list is sorted.\n \"\"\"\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029395",
"row_id": 29395,
"seed_ids": "[16]"
} | 0.554581 | Data_Structure_29395 | I | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4cfe86abe8ad657ac3c840fe1ccec0ec93efa761 | daf807a25e03bc4b182d87fd9e57a7d61b013dc3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29414_I | ### Scenario
You are implementing a secure communications software. As part of this software, you must include an RSA encryption system to ensure that messages can be securely transmitted. Your task is to implement the RSA key generation and encryption/decryption functions along with additional utility for testing purp... | import random
from sympy import mod_inverse
def generate_key(k, seed=None):
if seed is not None:
random.seed(seed)
def get_prime(bit_length):
while True:
candidate = random.getrandbits(bit_length)
if is_prime(candidate):
return candidate
p = get_pri... | from solution import generate_key, encrypt, decrypt, is_prime
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(1)
assert not is_prime(0)
assert not is_prime(-7)
def test_generate_key():
n, e, d = generate_key(16, s... | [
{
"docstring": null,
"function_declaration": "def generate_key(k, seed=None):",
"function_name": "generate_key",
"parameter_list": "(k, seed=None)"
},
{
"docstring": null,
"function_declaration": "def encrypt(data, e, n):",
"function_name": "encrypt",
"parameter_list": "(data, e,... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime\nfrom sympy.core.numbers import mod_inverse\n\ndef generate_key(k, seed=None):\n if seed is not None:\n ran... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029414",
"row_id": 29414,
"seed_ids": "[154]"
} | 0.682815 | Data_Structure_29414 | I | [
"generate_key",
"encrypt",
"decrypt",
"is_prime"
] | 4 | [
[
"generate_key",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 4bda630b07490ba641c955834d464a83f09ec988 | e7a7931e839bd5057b51399db5ebe98682b9e779 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29460_I | You are tasked with building and managing a Binary Search Tree (BST). Specifically, you will implement a function that allows for inserting new values into the BST, another function to search for a value, and a final function to delete a value.
### Function Requirements
1. **Function Name**: `insert`
* **Input**: ... | class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return TreeNode(key)
if key < root.val:
root.left = insert(root.left, key)
elif key > root.val:
root.right = insert(roo... | from solution import TreeNode, insert, search, delete
def test_insert_and_search_empty_tree():
root = None
root = insert(root, 5)
assert search(root, 5) == True
def test_insert_multiple_values():
root = None
root = insert(root, 5)
root = insert(root, 3)
root = insert(root, 7)
assert se... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef in... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029460",
"row_id": 29460,
"seed_ids": "[287]"
} | 0.532069 | Data_Structure_29460 | I | [
"insert",
"search",
"delete",
"minValueNode"
] | 4 | [
[
"delete",
"minValueNode"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 2679653f086bd6a30304dd7ff9eda03876e38754 | 2aa70c0d61529d6b2d6815bf2fbd69dcd715e161 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29522_I | ### Question
You are tasked with writing a function that computes the inverse Fast Fourier Transform (IFFT) of a given list of complex numbers using the Cooley-Tukey algorithm. The Inverse FFT is used to convert a signal from its frequency domain representation back to the time domain.
#### Requirements:
* Your functi... | from cmath import exp, pi
def ifft(x):
"""
Recursive implementation of the Cooley-Tukey IFFT algorithm.
"""
N = len(x)
if N == 1:
return x
# Conjugate the input
x_conj = [xi.conjugate() for xi in x]
# Apply FFT to the conjugated input
y = fft(x_conj)
# Conjugate the r... | from solution import ifft
from cmath import isclose
def test_ifft_basic():
input_data = [8.0+8.0j, 0.0+2.0j, 2.0-2.0j, -2.0+0.0j]
expected_output = [2.0+2.0j, 1.0+3.0j, 3.0+1.0j, 2.0+2.0j]
output_data = ifft(input_data)
assert all(isclose(output_data[i], expected_output[i], rel_tol=1e-9) for i in range... | [
{
"docstring": "Recursive implementation of the Cooley-Tukey IFFT algorithm.",
"function_declaration": "def ifft(x):",
"function_name": "ifft",
"parameter_list": "(x)"
},
{
"docstring": "Recursive implementation of the Cooley-Tukey FFT algorithm. ",
"function_declaration": "def fft(x):",... | [
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 cmath import exp, pi\n\ndef ifft(x):\n \"\"\"\n Recursive implementation of the Cooley-Tukey IFFT algorithm.\n \"\"\"\n N = len(x)\n if N ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029522",
"row_id": 29522,
"seed_ids": "[165]"
} | 0.528146 | Data_Structure_29522 | I | [
"ifft",
"fft"
] | 2 | [
[
"ifft",
"fft"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5b16cb22020e5db173605a887420166868e33065 | 0f61e5f7421246937a28b68e43b2879aaf645ab0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29535_I | Finding Special Numbers
You are given a positive integer \( n \). Write a program to find all primitive roots of \( n \). Note that not all integers have primitive roots.
### Input
* A single integer \( n \) (1 \( \leq n \leq 10^6 \)).
### Output
* A list of integers which are the primitive roots of \( n \).
* If no... | from math import gcd
from sympy import isprime, primefactors
from functools import reduce
def euler_totient(n):
"""Calculate Euler's Totient function φ(n)."""
if n == 1:
return 1
factors = set(primefactors(n))
phi = n
for p in factors:
phi *= (1 - 1/p)
return int(phi)
def is_pr... | from solution import find_primitive_roots
def test_find_primitive_roots():
assert find_primitive_roots(7) == [3, 5]
assert find_primitive_roots(12) == []
assert find_primitive_roots(5) == [2, 3]
assert find_primitive_roots(11) == [2, 6, 7, 8]
assert find_primitive_roots(15) == []
assert find_pr... | [
{
"docstring": "Calculate Euler's Totient function φ(n).",
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": "Check if g is a primitive root of n by verifying its order.",
"function_declaration": "def is_primitive... | [
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 math import gcd\nfrom sympy import isprime, primefactors\nfrom functools import reduce\n\ndef euler_totient(n):\n \"\"\"Calculate Euler's Totient func... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00029535",
"row_id": 29535,
"seed_ids": "[160]"
} | 0.539569 | Data_Structure_29535 | I | [
"euler_totient",
"is_primitive_root",
"find_primitive_roots"
] | 3 | [
[
"find_primitive_roots",
"euler_totient"
],
[
"find_primitive_roots",
"is_primitive_root"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | a9e2657bd253facf255da45f519988d0eac74766 | b09651f07a5343d81493034afe499f83e34755d0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29600_I | Greatest Common Divisor and Least Common Multiple
#### Part 1: Computation of GCD using Euclid's Algorithm
Write a function `compute_gcd` that computes the greatest common divisor (GCD) of two non-zero integers using Euclid's Algorithm.
#### Function Signature:
```python
def compute_gcd(a: int, b: int) -> int:
```
#... | def compute_gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor (GCD) of two non-zero integers using Euclid's Algorithm.
"""
a = abs(a)
b = abs(b)
while b:
a, b = b, a % b
return a
def compute_lcm(a: int, b: int) -> int:
"""
Computes the lowest common multip... | from solution import compute_gcd, compute_lcm
def test_compute_gcd():
assert compute_gcd(48, 18) == 6
assert compute_gcd(-48, 18) == 6
assert compute_gcd(48, -18) == 6
assert compute_gcd(-48, -18) == 6
assert compute_gcd(17, 13) == 1
assert compute_gcd(0, 5) == 5 # edge case
assert compute... | [
{
"docstring": "Computes the greatest common divisor (GCD) of two non-zero integers using Euclid's Algorithm.",
"function_declaration": "def compute_gcd(a, b):",
"function_name": "compute_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the lowest common multiple (LCM) of two non... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def compute_gcd(a: int, b: int) -> int:\n \"\"\"\n Compute the greatest common divisor (GCD) of two non-zero integers using Euclid's Algorithm.\n \"\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029600",
"row_id": 29600,
"seed_ids": "[166]"
} | 0.718694 | Data_Structure_29600 | I | [
"compute_gcd",
"compute_lcm"
] | 2 | [
[
"compute_lcm",
"compute_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3935561360035d88c84a0ffac99832052ddd7c67 | 1117c3cfef43834a9b869e1933977b8030691091 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29613_I | You are provided with the implementation of a singly linked list and two functions, `remove_dups` and `remove_dups_without_set`, for removing duplicate elements from the list. Your task is to build upon this functionality to solve the following problem:
### Task:
Implement a function `remove_dups_from_unsorted_list(he... | class Node:
def __init__(self, value):
self.value = value
self.next = None
def remove_dups(head):
if not head:
return head
node_set = set()
current = head
node_set.add(current.value)
while current.next:
if current.next.value in node_set:
current.... | import pytest
from solution import Node, remove_dups_from_unsorted_list
def construct_linked_list(values):
if not values:
return None
head = Node(values[0])
current = head
for value in values[1:]:
current.next = Node(value)
current = current.next
return head
def convert_lin... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\ndef remove_dups(head):\n if not head:\n return ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00029613",
"row_id": 29613,
"seed_ids": "[256]"
} | 0.617545 | Data_Structure_29613 | I | [
"remove_dups",
"remove_dups_without_set",
"remove_dups_from_unsorted_list"
] | 3 | [
[
"remove_dups_from_unsorted_list",
"remove_dups"
],
[
"remove_dups_from_unsorted_list",
"remove_dups_without_set"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | true | [] | true | d35ceb9ff61135832913ff3a5810ee75b8d6c884 | 3a4e3c1d639e35ff7ca08798db52a4930440415c | |||
v1.0 | instruct | Data_Structure | Data_Structure_29617_I | Next Prime Number Generator
#### Context
Given the fundamental concept of checking for a prime number, let's extend this concept to generate the next prime number after a given integer `m`.
#### Task
Write a function `next_prime_after(m)` that takes an integer `m` and returns the smallest prime number greater than `m... | 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 next_prime_after(m: int) -> int:
num =... | from solution import next_prime_after, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
def test_next_prime_after():
assert next_prime_after(10) == 11
assert next_prime_a... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def next_prime_after(m):",
"function_name": "next_prime_after",
"parameter_list": "(m)"
}
] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_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_0 | {
"original_instruction": "",
"prompt_id": "00029617",
"row_id": 29617,
"seed_ids": "[143]"
} | 0.620557 | Data_Structure_29617 | I | [
"is_prime",
"next_prime_after"
] | 2 | [
[
"next_prime_after",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | decde47961dd16629de01416da0c02a0c4e26680 | 64022bdaa8f4db726f4a515cc235798f44a9084c | |||
v1.0 | instruct | Data_Structure | Data_Structure_29639_I | #### Background
You are building a calculator that supports a variety of arithmetic operations. As part of this project, you need to implement some fundamental algorithms related to number theory. Specifically, you will need to calculate the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of two given int... | def gcd_bit(a: int, b: int) -> int:
if a == 0:
return b
if b == 0:
return a
shift = 0
# Reduce a and b by finding the common factors of 2
while ((a | b) & 1) == 0:
a >>= 1
b >>= 1
shift += 1
while (a & 1) == 0:
a >>= 1
while b !... | from solution import gcd_bit, lcm
def test_gcd_bit_positive_numbers():
assert gcd_bit(48, 18) == 6
def test_gcd_bit_with_one_zero():
assert gcd_bit(48, 0) == 48
assert gcd_bit(0, 18) == 18
def test_gcd_bit_with_both_zeros():
assert gcd_bit(0, 0) == 0
def test_gcd_bit_prime_numbers():
assert gcd_... | [
{
"docstring": null,
"function_declaration": "def gcd_bit(a, b):",
"function_name": "gcd_bit",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd_bit(a: int, b: int) -> int:\n \"\"\"\n Compute the GCD of two integers using the bitwise GCD algorithm.\n \"\"\"\n if a == 0:\n ret... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029639",
"row_id": 29639,
"seed_ids": "[166]"
} | 0.729778 | Data_Structure_29639 | I | [
"gcd_bit",
"lcm"
] | 2 | [
[
"lcm",
"gcd_bit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 61e3a58a040efbf7db412328dced740fe52ac43f | bc5075d34f1c079a411bf52147a88440e150d153 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29677_I | ### Programming Assessment: Finding Primitive Roots Efficiently
#### Context
An encrypted communication system relies on primitive roots to generate secure keys. As part of the system upgrade, you are required to write an efficient function to identify all primitive roots for given integers. Your implementation will b... | def gcd(a, b):
while b:
a, b = b, a % b
return a
def euler_totient(n):
if n == 1:
return 1
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1
if n > 1:
resul... | from solution import find_primitive_root
def test_find_primitive_root_1():
assert find_primitive_root(1) == [0]
def test_find_primitive_root_10():
assert find_primitive_root(10) == [3, 7]
def test_find_primitive_root_13():
assert find_primitive_root(13) == [2, 6, 7, 11]
def test_find_primitive_root_23()... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": null,
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_primitive_root(n):\n \"\"\"\n Returns a list of all primitive roots of n.\n \n Parameters:\n - n (int): Positive integer for which to ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029677",
"row_id": 29677,
"seed_ids": "[160]"
} | 0.496871 | Data_Structure_29677 | I | [
"gcd",
"euler_totient",
"all_prime_factors",
"is_primitive_root",
"find_primitive_root"
] | 5 | [
[
"find_primitive_root",
"all_prime_factors"
],
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"gcd"
],
[
"find_primitive_root",
"is_primitive_root"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 8cd17de07112018b0a6b8a00aea1abf1442a1ac9 | 3c5c4db7a6ef9566ca6d6cb931921a83c527e0fd | |||
v1.0 | instruct | Data_Structure | Data_Structure_29680_I | Implementing Optimized Bucket Sort
#### Scenario
You are an engineer working on a large-scale data analysis platform that processes millions of data points daily. One of your tasks is to implement an efficient sorting mechanism for a dataset that contains uniformly distributed real numbers between 0 and 1. You decide ... | def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else... | from solution import bucket_sort
def test_bucket_sort_basic():
assert bucket_sort([0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]) == [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
assert bucket_sort([0.56, 0.32, 0.22, 0.84, 0.76]) == [0.22, 0.32, 0.56, 0.76, 0.84]
def test_bucket_s... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def bucket_sort(arr):",
"function_name": "bucket_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n L = arr[:mid]\n R = arr[mid:]\n\n merge_sort(L)\n merge_... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029680",
"row_id": 29680,
"seed_ids": "[26]"
} | 0.524894 | Data_Structure_29680 | I | [
"merge_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"merge_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 56eb894d1081389be78b2d4eb259bd888ef0762f | b9c20297c51f6bd03c8818e04ab0e5af78c9475c | |||
v1.0 | instruct | Data_Structure | Data_Structure_29685_I | ### Question
You need to implement a function that uses the Knuth-Morris-Pratt algorithm to find all starting indices where a pattern string matches within a given text string. Implement the function `find_pattern_occurrences(text: str, pattern: str) -> List[int]`.
#### Function Signature
```python
def find_pattern_oc... | from typing import List
def compute_prefix_function(pattern: str) -> List[int]:
"""
Computes the prefix function (partial match table) for the 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 = ... | from solution import find_pattern_occurrences
def test_find_pattern_occurrences_example_case_1():
assert find_pattern_occurrences("abracadabra", "abra") == [0, 7]
def test_find_pattern_occurrences_example_case_2():
assert find_pattern_occurrences("aaaaa", "aa") == [0, 1, 2, 3]
def test_find_pattern_occurrenc... | [
{
"docstring": "Computes the prefix function (partial match table) for the KMP algorithm.",
"function_declaration": "def compute_prefix_function(pattern):",
"function_name": "compute_prefix_function",
"parameter_list": "(pattern)"
},
{
"docstring": "Finds all occurrences of the pattern in th... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef compute_lps(pattern: str) -> List[int]:\n \"\"\"\n Computes the longest proper prefix which is also a suffix array for th... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029685",
"row_id": 29685,
"seed_ids": "[93]"
} | 0.621971 | Data_Structure_29685 | I | [
"compute_prefix_function",
"find_pattern_occurrences"
] | 2 | [
[
"find_pattern_occurrences",
"compute_prefix_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1226df2d06b8fd61fc67e0be92c9c02d929f3a58 | ad70208f0d3821067bcdadbfe40af54d8e88b4d9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29753_I | ### Question: Roman Numeral Validator and Converter
In certain historical and computer science contexts, you might need to convert Roman numerals to integers. Given a string representing a Roman numeral, your task is to create a function that not only converts the Roman numeral to an integer but also validates the inp... | def roman_to_int(s: str) -> int:
"""
Converts a Roman numeral to an integer and validates the input.
Args:
s (str): A string representing a Roman numeral.
Returns:
int: The integer value of the Roman numeral if valid, otherwise -1.
"""
# Define Roman numeral values
roman_nu... | from solution import roman_to_int, int_to_roman
def test_roman_to_int():
"""
Test conversion of Roman numeral to integer.
"""
assert roman_to_int("III") == 3
assert roman_to_int("IV") == 4
assert roman_to_int("IX") == 9
assert roman_to_int("LVIII") == 58
assert roman_to_int("MCMXCIV") =... | [
{
"docstring": "Converts a Roman numeral to an integer and validates the input.\n\nArgs:\ns (str): A string representing a Roman numeral.\n\nReturns:\nint: The integer value of the Roman numeral if valid, otherwise -1.",
"function_declaration": "def roman_to_int(s):",
"function_name": "roman_to_int",
... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def roman_to_int(s: str) -> int:\n roman_to_int_map = {\n 'I': 1, 'V': 5, 'X': 10, 'L': 50,\n 'C': 100, 'D': 500, 'M': 1000\n }\n \n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00029753",
"row_id": 29753,
"seed_ids": "[82]"
} | 0.727741 | Data_Structure_29753 | I | [
"roman_to_int",
"int_to_roman"
] | 2 | [
[
"roman_to_int",
"int_to_roman"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d23082fbca36f7cd040a1b259aa415355c355b3f | b066f584945cb87ef9290661ecf8a5657dcdc52e | |||
v1.0 | instruct | Data_Structure | Data_Structure_29774_I | ### 1-Sparse Stream Recovery Algorithm Implementation
You are given a stream of tuples, where each tuple contains a number and a sign denoting an addition or a subtraction. Your task is to implement an algorithm to determine if the stream is 1-sparse, which means that, considering the signs, there is exactly one uniqu... | def one_sparse(array):
"""
Determines if the stream is 1-sparse. If it is, returns the unique number left uncanceled.
"""
value_sum = 0
sum_signs = 0
bitsum = [0] * 32
for val, sign in array:
if sign == '+':
value_sum += val
sum_signs += 1
else:
... | import pytest
from solution import one_sparse, _check_every_number_in_bitsum, _get_bit_sum
def test_one_sparse_case1():
assert one_sparse([(4, '+'), (2, '+'), (2, '-'), (4, '+'), (3, '+'), (3, '-')]) == 4
def test_one_sparse_case2():
assert one_sparse([(2, '+'), (2, '+'), (2, '+'), (2, '+'), (2, '+'), (2, '+'... | [
{
"docstring": "Determines if the stream is 1-sparse. If it is, returns the unique number left uncanceled.",
"function_declaration": "def one_sparse(array):",
"function_name": "one_sparse",
"parameter_list": "(array)"
},
{
"docstring": "Validate the internal bit sum array",
"function_dec... | [
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 one_sparse(array):\n \"\"\"\n Determines if the stream is 1-sparse and returns the unique number.\n If the stream is not 1-sparse, returns None.\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029774",
"row_id": 29774,
"seed_ids": "[126]"
} | 0.557423 | Data_Structure_29774 | I | [
"one_sparse",
"_check_every_number_in_bitsum",
"_get_bit_sum"
] | 3 | [
[
"one_sparse",
"_check_every_number_in_bitsum"
],
[
"one_sparse",
"_get_bit_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4560858bdd2b7caeee273123d574edbeac5dd688 | 73cc49a2d09e43c8ce5488bdde762d12a8e77ea3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29827_I | ### RSA Key Generation Algorithm Implementation
You are given the task of implementing a function that generates a pair of RSA keys (public and private keys). You are required to modify the existing code to improve the performance of the key generation process, specifically focusing on prime number generation and modu... | import random
from typing import Optional, Tuple
def is_prime(n: int, k: int = 40) -> bool:
""" Use Miller-Rabin primality test to check if a number is prime """
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
# Write n as d*2^r + 1 with d odd (by... | from solution import generate_key, is_prime
def test_generate_key():
n, e, d = generate_key(16, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert n > 0
assert e > 0
assert d > 0
def test_key_correctness():
# Testing for a small key size
n... | [
{
"docstring": "Use Miller-Rabin primality test to check if a number is prime ",
"function_declaration": "def is_prime(n, k=40):",
"function_name": "is_prime",
"parameter_list": "(n, k=40)"
},
{
"docstring": "Generate a large prime number of given bits using Miller-Rabin Test ",
"functio... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import Tuple, Optional\n\ndef is_prime(n, k=5):\n \"\"\" Test if a number is prime using the Miller-Rabin test \"\"\"\n if n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029827",
"row_id": 29827,
"seed_ids": "[154]"
} | 0.574248 | Data_Structure_29827 | I | [
"is_prime",
"generate_large_prime",
"gcd",
"egcd",
"modinv",
"generate_key"
] | 6 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"generate_large_prime"
],
[
"generate_key",
"modinv"
],
[
"generate_large_prime",
"is_prime"
],
[
"modinv",
"egcd"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 05871d0034ad4f66abfd1cd04cfbc9bbaf88ed4c | f864885b19ecdded3f06d56fea0403a5352fe72c | |||
v1.0 | instruct | Data_Structure | Data_Structure_29866_I | Optimized Primitive Root Finder
You are tasked to write an optimized version of the primitive root finder algorithms provided. Specifically, implement the following functions:
#### Function Signature:
```python
def find_order(a: int, n: int) -> int:
pass
def euler_totient(n: int) -> int:
pass
def find_primi... | from typing import List
def find_order(a: int, n: int) -> int:
"""
Calculates the order of `a` modulo `n`, the smallest k such that a^k ≡ 1 (mod n).
"""
if (a % n == 0):
return -1
order = 1
value = a % n
while value != 1:
value = (value * a) % n
order += 1
... | from solution import find_order, euler_totient, find_primitive_root
def test_find_order():
assert find_order(2, 5) == 4
assert find_order(2, 6) == -1
assert find_order(3, 7) == 6
assert find_order(7, 10) == 4
def test_euler_totient():
assert euler_totient(9) == 6
assert euler_totient(10) == 4
... | [
{
"docstring": "Calculates the order of `a` modulo `n`, the smallest k such that a^k ≡ 1 (mod n).",
"function_declaration": "def find_order(a, n):",
"function_name": "find_order",
"parameter_list": "(a, n)"
},
{
"docstring": "Calculates Euler's totient function φ(n), the count of integers up... | [
0,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import gcd\nfrom typing import List\n\ndef find_order(a: int, n: int) -> int:\n \"\"\"\n Returns the order of integer a modulo n, or -1 if no ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00029866",
"row_id": 29866,
"seed_ids": "[160]"
} | 0.515163 | Data_Structure_29866 | I | [
"find_order",
"euler_totient",
"find_primitive_root",
"gcd"
] | 4 | [
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"find_order"
],
[
"find_primitive_root",
"gcd"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | bb3c7364622457ae6b122ccc3530c1f948988c6b | c09611a0f061727285634d0050acdc04af88f03c | |||
v1.0 | instruct | Data_Structure | Data_Structure_29891_I | ### Coding Task: Extended Factorial Calculation
#### Context and Description
You are helping a research team to perform combinatorial calculations, and they require a function to compute the factorial of a number with the possibility of returning the result modulo a given value. You are provided a function that comput... | def extended_factorial(n, mod=None, strategy='iterative'):
"""
Compute the factorial of a non-negative integer n optionally modulo mod using the specified strategy.
Parameters:
n (int): A non-negative integer whose factorial is to be computed.
mod (int, optional): A positive integer for modulo oper... | from solution import extended_factorial
def test_extended_factorial_no_mod_iterative():
assert extended_factorial(5) == 120
assert extended_factorial(0) == 1
assert extended_factorial(1) == 1
def test_extended_factorial_with_mod_iterative():
assert extended_factorial(5, 3) == 0
assert extended_fac... | [
{
"docstring": "Compute the factorial of a non-negative integer n optionally modulo mod using the specified strategy.\n\nParameters:\nn (int): A non-negative integer whose factorial is to be computed.\nmod (int, optional): A positive integer for modulo operation. Defaults to None.\nstrategy (str, optional): A s... | [
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 extended_factorial(n: int, mod: int = None, strategy: str = 'iterative') -> int:\n \"\"\"\n Compute the factorial of a non-negative integer n option... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029891",
"row_id": 29891,
"seed_ids": "[139]"
} | 0.641817 | Data_Structure_29891 | I | [
"extended_factorial",
"factorial_iterative",
"factorial_recursive"
] | 3 | [
[
"extended_factorial",
"factorial_iterative"
],
[
"extended_factorial",
"factorial_recursive"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c13de9ce6a84125ec6d2af3cd58048943ddd2657 | 99968eff41e02f850b9a3a219c74eab53c599291 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29892_I | #### Interpolation Search Extension
You are given a sorted array `array` of integers and a list `search_keys` containing multiple search keys. Implement a function `batch_interpolation_search` that searches for each key in `search_keys` within the `array` using the Interpolation Search algorithm. Your function should ... | from typing import List
def interpolation_search(array: List[int], key: int) -> int:
"""
Perform an interpolation search for a given key in the array.
Parameters:
array (List[int]): A sorted list of unique integers.
key (int): The integer value to search in the array.
Returns:
int... | from solution import batch_interpolation_search
def test_batch_interpolation_search_single_element():
array = [10]
search_keys = [10, 5]
assert batch_interpolation_search(array, search_keys) == [0, -1]
def test_batch_interpolation_search_multiple_elements():
array = [-25, -12, -1, 10, 12, 15, 20, 41, ... | [
{
"docstring": "Perform an interpolation search for a given key in the array.\n\nParameters:\narray (List[int]): A sorted list of unique integers.\nkey (int): The integer value to search in the array.\n\nReturns:\nint: The index of the key in the array if found, otherwise -1.",
"function_declaration": "def ... | [
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 interpolation_search(array: List[int], key: int) -> int:\n \"\"\"\n Perform an interpolation search for a given key in th... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00029892",
"row_id": 29892,
"seed_ids": "[192]"
} | 0.533069 | Data_Structure_29892 | I | [
"interpolation_search",
"batch_interpolation_search"
] | 2 | [
[
"batch_interpolation_search",
"interpolation_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e25b07da9403842fbb8fa1c2507c7c6b0edf06eb | ed54d387b3e5120d05828faf7c218ba09fe835ea | |||
v1.0 | instruct | Data_Structure | Data_Structure_29897_I | ### Scenario
You work as a software engineer for a company that ensures secure communication between its clients. To achieve robust security, you are tasked with implementing a basic version of an RSA encryption algorithm provided to you in pseudocode. You've decided to complete the RSA key generation, encryption, and... | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(bits):
"""Generates an odd integer randomly."""
p = random.getrandbits(bits)
# Apply a mask to set MSB and LSB to 1 to ensure proper bit length.
p |= (1 << bits - 1) | 1
return p
def generate_prime(bits):
"""Gene... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16, seed=42)
assert type(n) == int
assert type(e) == int
assert type(d) == int
def test_encrypt_decrypt():
n, e, d = generate_key(16, seed=42)
data = 20
encrypted = encrypt(data, e, n)
d... | [
{
"docstring": "Generates an odd integer randomly.",
"function_declaration": "def generate_prime_candidate(bits):",
"function_name": "generate_prime_candidate",
"parameter_list": "(bits)"
},
{
"docstring": "Generate a prime number of 'bits' bit length.",
"function_declaration": "def gene... | [
0,
0,
0,
1,
0,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime(bit_length, seed=None):\n if seed is not None:\n random.seed(seed)\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00029897",
"row_id": 29897,
"seed_ids": "[154]"
} | 0.707082 | Data_Structure_29897 | I | [
"generate_prime_candidate",
"generate_prime",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_prime"
],
[
"generate_prime",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | d2805197d908be1333bc5c8473f4be17c4ff22ac | f29f15a06f76f708b36afa89d28146ae718a25f7 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29916_I | **Context**: You are given the task of designing a network flow system that can handle water distribution in a city. The city has different junctions (nodes) and pipes (edges) with varying capacities.
**Problem**: Implement a function to compute the maximum amount of water that can be pushed from the source node to th... | from collections import deque
from typing import List
def bfs(residual_graph, source, sink, parent):
visited = [False] * len(residual_graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for ind, val in enumerate(residual_graph[u]):
if not... | from solution import compute_maximum_water_flow
def test_case_1():
adj_matrix = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert compute_maximum_water_flow(adj_matrix) == 2... | [
{
"docstring": null,
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def compute_maximum_water_flow(adj_matrix):",
"function_n... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(residual_capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029916",
"row_id": 29916,
"seed_ids": "[229]"
} | 0.63962 | Data_Structure_29916 | I | [
"bfs",
"compute_maximum_water_flow"
] | 2 | [
[
"compute_maximum_water_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2212bfb0aa7cfbbc86b7e859358543420f1527e9 | 98d767c9180f4755e519cf4ee2788a99da501e3c | |||
v1.0 | instruct | Data_Structure | Data_Structure_29937_I | You have been tasked with completing the implementation of the insertion sort algorithm using the provided helper method `search_insert`. The goal is to sort a given list of integers in non-decreasing order efficiently.
### Function Signature
```python
def insertion_sort(arr: List[int]) -> List[int]:
pass
```
###... | from typing import List
def search_insert(arr: List[int], num: int) -> int:
"""
Uses binary search to find the index where 'num' should be inserted in 'arr' to maintain sorted order.
"""
low, high = 0, len(arr)
while low < high:
mid = (low + high) // 2
if arr[mid] < num:
... | from solution import insertion_sort
def test_insertion_sort_sample_cases():
assert insertion_sort([3, 1, 4, 1, 5]) == [1, 1, 3, 4, 5]
assert insertion_sort([0, -1, 2, -3, 5, 6, -7]) == [-7, -3, -1, 0, 2, 5, 6]
assert insertion_sort([10, 20, 30, 10, 5]) == [5, 10, 10, 20, 30]
assert insertion_sort([]) =... | [
{
"docstring": "Uses binary search to find the index where 'num' should be inserted in 'arr' to maintain sorted order.",
"function_declaration": "def search_insert(arr, num):",
"function_name": "search_insert",
"parameter_list": "(arr, num)"
},
{
"docstring": "Sorts a list of integers in non... | [
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], low: int, high: int, key: int) -> int:\n while low < high:\n mid = (low + high) // 2\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029937",
"row_id": 29937,
"seed_ids": "[199]"
} | 0.575711 | Data_Structure_29937 | I | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6e5b3e97eff2146343643f9af917454b1cd7201e | 14cece4cd78041ca7f66ee167bcbe2f518eedab5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_29967_I | You are tasked with developing a function to manage a collection of unique integer values using a Binary Search Tree (BST). Implement the core operations of a BST: insertion, deletion, and lookup. Additionally, provide a method to return the values of the BST sorted in ascending order (i.e., an in-order traversal).
##... | from typing import Optional, List
class TreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
def insert(root: Optional[TreeNode], val: int) -> TreeNode:
if root is None:
return TreeNode(val)
if val < root.val:
root.left = insert(roo... | from solution import TreeNode, insert, delete, lookup, inorder_traversal
def test_insert():
root = None
root = insert(root, 5)
root = insert(root, 3)
root = insert(root, 7)
assert inorder_traversal(root) == [3, 5, 7]
def test_delete_leaf_node():
root = None
root = insert(root, 5)
root ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Optional, List\n\nclass TreeNode:\n def __init__(self, val=0):\n self.val = val\n self.left = None\n self.right = N... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029967",
"row_id": 29967,
"seed_ids": "[287]"
} | 0.499941 | Data_Structure_29967 | I | [
"insert",
"min_value_node",
"delete",
"lookup",
"inorder_traversal"
] | 5 | [
[
"delete",
"min_value_node"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 922761665522b4ac2169a358d9b49e65709bee9f | 67161d39b67e88c693c3b57e9f265cc663b71bae | |||
v1.0 | instruct | Data_Structure | Data_Structure_29994_I | **Coding Assessment Question**
### Context
You are tasked with improving an ancient sorting machine lying in the archives of your comp-sci department—an archaic Bogo Sort machine. While it's understood that Bogo Sort is impractical for large datasets, your goal is to enhance its efficiency to a degree that it can hand... | import random
def is_sorted(arr):
"""
Checks if the array is sorted in ascending order.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def guided_shuffle(arr):
"""
Performs a guided shuffle by randomly swapping adjacent elements.
... | from solution import guided_bogo_sort
def test_small_sorted_list():
assert guided_bogo_sort([1, 2, 3]) == [1, 2, 3]
def test_small_random_list():
assert guided_bogo_sort([3, 1, 2]) == [1, 2, 3]
def test_repeated_elements():
assert guided_bogo_sort([10, -10, 10]) == [-10, 10, 10]
def test_single_element(... | [
{
"docstring": "Checks if the array is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Performs a guided shuffle by randomly swapping adjacent elements.",
"function_declaration": "def g... | [
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 is_sorted(arr):\n \"\"\"\n Helper function to check if the list is sorted.\n \"\"\"\n for i in range(len(arr) - 1):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029994",
"row_id": 29994,
"seed_ids": "[16]"
} | 0.57278 | Data_Structure_29994 | I | [
"is_sorted",
"guided_shuffle",
"guided_bogo_sort"
] | 3 | [
[
"guided_bogo_sort",
"guided_shuffle"
],
[
"guided_bogo_sort",
"is_sorted"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 01eab2680f987503ee9c9eaa52cfc44fcb71b607 | 02007845f4b5382ebc58ebf6316784148513fadb | |||
v1.0 | instruct | Data_Structure | Data_Structure_30004_I | ### Problem: Optimized Least Common Multiple Calculation with Edge Case Handling
You are provided with two functions that compute the greatest common divisor (gcd) using different approaches and a function to compute the least common multiple (lcm) using the gcd. Your task is to optimize and enhance the current implem... | def gcd_bit_enhanced(a, b):
"""
Computes the greatest common divisor (GCD) of two non-negative integers a and b
using bitwise operations. This function should also handle edge cases effectively.
"""
if a == 0:
return b
if b == 0:
return a
# Reduce any common factors of 2
... | from solution import gcd_bit_enhanced, lcm_optimized
def test_gcd_bit_enhanced():
assert gcd_bit_enhanced(48, 18) == 6
assert gcd_bit_enhanced(0, 0) == 0
assert gcd_bit_enhanced(0, 18) == 18
assert gcd_bit_enhanced(18, 0) == 18
assert gcd_bit_enhanced(42, 56) == 14
assert gcd_bit_enhanced(100_0... | [
{
"docstring": "Computes the greatest common divisor (GCD) of two non-negative integers a and b\nusing bitwise operations. This function should also handle edge cases effectively.",
"function_declaration": "def gcd_bit_enhanced(a, b):",
"function_name": "gcd_bit_enhanced",
"parameter_list": "(a, b)"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd_bit_enhanced(a: int, b: int) -> int:\n \"\"\"\n Computes the greatest common divisor (GCD) of two non-negative integers a and b\n using bitwi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030004",
"row_id": 30004,
"seed_ids": "[166]"
} | 0.609867 | Data_Structure_30004 | I | [
"gcd_bit_enhanced",
"lcm_optimized"
] | 2 | [
[
"lcm_optimized",
"gcd_bit_enhanced"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 91cc4a9a8b5b8cbb64822f132c0760429bd750d5 | 0f2b54b14b9cdc7557164484d85bbf63b34dedda | |||
v1.0 | instruct | Data_Structure | Data_Structure_30028_I | **Question: Optimized Quick Sort with Randomized Pivot**
You are tasked with implementing an optimized version of the Quick Sort algorithm. This optimized version must address the performance bottleneck of selecting a bad pivot by using a randomized pivot. Additionally, to minimize the recursion overhead for small sub... | from typing import List
import random
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 arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def partition(a... | from solution import optimized_quick_sort
def test_empty_array():
assert optimized_quick_sort([], 5) == []
def test_single_element():
assert optimized_quick_sort([10], 5) == [10]
def test_pre_sorted_array():
assert optimized_quick_sort([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]
def test_reverse_sort... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"paramet... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef insertion_sort(arr, low, high):\n for i in range(low + 1, high + 1):\n key = arr[i]\n j = i - 1\n while j >= low ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030028",
"row_id": 30028,
"seed_ids": "[25]"
} | 0.540932 | Data_Structure_30028 | I | [
"insertion_sort",
"partition",
"quick_sort",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"quick_sort"
],
[
"quick_sort",
"insertion_sort"
],
[
"quick_sort",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | f108635de170faa1aec3798b69a60f9e0c02f237 | cc36aff4ea2e6d205c9bab0ba89e43582b75f231 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30054_I | Compute the n-th Fibonacci Number Using Matrix Exponentiation
#### Objective:
You are required to implement a function to compute the n-th Fibonacci number using matrix exponentiation.
#### Scenario:
Fibonacci numbers have applications in different areas such as algorithms involving dynamic programming, computational... | def multiply_matrices(A, 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, ... | from solution import fib_matrix
def test_fib_matrix_basic():
assert fib_matrix(0) == 0
assert fib_matrix(1) == 1
assert fib_matrix(2) == 1
assert fib_matrix(3) == 2
assert fib_matrix(4) == 3
assert fib_matrix(5) == 5
assert fib_matrix(6) == 8
def test_fib_matrix_large():
# Test with la... | [
{
"docstring": null,
"function_declaration": "def multiply_matrices(A, B):",
"function_name": "multiply_matrices",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def matrix_power(matrix, power):",
"function_name": "matrix_power",
"parameter_list": "(m... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fib_matrix(n: int) -> int:\n \"\"\"\n Computes the n-th Fibonacci number using matrix exponentiation.\n \n Parameters:\n n (int): The posit... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030054",
"row_id": 30054,
"seed_ids": "[37]"
} | 0.689578 | Data_Structure_30054 | I | [
"multiply_matrices",
"matrix_power",
"fib_matrix"
] | 3 | [
[
"fib_matrix",
"matrix_power"
],
[
"matrix_power",
"multiply_matrices"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cd5ce508172a80e50775c267577c11d32cdb4dd7 | e378332d9a23d99c2ebcf9f942a0af4edb75c5c8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30058_I | ### Nearest Neighbor Search Algorithm
#### Background
You are tasked with implementing a crucial component of a recommendation system that quickly identifies the most similar historical data point to a newly incoming data point. This function is a simplified version of the nearest neighbor search algorithm.
#### Task... | import math
def euclidean_distance(a, b):
"""
Calculate the Euclidean distance between two vectors a and b.
"""
return math.sqrt(sum((a_i - b_i) ** 2 for a_i, b_i in zip(a, b)))
def optimized_nearest_neighbor(x, tSet):
"""
Find the value associated with the nearest neighbor to vector x in tSet... | from solution import optimized_nearest_neighbor
def test_nearest_neighbor_single_element():
x = (2, 3)
tSet = {(1, 2): "A"}
assert optimized_nearest_neighbor(x, tSet) == "A"
def test_nearest_neighbor_multiple_elements():
x = (2, 3)
tSet = {(1, 2): "A", (4, 5): "B", (1, 3): "C"}
assert optimize... | [
{
"docstring": "Calculate the Euclidean distance between two vectors a and b.",
"function_declaration": "def euclidean_distance(a, b):",
"function_name": "euclidean_distance",
"parameter_list": "(a, b)"
},
{
"docstring": "Find the value associated with the nearest neighbor to vector x in tSe... | [
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": "import math\n\ndef euclidean_distance(x, y):\n \"\"\"\n Calculate the Euclidean distance between two vectors x and y.\n \"\"\"\n return math.sqrt(... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00030058",
"row_id": 30058,
"seed_ids": "[260]"
} | 0.625635 | Data_Structure_30058 | I | [
"euclidean_distance",
"optimized_nearest_neighbor"
] | 2 | [
[
"optimized_nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e415be0a1f714993c1327d021e8f937251d4bd5e | 160fa557c6d35777218179c355006ac1050683ff | |||
v1.0 | instruct | Data_Structure | Data_Structure_30061_I | ### Programming Task: Implementing Enhanced Radix Sort
#### Scenario
Radix Sort is especially useful for sorting large datasets of non-negative integers. You've been assigned to improve the radix sort implementation for an even distribution of numbers and ensure it handles the edge cases correctly.
#### Problem State... | from typing import List
def enhanced_radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
if not arr:
return []
max_num = max(arr)
exp = 1
base = 10
while max_num // exp > 0:
arr = counting_sort_by_digit(arr, exp, base)
if simulation:
print(f"... | from solution import enhanced_radix_sort
def test_enhanced_radix_sort_empty_list():
assert enhanced_radix_sort([]) == []
def test_enhanced_radix_sort_single_element():
assert enhanced_radix_sort([1]) == [1]
def test_enhanced_radix_sort_duplicates():
assert enhanced_radix_sort([5, 5, 5, 5]) == [5, 5, 5, 5... | [
{
"docstring": null,
"function_declaration": "def enhanced_radix_sort(arr, simulation=False):",
"function_name": "enhanced_radix_sort",
"parameter_list": "(arr, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def counting_sort_by_digit(arr, exp, base):",
"function... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef enhanced_radix_sort(arr: List[int], simulation: bool = False) -> List[int]:\n if len(arr) == 0:\n return arr\n\n b... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030061",
"row_id": 30061,
"seed_ids": "[15]"
} | 0.616717 | Data_Structure_30061 | I | [
"enhanced_radix_sort",
"counting_sort_by_digit"
] | 2 | [
[
"enhanced_radix_sort",
"counting_sort_by_digit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a0e0f2982b0bf3a94074e555eab8dbd069693528 | 417006eb84587f82d5e558ef60ac929e1870c1bf | |||
v1.0 | instruct | Data_Structure | Data_Structure_30103_I | ### Problem: Max Flow in An Augmented Flow Network
As a network engineer, you are given a task to determine the maximum flow of data that can be pushed from a source server to a target server in a data center. The network architecture can be represented as a directed graph, where each node represents a server and edge... | from collections import deque
def bfs(rGraph, s, t, parent):
visited = [False] * len(rGraph)
queue = deque([s])
visited[s] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(rGraph[u]):
if not visited[v] and capacity > 0: # Not yet visited and there's ca... | from solution import compute_max_flow
def test_simple_network():
network = [
[0, 10, 0, 0],
[0, 0, 4, 6],
[0, 0, 0, 10],
[0, 0, 0, 0]
]
assert compute_max_flow(network) == 10
def test_medium_network():
network = [
[0, 10, 10, 0],
[0, 0, 10, 10],
... | [
{
"docstring": null,
"function_declaration": "def bfs(rGraph, s, t, parent):",
"function_name": "bfs",
"parameter_list": "(rGraph, s, t, parent)"
},
{
"docstring": null,
"function_declaration": "def compute_max_flow(network):",
"function_name": "compute_max_flow",
"parameter_list... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(residual_graph, source, sink, parent):\n \"\"\"\n Standard BFS to find if there is a path from source to sink i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030103",
"row_id": 30103,
"seed_ids": "[229]"
} | 0.593735 | Data_Structure_30103 | I | [
"bfs",
"compute_max_flow"
] | 2 | [
[
"compute_max_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c624ef6c777feb02a267eec66184e2fecb57d0de | a38e50fc9ead44fc5f9433bb6c3384d71ecf9501 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30158_I | ### Matrix Exponentiation by Squaring
### Context
Matrix exponentiation is an important technique with various applications in algorithms, such as in graph theory and cryptography. Implementing it efficiently can save a significant amount of computational resources.
### Task
You are required to implement a function t... | 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 j in range(n):
result[i][j] = sum(A[i][k] * B[k][j] for k in range(n))
return result
def matrix_power(mat, power):
"""
... | from solution import matrix_power
def test_matrix_power_base_case():
mat = [[2]]
power = 0
result = matrix_power(mat, power)
assert result == [[1]] # Any matrix to the power of 0 should be the identity matrix of same size
def test_matrix_power_identity():
mat = [
[1, 0],
[0, 1]
... | [
{
"docstring": "Multiplies two square matrices A and B.",
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": "Raises the square matrix `mat` to the power `power` using exponentiation by squaring.",
"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 matrix_multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B.\n \"\"\"\n n = len(A)\n result = [[0] * n for _ in range(n)]\n for i ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00030158",
"row_id": 30158,
"seed_ids": "[340]"
} | 0.516494 | Data_Structure_30158 | I | [
"matrix_multiply",
"matrix_power"
] | 2 | [
[
"matrix_power",
"matrix_multiply"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 795c05538dbe7c45fb8878ec3f68aa9207560a95 | 1f70942d7882faa1e53a0d87b5a615bf06d7244a | |||
v1.0 | instruct | Data_Structure | Data_Structure_30167_I | ### Prime Number Range Finder
#### Background
In various applications, such as cryptography and numerical analysis, determining the prime numbers within a given range is essential. You've identified that having an efficient algorithm that can verify the primality of a number is a crucial component of such tasks.
####... | from typing import List
def is_prime(n: int) -> bool:
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
retur... | from solution import find_primes_in_range
def test_find_primes_in_range_basic_cases():
assert find_primes_in_range(10, 30) == [11, 13, 17, 19, 23, 29]
assert find_primes_in_range(1, 10) == [2, 3, 5, 7]
def test_find_primes_in_range_single_element():
assert find_primes_in_range(7, 7) == [7]
assert find... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find all prime numbers in the given range [start, end].",
"function_declaration": "def find_primes_in_range(start, end):",
... | [
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 \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00030167",
"row_id": 30167,
"seed_ids": "[143]"
} | 0.649598 | Data_Structure_30167 | I | [
"is_prime",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1d205232ce88c9f959ca0d686a1ec661353bbb33 | 9ef53d31681a6d0774e6f7854c4016aa1b91c6d1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30178_I | ## Huffman Coding Challenge
Huffman Coding is a popular algorithm used for lossless data compression. Your task is to implement both the encoding and decoding functions for Huffman Coding. Given a file, your function should be able to read the file, compress it using the Huffman Coding algorithm, and save the compress... | import heapq
from collections import defaultdict, Counter
class HuffmanNode:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def build_huffman_tree(text):
... | import pytest
from solution import encode_file, decode_file, huffman_encode, huffman_decode, build_huffman_tree, build_codes, HuffmanNode
def write_file(filename, content):
with open(filename, 'w') as file:
file.write(content)
def read_file(filename):
with open(filename, 'r') as file:
return f... | [] | [
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 heapq import heappush, heappop, heapify\nfrom collections import defaultdict\nimport os\nimport struct\n\nclass HuffmanNode:\n def __init__(self, char... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00030178",
"row_id": 30178,
"seed_ids": "[335]"
} | 0.524756 | Data_Structure_30178 | I | [
"build_huffman_tree",
"build_codes",
"huffman_encode",
"huffman_decode",
"encode_file",
"decode_file"
] | 6 | [
[
"decode_file",
"huffman_decode"
],
[
"encode_file",
"huffman_encode"
],
[
"huffman_encode",
"build_codes"
],
[
"huffman_encode",
"build_huffman_tree"
]
] | 4 | [] | false | [
"HuffmanNode"
] | true | pytest | true | [] | true | 403d80f14f5e57a6f4c7faa1c50fd134a4414e47 | ac99d7b73cf17276d18b6fcf99b2241784290fe4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30184_I | ### Bogo Sort Analysis and Enhancement
As a novice algorithm designer, you are tasked with analyzing the Bogo Sort algorithm provided and suggesting enhancements for practical use. Although the Bogo Sort algorithm is theoretically interesting, it is impractical for any substantial application due to its inefficiency.
... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def bogo_sort(arr):
"""
Performs a single attempt of Bogo Sort by shuffling.
"""
random.shuffle(arr)
return arr
def enhanced_bog... | def test_is_sorted():
assert is_sorted([1, 2, 3]) == True
assert is_sorted([3, 2, 1]) == False
assert is_sorted([]) == True
assert is_sorted([1]) == True
def test_enhanced_bogo_sort():
# Testing with small inputs
assert enhanced_bogo_sort([3, 2, 1], 10) == [1, 2, 3]
assert enhanced_bogo_sor... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Performs a single attempt of Bogo Sort by shuffling.",
"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\n\ndef is_sorted(arr):\n \"\"\" Check if the array is sorted in ascending order \"\"\"\n for i in range(len(arr) - 1):\n if arr[i] ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030184",
"row_id": 30184,
"seed_ids": "[16]"
} | 0.560107 | Data_Structure_30184 | I | [
"is_sorted",
"bogo_sort",
"enhanced_bogo_sort"
] | 3 | [
[
"enhanced_bogo_sort",
"bogo_sort"
],
[
"enhanced_bogo_sort",
"is_sorted"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 3eef2aac0df36bc416374602253b76bd10e71286 | d9d013a5af59457c6ddc4e3afe8c0109e427c8e7 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30198_I | ## Run-Length Encoding and Decoding
### Scenario
You are working as a software developer in a data storage company. Your task is to enhance the company's storage efficiency by implementing a Run-Length Encoding (RLE) algorithm, which is a form of lossless data compression. With RLE, you convert data streams into a seq... | def rle_operations(operation: str, data: str) -> str:
if operation == "encode":
return rle_encode(data)
elif operation == "decode":
return rle_decode(data)
else:
raise ValueError("Unknown operation. Use 'encode' or 'decode'.")
def rle_encode(data: str) -> str:
if not data:
... | from solution import rle_operations
def test_encode_basic():
assert rle_operations("encode", "aaabbccaaa") == "3a2b2c3a"
def test_decode_basic():
assert rle_operations("decode", "3a2b2c3a") == "aaabbccaaa"
def test_encode_empty():
assert rle_operations("encode", "") == ""
def test_decode_empty():
as... | [
{
"docstring": null,
"function_declaration": "def rle_operations(operation, data):",
"function_name": "rle_operations",
"parameter_list": "(operation, data)"
},
{
"docstring": null,
"function_declaration": "def rle_encode(data):",
"function_name": "rle_encode",
"parameter_list": ... | [
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 rle_operations(operation: str, data: str) -> str:\n if operation == \"encode\":\n return rle_encode(data)\n elif operation == \"decode\":\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00030198",
"row_id": 30198,
"seed_ids": "[334]"
} | 0.642155 | Data_Structure_30198 | I | [
"rle_operations",
"rle_encode",
"rle_decode"
] | 3 | [
[
"rle_operations",
"rle_decode"
],
[
"rle_operations",
"rle_encode"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cfacc6f78b5ca996c05148ad52e9ff9f06a4d546 | 9d0057669a67d0b78d1c5c2fd93f8ccc43742287 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30203_I | In number theory, a self-descriptive power sum number is a number in which the sum of its digits raised to consecutive powers equals the number itself. For example, 89 is a self-descriptive power sum number because \(8^1 + 9^2 = 89\), and 135 is another such number since \(1^1 + 3^2 + 5^3 = 135\).
Your task is to impl... | from typing import List
def is_self_descriptive_number(n: int) -> bool:
"""
Checks if a number is a self-descriptive power sum number.
"""
digits = [int(d) for d in str(n)]
power_sum = sum(digit ** (i + 1) for i, digit in enumerate(digits))
return power_sum == n
def find_self_descriptive_numbe... | from solution import find_self_descriptive_numbers, is_self_descriptive_number
def test_is_self_descriptive_number():
assert is_self_descriptive_number(89) == True
assert is_self_descriptive_number(135) == True
assert is_self_descriptive_number(1) == True
assert is_self_descriptive_number(12) == False
... | [
{
"docstring": "Checks if a number is a self-descriptive power sum number.",
"function_declaration": "def is_self_descriptive_number(n):",
"function_name": "is_self_descriptive_number",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of self-descriptive power sum numbers in the ran... | [
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_self_descriptive_number(n: int) -> bool:\n \"\"\"\n Checks if a number is a self-descriptive power sum number.\n \"... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00030203",
"row_id": 30203,
"seed_ids": "[135]"
} | 0.641876 | Data_Structure_30203 | I | [
"is_self_descriptive_number",
"find_self_descriptive_numbers"
] | 2 | [
[
"find_self_descriptive_numbers",
"is_self_descriptive_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f68ce594d012f6ffc64c2beb61796c620dcc5a4b | 17bddf73c3a3d1f3646e810e048b6bd3ab3b9ac3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30246_I | ### Pancake Sorting with Error Handling
**Context**:
You are developing a feature for a bakery’s inventory management system. The bakery wants to organize the pancakes by size, from the smallest on top to the largest at the bottom, using a series of pancake flips.
**Problem**:
Implement a function `enhanced_pancake_s... | from typing import List
def flip(arr: List[int], k: int) -> None:
"""
Function to reverse the first k elements of the array
"""
arr[:k] = arr[:k][::-1]
def find_max_index(arr: List[int], n: int) -> int:
"""
Function to find the index of the maximum element in arr[0:n]
"""
max_index = 0... | from solution import enhanced_pancake_sort
import pytest
def test_empty_list():
assert enhanced_pancake_sort([]) == []
def test_single_element_list():
assert enhanced_pancake_sort([5]) == [5]
def test_sorted_list():
assert enhanced_pancake_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted... | [
{
"docstring": "Function to reverse the first k elements of the array",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Function to find the index of the maximum element in arr[0:n]",
"function_declaration": "def find_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_pancake_sort(arr):\n def flip(arr, k):\n return arr[:k+1][::-1] + arr[k+1:]\n\n def find_max_index(arr, n):\n max_index = 0\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030246",
"row_id": 30246,
"seed_ids": "[9]"
} | 0.677014 | Data_Structure_30246 | I | [
"flip",
"find_max_index",
"enhanced_pancake_sort"
] | 3 | [
[
"enhanced_pancake_sort",
"find_max_index"
],
[
"enhanced_pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fae1915dd7730398ea731cb113dee832f4d55760 | 63f83682d8fa734a127c554c6fc144c7501ca0cf | |||
v1.0 | instruct | Data_Structure | Data_Structure_30249_I | RSA Encryption Key Calculation
RSA encryption heavily relies on the modular inverse operation. Given two prime numbers \( p \) and \( q \), you can generate the public and private keys for RSA encryption by following specific steps.
**Scenario**: You are to write a function that, given two prime numbers \( p \) and \... | import math
def extended_gcd(a, b):
"""
Extended Euclidean Algorithm:
Given two integers a and b, return a tuple (g, x, y), where g is gcd(a, b) and x,y are such that
ax + by = g.
"""
if a == 0:
return (b, 0, 1)
g, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x... | from solution import generate_rsa_keys
def test_generate_rsa_keys_basic():
p = 61
q = 53
n, phi_n, e, d, max_pq = generate_rsa_keys(p, q)
assert n == 61 * 53
assert phi_n == (61 - 1) * (53 - 1)
assert e == 65537
assert (e * d) % phi_n == 1
assert max_pq == 61
def test_generate_rsa_keys... | [
{
"docstring": "Extended Euclidean Algorithm:\nGiven two integers a and b, return a tuple (g, x, y), where g is gcd(a, b) and x,y are such that\nax + by = g.",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Co... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import math\n\ndef extended_gcd(a, b):\n \"\"\"\n Extended Euclidean Algorithm:\n Given two integers a and b, return a tuple... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00030249",
"row_id": 30249,
"seed_ids": "[161]"
} | 0.545361 | Data_Structure_30249 | I | [
"extended_gcd",
"modular_inverse",
"generate_rsa_keys"
] | 3 | [
[
"generate_rsa_keys",
"extended_gcd"
],
[
"generate_rsa_keys",
"modular_inverse"
],
[
"modular_inverse",
"extended_gcd"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | d0ac6d507c0b1e1bcd731475e96aa1a00830446e | b6ad39a5dc9cf1f9054978eb840cf17f779e6c44 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30254_I | #### Scenario
You are tasked with creating a custom file compression system using Huffman Coding. The files to be compressed consist of plain text files which may contain any dictionary-based language text input.
#### Requirements
The goal is to implement a function `perform_huffman_encoding` that takes an input stri... | import heapq
from collections import defaultdict, Counter
from typing import Any, Dict, List, Tuple
class Node:
def __init__(self, char: str, freq: int):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < oth... | from solution import Node, perform_huffman_encoding
def validate_huffman_tree(node: Node, expected_nodes: List[Tuple[str, int]]):
result_nodes = []
def traverse(node: Node):
if node is None:
return
if node.char:
result_nodes.append((node.char, node.freq))
travers... | [] | [
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": "import heapq\nfrom collections import defaultdict\nfrom typing import Tuple, Any\n\nclass Node:\n def __init__(self, char: Any, freq: int):\n self.c... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00030254",
"row_id": 30254,
"seed_ids": "[335]"
} | 0.556609 | Data_Structure_30254 | I | [
"build_huffman_tree",
"generate_huffman_codes",
"perform_huffman_encoding"
] | 3 | [
[
"perform_huffman_encoding",
"build_huffman_tree"
],
[
"perform_huffman_encoding",
"generate_huffman_codes"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | true | [] | true | fa2b5a0690b0c4894701f9e65de142db55bc0d1b | ab15c0ab37008dd7ceb0c5deb18ad2d2c95128cc | |||
v1.0 | instruct | Data_Structure | Data_Structure_30263_I | ### Scenario
You are given the task of sorting a list of students' scores. These scores can range from 0 to 100. You'll use the merge sort algorithm provided in the code snippets, but with an added constraint: you need to sort them in descending order, rather than ascending order.
### Task
Implement the merge sort alg... | def merge_sort(arr):
"""
Sorts the input list using merge sort in descending order.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
merged = [None] * (len(left) + len(right))
merge(left, right, merged)
retu... | import pytest
from solution import merge_sort
def test_merge_sort_multiple_elements():
assert merge_sort([34, 7, 23, 32, 5, 62]) == [62, 34, 32, 23, 7, 5]
def test_merge_sort_sorted_asc():
assert merge_sort([1, 4, 5, 7]) == [7, 5, 4, 1]
def test_merge_sort_sorted_desc():
assert merge_sort([7, 5, 4, 1]) =... | [
{
"docstring": "Sorts the input list using merge sort in descending order.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into one in descending order.",
"function_declaration": "def me... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr: list) -> list:\n \"\"\"\n Perform merge sort on the given list in descending order.\n \"\"\"\n if len(arr) <= 1:\n retu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030263",
"row_id": 30263,
"seed_ids": "[12]"
} | 0.643523 | Data_Structure_30263 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 02577fd2bb3d9ee6ecf26a8a5784e7ab11cea434 | eb4563b5a26d11124aa49ba666371cb210919844 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30364_I | ### Scenario
You are developing a recommendation system for a movie streaming service. Given a user's preference profile - represented as a vector of features (like genres, language, release year, etc.), you need to suggest a movie that best matches the user's profile from a collection of movies, each represented by it... | import math
def euclidean_distance(x, y):
"""
Computes the Euclidean distance between two vectors.
:param x: tuple of floats
:param y: tuple of floats
:return: float representing the Euclidean distance
"""
return math.sqrt(sum((xi - yi) * (xi - yi) for xi, yi in zip(x, y)))
def recomm... | from solution import recommend_movie
def test_recommend_movie_single_movie():
user_profile = (1.0, 2.0, 3.0)
movies = {(1.0, 2.0, 3.0): "Movie A"}
assert recommend_movie(user_profile, movies) == "Movie A"
def test_recommend_movie_multiple_movies():
user_profile = (1.2, 3.4, 5.6)
movies = {
... | [
{
"docstring": "Computes the Euclidean distance between two vectors.\n\n:param x: tuple of floats\n:param y: tuple of floats\n:return: float representing the Euclidean distance",
"function_declaration": "def euclidean_distance(x, y):",
"function_name": "euclidean_distance",
"parameter_list": "(x, y)... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import sqrt\n\ndef euclidean_distance(vec1, vec2):\n return sqrt(sum((a - b)**2 for a, b in zip(vec1, vec2)))\n\ndef recommend_movie(user_profile... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030364",
"row_id": 30364,
"seed_ids": "[260]"
} | 0.520062 | Data_Structure_30364 | I | [
"euclidean_distance",
"recommend_movie"
] | 2 | [
[
"recommend_movie",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 32805217c73cdfbe7776db5c61ef64f3d5041fb3 | 358f47643b493fe6bed7d880d0add2b7df92f0a3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30481_I | ### Problem Context
You are developing a simulation for a system that involves a large number of state transitions represented by matrices. To optimize the performance of your simulation, it is crucial to efficiently compute the exponentiation of state transition matrices.
### Task
Write a function `large_matrix_expon... | def matrix_mult(A, B):
"""
Multiplies two square matrices A and B.
"""
size = len(A)
result = [[0] * size for _ in range(size)]
for i in range(size):
for j in range(size):
result[i][j] = sum(A[i][k] * B[k][j] for k in range(size))
return result
def large_matrix_exponenti... | from solution import large_matrix_exponentiation, matrix_mult
def test_large_matrix_exponentiation_example():
mat = [
[1, 1],
[1, 0]
]
power = 5
expected_output = [
[8, 5],
[5, 3]
]
assert large_matrix_exponentiation(mat, power) == expected_output
def test_large... | [
{
"docstring": "Multiplies two square matrices A and B.",
"function_declaration": "def matrix_mult(A, B):",
"function_name": "matrix_mult",
"parameter_list": "(A, B)"
},
{
"docstring": "Computes mat^power using repeated squaring method.",
"function_declaration": "def large_matrix_exponen... | [
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_multiply(mat1, mat2):\n \"\"\"\n Multiplies two square matrices mat1 and mat2.\n \"\"\"\n n = len(mat1)\n result = [[0] * n for _ in... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030481",
"row_id": 30481,
"seed_ids": "[340]"
} | 0.41616 | Data_Structure_30481 | I | [
"matrix_mult",
"large_matrix_exponentiation"
] | 2 | [
[
"large_matrix_exponentiation",
"matrix_mult"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ce61ad8d31d1181c46c9b2577a16e3e68b4494e4 | 24d07de6b4b2f9ee14dd63d2b29bcf0e2c3d2f0b | |||
v1.0 | instruct | Data_Structure | Data_Structure_30501_I | #### Scenario
You are a software developer at a logistics company. Your company is developing an application that analyzes the reachability of delivery locations within a city. The city is modeled as a directed graph, where vertices represent locations and edges represent direct roads between them. To determine which l... | from typing import List, Tuple
def dfs(graph, source, vertex, reachable):
reachable[source][vertex] = 1
for neighbor in graph[vertex]:
if not reachable[source][neighbor]:
dfs(graph, source, neighbor, reachable)
def find_transitive_closure(vertices: int, edges: List[Tuple[int, int]]) -> Lis... | from solution import find_transitive_closure
def test_find_transitive_closure_simple():
vertices = 2
edges = [(0, 1)]
expected_result = [[1, 1], [0, 1]]
assert find_transitive_closure(vertices, edges) == expected_result
def test_find_transitive_closure_no_edges():
vertices = 3
edges = []
e... | [
{
"docstring": null,
"function_declaration": "def dfs(graph, source, vertex, reachable):",
"function_name": "dfs",
"parameter_list": "(graph, source, vertex, reachable)"
},
{
"docstring": null,
"function_declaration": "def find_transitive_closure(vertices, edges):",
"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": "from typing import List, Tuple\n\ndef dfs(graph, source, vertex, reachable):\n reachable[source][vertex] = 1\n for neighbor in graph[vertex]:\n i... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00030501",
"row_id": 30501,
"seed_ids": "[228]"
} | 0.60719 | Data_Structure_30501 | I | [
"dfs",
"find_transitive_closure"
] | 2 | [
[
"find_transitive_closure",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 61e17747b7ca17a2f8c802729896da14eb936da6 | 1f377371918fba74f3d6c64e2296d83142c0c7d2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30565_I | ### Bucket Sort Implementation
#### Problem Statement
Implement the bucket sort algorithm. Your implementation should divide input data into a specific number of buckets, sort each bucket individually using insertion sort, and then concatenate the buckets to create the final sorted list.
#### Input
- A list of non-ne... | def insertion_sort(bucket):
"""
Sorts a bucket using the insertion sort algorithm.
"""
for i in range(1, len(bucket)):
key = bucket[i]
j = i - 1
while j >= 0 and key < bucket[j]:
bucket[j + 1] = bucket[j]
j -= 1
bucket[j + 1] = key
return bucke... | from solution import bucket_sort
def test_bucket_sort_normal_case():
assert bucket_sort([4, 1, 7, 3, 2, 9, 0, 6]) == [0, 1, 2, 3, 4, 6, 7, 9]
def test_bucket_sort_single_element():
assert bucket_sort([5]) == [5]
def test_bucket_sort_empty_list():
assert bucket_sort([]) == []
def test_bucket_sort_identic... | [
{
"docstring": "Sorts a bucket using the insertion sort algorithm.",
"function_declaration": "def insertion_sort(bucket):",
"function_name": "insertion_sort",
"parameter_list": "(bucket)"
},
{
"docstring": "Sorts an array of non-negative integers using the bucket sort algorithm.\n\nArgs:\nar... | [
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(arr):\n \"\"\"\n Helper function to sort a list using insertion sort.\n \"\"\"\n for i in range(1, len(arr)):\n key = ar... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030565",
"row_id": 30565,
"seed_ids": "[26]"
} | 0.566078 | Data_Structure_30565 | I | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fb05ea26ea5854b26860420e2e4a47b067865c4a | b8cb5c3a423fb22705af3e57ffd13bfc4502d1d0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30632_I | ### Maximum Flow Calculation in a Network Graph
You are tasked with implementing a function to calculate the maximum flow in a network graph from a given source to a sink using one of the provided algorithms.
#### Function Signature
```python
def calculate_max_flow(capacity: List[List[int]], source: int, sink: int) -... | from typing import List
from collections import deque
def bfs(residual_capacity, source, sink, parent):
visited = [False] * len(residual_capacity)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, cap in enumerate(residual_capacity[u]):... | from solution import calculate_max_flow
def test_calculate_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 calcul... | [
{
"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 calculate_max_flow(capacity, source, sink):",
"... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List\n\ndef bfs(capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n visited ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030632",
"row_id": 30632,
"seed_ids": "[240]"
} | 0.613423 | Data_Structure_30632 | I | [
"bfs",
"calculate_max_flow"
] | 2 | [
[
"calculate_max_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 39540dba776325fa75ee17aa67468390e1b3c7f0 | 86587c7c7d47e0b559e840fb4630ea39947f302d | |||
v1.0 | instruct | Data_Structure | Data_Structure_30639_I | ### Problem: Text Editor Spell Correction
You are tasked with implementing a spell checker for a simple text editor. The spell checker needs to suggest corrections for misspelled words by computing the edit distance between the misspelled word and potential correct words from a dictionary.
#### Function Signature:
``... | from typing import List
def edit_distance(word1: str, word2: str) -> int:
"""Compute the edit distance between two words using dynamic programming."""
m, n = len(word1), len(word2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == ... | from solution import spell_checker
def test_spell_checker_basic():
assert spell_checker("speling", ["spelling", "spewing", "spieling"]) == "spelling"
def test_spell_checker_with_identical_words():
assert spell_checker("rate", ["rate", "rate", "sample"]) == "rate"
def test_spell_checker_with_tie():
assert... | [
{
"docstring": "Compute the edit distance between two words using dynamic programming.",
"function_declaration": "def edit_distance(word1, word2):",
"function_name": "edit_distance",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Suggests the correct word from the dictionary with the ... | [
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 edit_distance(word1: str, word2: str) -> int:\n \"\"\"Compute the edit distance between two words using dynamic programming.... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00030639",
"row_id": 30639,
"seed_ids": "[31]"
} | 0.590105 | Data_Structure_30639 | I | [
"edit_distance",
"spell_checker"
] | 2 | [
[
"spell_checker",
"edit_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a6abf5087c96c8b86c20b304e808c880cc76fcda | d1c37e3a2a3122d33a072fcfc341862b327b7221 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30650_I | Enhanced Bogo Sort with Simulation Counter
Given the inefficiency of Bogo Sort, your task is to implement an enhanced version of Bogo Sort that includes a simulation counter to keep track of the number of shuffles performed. Additionally, your implementation should return the sorted list along with a count of how many... | 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_enhanced(arr: list[int]) -> tuple[list[int], int]:
"""
Enhanced Bogo Sort that returns... | from solution import bogo_sort_enhanced
def test_bogo_sort_enhanced_single_element():
assert bogo_sort_enhanced([1]) == ([1], 0)
def test_bogo_sort_enhanced_already_sorted():
result = bogo_sort_enhanced([1, 2, 3])
assert result[0] == [1, 2, 3]
assert result[1] >= 0 # Count can vary, but must be a... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Enhanced Bogo Sort that returns the sorted list and the number of shuffles performed.",
"function_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": "import random\n\ndef bogo_sort_enhanced(arr: list[int]) -> tuple[list[int], int]:\n \"\"\"\n Sort the array using Bogo Sort and count the number of shuf... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030650",
"row_id": 30650,
"seed_ids": "[16]"
} | 0.618253 | Data_Structure_30650 | I | [
"is_sorted",
"bogo_sort_enhanced"
] | 2 | [
[
"bogo_sort_enhanced",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0f7760c1fbf7c0dbdc40f0d72a85d032a4c92a06 | 1d1278e58a230e4b4f075311009a399a4961f743 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30720_I | ### Question: Implement Enhanced Diffie-Hellman Key Exchange with Additional Constraints
**Objective**: Implement Diffie-Hellman Key Exchange algorithm with enhanced features to address additional constraints such as verifying if `p` is prime and if `a` is a valid primitive root of `p`.
#### Scenario
Alice and Bob wa... | import sympy
import random
def is_primitive_root(a, p):
"""
Check if `a` is a primitive root of `p`.
"""
required_set = set(num for num in range(1, p) if sympy.gcd(num, p) == 1)
actual_set = set((a ** powers) % p for powers in range(1, p))
return required_set == actual_set
def secure_diffie_he... | from solution import secure_diffie_hellman_key_exchange
def test_secure_diffie_hellman_key_exchange_successful():
shared_key = secure_diffie_hellman_key_exchange(2, 11, False)
assert isinstance(shared_key, int)
def test_secure_diffie_hellman_key_exchange_non_prime():
result = secure_diffie_hellman_key_exc... | [
{
"docstring": "Check if `a` is a primitive root of `p`.",
"function_declaration": "def is_primitive_root(a, p):",
"function_name": "is_primitive_root",
"parameter_list": "(a, p)"
},
{
"docstring": "Performs the Diffie-Hellman key exchange if the following conditions are met:\n1. `p` is a pr... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030720",
"row_id": 30720,
"seed_ids": "[146]"
} | 0.411361 | Data_Structure_30720 | I | [
"is_primitive_root",
"secure_diffie_hellman_key_exchange"
] | 2 | [
[
"secure_diffie_hellman_key_exchange",
"is_primitive_root"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | dd0ed78b891d1b67682e803708c580e26e58ec08 | 55b6fa9562f04281cc1c17d3c468f3d1fb1bbc78 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30734_I | Alice and Bob want to securely exchange keys over an insecure network using the Diffie-Hellman Key Exchange method. Your task is to implement their key exchange process. You need to ensure that the prime number \(p\) and primitive root \(a\) are validated correctly and then perform the Diffie-Hellman key exchange.
###... | import random
from math import gcd
def prime_check(num):
"""
Returns True if num is a prime number, else False.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 ... | from solution import diffie_hellman_key_exchange, prime_check, euler_totient, find_order, find_primitive_root
def test_prime_check():
assert prime_check(23) == True
assert prime_check(20) == False
assert prime_check(2) == True
assert prime_check(1) == False
assert prime_check(0) == False
assert... | [
{
"docstring": "Returns True if num is a prime number, else False.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Returns the value of Euler's Totient function for n.",
"function_declaration": "def euler_tot... | [
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": "def prime_check(num: int) -> bool:\n \"\"\"\n Returns True if num is a prime number else False.\n \"\"\"\n if num <= 1:\n return False\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00030734",
"row_id": 30734,
"seed_ids": "[146]"
} | 0.462311 | Data_Structure_30734 | I | [
"prime_check",
"euler_totient",
"find_order",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 5 | [
[
"diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"diffie_hellman_key_exchange",
"prime_check"
],
[
"find_order",
"euler_totient"
],
[
"find_primitive_root",
"prime_check"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | c363d311e43d976e33b0e6fd0e5b9c7e85e0498a | b41ba123b9ae5b5707f6e85acdc0fb48cd69a29a | |||
v1.0 | instruct | Data_Structure | Data_Structure_30787_I | You are required to implement a function for matrix inversion that handles both 2x2 matrices and larger n x n matrices using the determinant-based method. Your function should follow the general steps used in the provided code, such as computing the matrix of minors and cofactors, adjugating, and multiplying by the inv... | from typing import List
def determinant(matrix: List[List[float]]) -> float:
"""Calculate the determinant of a matrix."""
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for c in range(n):
... | import pytest
from solution import invert_matrix
def test_valid_2x2_matrix():
matrix = [
[4, 7],
[2, 6]
]
inverse = invert_matrix(matrix)
expected = [[0.6, -0.7], [-0.2, 0.4]]
for i in range(2):
for j in range(2):
assert abs(inverse[i][j] - expected[i][j]) < 1e-9... | [
{
"docstring": "Calculate the determinant of a matrix.",
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": "Return the Minor of the matrix by removing the specified row and column.",
"function_declaration": ... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef determinant(matrix: List[List[float]]) -> float:\n n = len(matrix)\n if n == 2:\n return matrix[0][0] * matrix[1][... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00030787",
"row_id": 30787,
"seed_ids": "[347]"
} | 0.541497 | Data_Structure_30787 | I | [
"determinant",
"minor",
"transpose",
"cofactor",
"invert_matrix"
] | 5 | [
[
"cofactor",
"determinant"
],
[
"cofactor",
"minor"
],
[
"determinant",
"minor"
],
[
"invert_matrix",
"cofactor"
],
[
"invert_matrix",
"determinant"
],
[
"invert_matrix",
"transpose"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | 8c23ab8dbcafaa2e617fbc15098407acfea7def3 | 8942a5565e730a300794ffe61810518a33ca29f2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30821_I | ### Context
Spell checkers are a common tool in text editors to help users identify and correct spelling mistakes. A critical component of a spell checker is to measure how close a given word is to the correctly spelled words in its dictionary.
### Task
Write a function `find_closest_word` that, given a list of correc... | from typing import List
def edit_distance(word_a, word_b):
length_a, length_b = len(word_a) + 1, len(word_b) + 1
edit = [[0 for _ in range(length_b)] for _ in range(length_a)]
for i in range(1, length_a):
edit[i][0] = i
for j in range(1, length_b):
edit[0][j] = j
for i in range(... | from solution import find_closest_word
def test_find_closest_word_example_1():
assert find_closest_word(["food", "money", "mood", "hone"], "foond") == "food"
def test_find_closest_word_example_2():
assert find_closest_word(["spelling", "checker", "correct"], "cheker") == "checker"
def test_find_closest_word_... | [
{
"docstring": null,
"function_declaration": "def edit_distance(word_a, word_b):",
"function_name": "edit_distance",
"parameter_list": "(word_a, word_b)"
},
{
"docstring": null,
"function_declaration": "def find_closest_word(dictionary, query):",
"function_name": "find_closest_word",... | [
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 edit_distance(word_a, word_b):\n length_a, length_b = len(word_a) + 1, len(word_b) + 1\n\n edit = [[0 for _ in range(leng... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030821",
"row_id": 30821,
"seed_ids": "[31]"
} | 0.621052 | Data_Structure_30821 | I | [
"edit_distance",
"find_closest_word"
] | 2 | [
[
"find_closest_word",
"edit_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ee0740fa30e357834c6ba1da4d6d79e2dcf1bf09 | 6a9e9ff57fbd3ad670ffd24dd0e8052c0758affc | |||
v1.0 | instruct | Data_Structure | Data_Structure_30843_I | You are required to implement a function that calculates the greatest common divisor (GCD) of an array of non-negative integers using two different algorithms: Euclid's Algorithm and Bitwise Operations. Additionally, you will need to compute the least common multiple (LCM) and the number of trailing zeroes of its binar... | from functools import reduce
from math import gcd
def gcd_euclid(a, b):
while b:
a, b = b, a % b
return a
def gcd_bitwise(a, b):
if a == 0: return b
if b == 0: return a
if a == b: return a
if a & 1 == 0: # a is even
if b & 1: # b is odd
return gcd_bitwise(a >> 1, ... | from solution import array_gcd_euclid, array_gcd_bitwise, array_lcm, trailing_zero
def test_array_gcd_euclid():
assert array_gcd_euclid([24, 36, 48]) == 12
assert array_gcd_euclid([1, 2, 3, 4, 5]) == 1
assert array_gcd_euclid([12, 15, 18, 21]) == 3
assert array_gcd_euclid([3, 9, 27]) == 3
assert ar... | [
{
"docstring": null,
"function_declaration": "def gcd_euclid(a, b):",
"function_name": "gcd_euclid",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def gcd_bitwise(a, b):",
"function_name": "gcd_bitwise",
"parameter_list": "(a, b)"
},
{
"docst... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import reduce\n\ndef gcd_euclid(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef array_gcd_euclid(arr):\n return reduce(gc... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00030843",
"row_id": 30843,
"seed_ids": "[166]"
} | 0.687422 | Data_Structure_30843 | I | [
"gcd_euclid",
"gcd_bitwise",
"array_gcd_euclid",
"array_gcd_bitwise",
"array_lcm",
"trailing_zero"
] | 6 | [
[
"array_gcd_bitwise",
"gcd_bitwise"
],
[
"array_gcd_euclid",
"gcd_euclid"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | eac7ab46a3143a23c23b610df927017deb4689a4 | c750a18d62443316c24e77478d79387aff144f18 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30866_I | ### Question: Implement and Enhance Stooge Sort
#### Background
Stooge Sort is an inefficient recursive sorting algorithm with very poor performance characteristics. Despite its impracticality for large data sets, it is a useful tool for educational purposes to understand recursive sorting techniques.
#### Problem St... | def is_sorted(arr, l, h):
"""Helper function to check if a segment of the array is sorted."""
for i in range(l, h):
if arr[i] > arr[i + 1]:
return False
return True
def enhanced_stoogesort(arr, l, h):
"""Function to perform enhanced Stooge Sort on a segment of the array."""
if l... | from solution import enhanced_stoogesort
def test_sorted_array():
arr = [1, 2, 3, 4, 5]
enhanced_stoogesort(arr, 0, len(arr) - 1)
assert arr == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
arr = [5, 4, 3, 2, 1]
enhanced_stoogesort(arr, 0, len(arr) - 1)
assert arr == [1, 2, 3, 4, 5]
def te... | [
{
"docstring": "Helper function to check if a segment of the array is sorted.",
"function_declaration": "def is_sorted(arr, l, h):",
"function_name": "is_sorted",
"parameter_list": "(arr, l, h)"
},
{
"docstring": "Function to perform enhanced Stooge Sort on a segment of the array.",
"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 is_sorted(arr, l, h):\n \"\"\"\n Helper function to check if the segment of the array is sorted.\n \"\"\"\n for i in range(l, h):\n if ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030866",
"row_id": 30866,
"seed_ids": "[10]"
} | 0.572363 | Data_Structure_30866 | I | [
"is_sorted",
"enhanced_stoogesort"
] | 2 | [
[
"enhanced_stoogesort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4288458af2be99b9be0abd76d45bb96125d74e2b | de6c558d6e8ec059c0a4f8bcae93a59aed07fe34 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30872_I | ### Base Conversion Challenge
You have been provided with two functions, `int_to_base` and `base_to_int`, that convert integers to different base representations and vice versa. Your task is to extend these functionalities with additional features and handle different edge cases.
#### Objectives
1. Implement a functi... | def int_to_base(n, base):
"""Helper function to convert an integer to a given base."""
if n == 0:
return "0"
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
result = ""
negative = n < 0
n = abs(n)
while n:
result = digits[n % base] + result
n //= base
... | def test_int_to_base():
assert int_to_base(5, 2) == '101'
assert int_to_base(255, 16) == 'FF'
assert int_to_base(-10, 2) == '-1010'
assert int_to_base(0, 2) == '0'
def test_base_to_int():
assert base_to_int('101', 2) == 5
assert base_to_int('FF', 16) == 255
assert base_to_int('-1010', 2) ==... | [
{
"docstring": "Helper function to convert an integer to a given base.",
"function_declaration": "def int_to_base(n, base):",
"function_name": "int_to_base",
"parameter_list": "(n, base)"
},
{
"docstring": "Helper function to convert a base string to an integer.",
"function_declaration":... | [
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 base_converter(value, base, convert_back=False):\n \"\"\"\n :type value: str or int\n :type base: int\n :type convert_back: bool\n :rtype: ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030872",
"row_id": 30872,
"seed_ids": "[164]"
} | 0.782571 | Data_Structure_30872 | I | [
"int_to_base",
"base_to_int",
"base_converter"
] | 3 | [
[
"base_converter",
"base_to_int"
],
[
"base_converter",
"int_to_base"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | c97ce7e89e16ad30a11b786194ac83bf5c1f0566 | 134f1e6a1c5a99cf551ee20a5929756509d5566f | |||
v1.0 | instruct | Data_Structure | Data_Structure_30902_I | Enhanced Shell Sort Implementation
#### Context
Shell Sort is a generalization of insertion sort that allows the exchange of items that are far apart. The algorithm sorts elements by comparing them with each other at a certain gap and reduces this gap sequentially following a specific pattern until it reaches 1.
####... | from typing import List
def generate_pratt_sequence(n: int) -> List[int]:
"""
Generates Pratt's sequence up to the maximum value less than n.
Pratt's gaps are all products of powers of 2 and 3.
"""
gaps = set()
k = 1
while k < n:
m = k
while m < n:
gaps.add(m)
... | from solution import pratt_shell_sort
def test_pratt_shell_sort_unsorted():
assert pratt_shell_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
def test_pratt_shell_sort_random():
assert pratt_shell_sort([20, 35, -15, 7, 55, 1, -22]) == [-22, -15, 1, 7, 20, 35, 55]
def test_pratt_shell_sort_reverse():
asse... | [
{
"docstring": "Generates Pratt's sequence up to the maximum value less than n.\nPratt's gaps are all products of powers of 2 and 3.",
"function_declaration": "def generate_pratt_sequence(n):",
"function_name": "generate_pratt_sequence",
"parameter_list": "(n)"
},
{
"docstring": "Sorts the g... | [
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 generate_pratt_sequence(n: int) -> List[int]:\n \"\"\"\n Generate Pratt's sequence up to n (the length of the array to be... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00030902",
"row_id": 30902,
"seed_ids": "[22]"
} | 0.595075 | Data_Structure_30902 | I | [
"generate_pratt_sequence",
"pratt_shell_sort"
] | 2 | [
[
"pratt_shell_sort",
"generate_pratt_sequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e2c3c3efcd836f0d45650d5bf8b0d0a47580d44b | a544e7e592d22570c238003a9f003b1ce45ecda0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_30970_I | ### Question: Implement Enhanced Diffie-Hellman Key Exchange
You are tasked with implementing an enhanced version of the Diffie-Hellman key exchange algorithm. Your version needs to include additional validation checks and logging functionalities to help in debugging and understanding the flow of key generation and exc... | import random
import sympy
def is_prime(num):
"""
Check if the number is a prime.
"""
return sympy.isprime(num)
def find_primitive_root(p):
"""
Find a primitive root modulo p.
"""
if not is_prime(p):
return -1
phi = p - 1
factors = sympy.ntheory.factor_.factorint(p... | from solution import enhanced_diffie_hellman
def test_enhanced_diffie_hellman_valid_primitive_root():
# p = 23 (prime), a = 5 (primitive root of 23)
assert enhanced_diffie_hellman(5, 23) == True
def test_enhanced_diffie_hellman_invalid_prime():
# p = 24 (not a prime)
assert enhanced_diffie_hellman(5, ... | [
{
"docstring": "Check if the number is a prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Find a primitive root modulo p.",
"function_declaration": "def find_primitive_root(p):",
"function_name": "find_pr... | [
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\nimport sympy\n\ndef is_prime(num):\n \"\"\"\n Check if the number is a prime.\n \"\"\"\n return sympy.isprime(num)\n\ndef find_prim... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00030970",
"row_id": 30970,
"seed_ids": "[146]"
} | 0.453039 | Data_Structure_30970 | I | [
"is_prime",
"find_primitive_root",
"enhanced_diffie_hellman"
] | 3 | [
[
"enhanced_diffie_hellman",
"find_primitive_root"
],
[
"enhanced_diffie_hellman",
"is_prime"
],
[
"find_primitive_root",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 0b7ede3125ffaf2fc6f9615db1f29218e097136a | 70a258ed8746540b82e94dc65ddec45e187eee00 | |||
v1.0 | instruct | Data_Structure | Data_Structure_31104_I | ### Question: Large Number Bogo Sort Probability Simulation
Given the highly inefficient nature of the Bogo Sort algorithm, simulate how unlikely it is to sort even a small list of elements within a reasonable timeframe. Write a function that calculates the probability of Bogo Sort successfully sorting an array within... | import random
from typing import List, Tuple
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to determine if the array is sorted.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def bogo_sort_probability(arr: List[int], max_iterations: int) -> Tuple[bool, int]:
"""
... | from solution import bogo_sort_probability
def test_sorted_array():
assert bogo_sort_probability([1, 2, 3], 1000) == (True, 0)
def test_reverse_sorted_array():
sorted_status, iterations = bogo_sort_probability([3, 2, 1], 1000)
assert sorted_status == False or (sorted_status == True and iterations < 1000)
... | [
{
"docstring": "Helper function to determine if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Attempts to sort the array using Bogo Sort for a specified number of iterations.\nReturns:\n- True ... | [
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 typing import List, Tuple\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to determine if the array is sorted.\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00031104",
"row_id": 31104,
"seed_ids": "[16]"
} | 0.485813 | Data_Structure_31104 | I | [
"is_sorted",
"bogo_sort_probability"
] | 2 | [
[
"bogo_sort_probability",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d0abe0a764476bae6ec0484a2e299a02928d89e5 | 12716075288c1e9589ec286e1f75aa523943dd80 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.