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_8477_I | Determining Strong Connectivity in a Directed Graph
You are tasked with determining if a directed graph is strongly connected. A strongly connected graph is one where there is a path between any pair of vertices in both directions. To solve this problem, you will utilize Depth-First Search (DFS) and graph reversal tec... | from typing import List, Tuple
def dfs(graph, start, visited):
stack = [start]
while stack:
vertex = stack.pop()
if not visited[vertex]:
visited[vertex] = True
stack.extend(graph[vertex])
def is_strongly_connected(vertex_count: int, edges: List[Tuple[int, int]]) -> bool... | from solution import is_strongly_connected
def test_single_vertex():
assert is_strongly_connected(1, []) == True
def test_no_edges():
assert is_strongly_connected(3, []) == False
def test_simple_strongly_connected():
assert is_strongly_connected(3, [(0, 1), (1, 2), (2, 0)]) == True
def test_not_strongly... | [
{
"docstring": null,
"function_declaration": "def dfs(graph, start, visited):",
"function_name": "dfs",
"parameter_list": "(graph, start, visited)"
},
{
"docstring": null,
"function_declaration": "def is_strongly_connected(vertex_count, edges):",
"function_name": "is_strongly_connect... | [
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 vertex = stack.pop()\n if not visited... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00008477",
"row_id": 8477,
"seed_ids": "[225]"
} | 0.606791 | Data_Structure_8477 | I | [
"dfs",
"is_strongly_connected"
] | 2 | [
[
"is_strongly_connected",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1efbbd1c31aceeba49de88588990fed763f654f6 | d3fa706dc8526827dea1c44c4378853b258c39be | |||
v1.0 | instruct | Data_Structure | Data_Structure_8522_I | ### Matrix Inversion Challenge
You are tasked with writing a function to invert a square matrix (n x n). This involves computing the matrix of minors, cofactor matrix, adjugate, and finally multiplying by the reciprocal of the determinant.
#### Function Signature
```python
def invert_matrix(matrix: List[List[float]])... | from typing import List
def get_minor(matrix: List[List[float]], i: int, j: int) -> List[List[float]]:
"""
Returns the minor of the matrix after removing the i-th row and j-th column.
"""
return [row[:j] + row[j+1:] for k, row in enumerate(matrix) if k != i]
def get_determinant(matrix: List[List[float... | from solution import invert_matrix
def test_invert_matrix_example_1():
matrix = [[4, 7], [2, 6]]
result = invert_matrix(matrix)
expected = [[0.6, -0.7], [-0.2, 0.4]]
for i in range(2):
for j in range(2):
assert round(result[i][j], 1) == round(expected[i][j], 1)
def test_invert_matr... | [
{
"docstring": "Returns the minor of the matrix after removing the i-th row and j-th column.",
"function_declaration": "def get_minor(matrix, i, j):",
"function_name": "get_minor",
"parameter_list": "(matrix, i, j)"
},
{
"docstring": "Recursively computes the determinant of the matrix.",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef get_minor(matrix: List[List[float]], i: int, j: int) -> List[List[float]]:\n \"\"\"\n Returns the minor of the matrix aft... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00008522",
"row_id": 8522,
"seed_ids": "[347]"
} | 0.573884 | Data_Structure_8522 | I | [
"get_minor",
"get_determinant",
"get_matrix_of_minors",
"get_cofactor_matrix",
"transpose",
"invert_matrix"
] | 6 | [
[
"get_cofactor_matrix",
"get_matrix_of_minors"
],
[
"get_determinant",
"get_minor"
],
[
"get_matrix_of_minors",
"get_determinant"
],
[
"get_matrix_of_minors",
"get_minor"
],
[
"invert_matrix",
"get_cofactor_matrix"
],
[
"invert_matrix",
"get_deter... | 7 | [] | false | [] | false | pytest | true | [] | true | e45cf38084f4fe73abc08d8c2e42f68ad513b7ea | 966526fd1f5f8aee4668faf75fafa93cbe99f5da | |||
v1.0 | instruct | Data_Structure | Data_Structure_8546_I | ### Question
Given the following RSA key generation specification, implement a more efficient RSA key generator.
#### Problem Statement
You are required to implement a function `generate_rsa_keypair(k, seed=None)` that generates an RSA key pair more efficiently. You will use the Miller-Rabin primality test for gener... | import random
from typing import Tuple
def is_prime(n, k=5):
"""Miller-Rabin primality test."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
r, d = 0, n - 1
while d % 2 == 0:
r += 1
d //= 2
def check_composite(a):
... | from solution import generate_rsa_keypair
def test_generate_rsa_keypair():
n, e, d = generate_rsa_keypair(16, seed=42)
assert n > 0
assert e == 65537
assert d > 0
plaintext = 42
encrypted = pow(plaintext, e, n)
decrypted = pow(encrypted, d, n)
assert decrypted == plaintext
def test_gen... | [
{
"docstring": "Miller-Rabin primality test.",
"function_declaration": "def is_prime(n, k=5):",
"function_name": "is_prime",
"parameter_list": "(n, k=5)"
},
{
"docstring": "Generate an odd integer randomly.",
"function_declaration": "def generate_prime_candidate(length):",
"function_... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import Tuple\n\ndef miller_rabin(n, k=40):\n if n in (2, 3):\n return True\n if n % 2 == 0 or n == 1:\n return ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00008546",
"row_id": 8546,
"seed_ids": "[154]"
} | 0.574707 | Data_Structure_8546 | I | [
"is_prime",
"generate_prime_candidate",
"generate_prime_number",
"extended_gcd",
"mod_inverse",
"generate_rsa_keypair"
] | 6 | [
[
"generate_prime_number",
"generate_prime_candidate"
],
[
"generate_prime_number",
"is_prime"
],
[
"generate_rsa_keypair",
"generate_prime_number"
],
[
"generate_rsa_keypair",
"mod_inverse"
],
[
"mod_inverse",
"extended_gcd"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 40cd2b782ee130bc97825e7b41e3eefe8a6e19a7 | ec7fc14ccad46b58a4365ae02b58122f300f3a62 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8587_I | You are given two tasks:
1. **Enhance GCD Algorithm**: Modify the standard GCD algorithm to accept multiple integers and compute their GCD. You should handle any number of integers greater than two efficiently.
2. **Efficient Trailing Zero Calculation**: Implement a function to compute the trailing zeroes for multipl... | from functools import reduce
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def gcd_multiple(numbers):
"""
Returns the greatest common divisor of a list of numbers.
"""
return reduce(gcd, numbers)
def trailing_zero(x):
"""
Returns the number of trailing zeros in the bin... | from solution import gcd_multiple, trailing_zeros_array
def test_gcd_multiple():
assert gcd_multiple([45, 90, 120]) == 15
assert gcd_multiple([81, 243]) == 81
assert gcd_multiple([12, 15, 21]) == 3
assert gcd_multiple([10, 20, 30, 40]) == 10
assert gcd_multiple([5, 7, 11]) == 1
def test_trailing_z... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the greatest common divisor of a list of numbers.",
"function_declaration": "def gcd_multiple(numbers):",
"function_name": "gcd_multiple",
... | [
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\nimport math\n\ndef gcd(a, b):\n \"\"\"\n Returns the greatest common divisor (GCD) of a and b.\n \"\"\"\n while b !=... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00008587",
"row_id": 8587,
"seed_ids": "[166]"
} | 0.574278 | Data_Structure_8587 | I | [
"gcd",
"gcd_multiple",
"trailing_zero",
"trailing_zeros_array"
] | 4 | [
[
"gcd_multiple",
"gcd"
],
[
"trailing_zeros_array",
"trailing_zero"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ad2cbae985e2794d06be06ca4523ea58fce6a5b0 | ffa1f0b30ab75527cd57092c50e22b3d5426de6a | |||
v1.0 | instruct | Data_Structure | Data_Structure_8614_I | ### Binary Exponentiation Function Implementation
#### Task
Implement a function `matrix_power` that employs the principles of binary exponentiation to raise a given square matrix `matrix` to the power `n`. The function should return the resulting matrix. Assume all matrices are square matrices of size `m x m`.
#### ... | def matrix_multiply(A, B, mod=None):
"""
Multiplies two matrices A and B. If mod is specified, performs multiplication modulo 'mod'.
"""
m = len(A)
result = [[0] * m for _ in range(m)]
for i in range(m):
for j in range(m):
for k in range(m):
result[i][j] += A[... | import pytest
from solution import matrix_power
def test_matrix_power_basic():
matrix = [
[1, 1],
[1, 0]
]
n = 5
mod = 1000
expected_output = [
[8, 5],
[5, 3]
]
assert matrix_power(matrix, n, mod) == expected_output
def test_matrix_power_identity():
matr... | [
{
"docstring": "Multiplies two matrices A and B. If mod is specified, performs multiplication modulo 'mod'.",
"function_declaration": "def matrix_multiply(A, B, mod=None):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B, mod=None)"
},
{
"docstring": "Returns the identity matri... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef matrix_multiply(a: List[List[int]], b: List[List[int]], mod: int = None) -> List[List[int]]:\n m = len(a)\n result = [[0]... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00008614",
"row_id": 8614,
"seed_ids": "[151]"
} | 0.576078 | Data_Structure_8614 | I | [
"matrix_multiply",
"matrix_identity",
"matrix_power"
] | 3 | [
[
"matrix_power",
"matrix_identity"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 13bfd6dd113a7dc2d7e35b016d17056eb226d510 | bf7a7ec111b9c9abd5d13163600211dcd4b7a2ca | |||
v1.0 | instruct | Data_Structure | Data_Structure_8632_I | ### Objective:
Design a function to efficiently compute the prime numbers in a given range using the Rabin-Miller primality test algorithm.
### Problem Statement:
Write a function `find_primes_in_range(low, high, k)` that returns a list of all numbers between `low` and `high` inclusive that are prime. Use the Rabin-Mi... | import random
def miller_rabin_test(n, k):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
def power_mod(b, e, m):
res = 1
b = b % m
while e > 0:
if e % 2 == 1:
res = (res * b) % m
e ... | from solution import find_primes_in_range
def test_find_primes_in_range_example1():
assert find_primes_in_range(10, 50, 10) == [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
def test_find_primes_in_range_example2():
assert find_primes_in_range(1, 20, 5) == [2, 3, 5, 7, 11, 13, 17, 19]
def test_find_primes_in_r... | [
{
"docstring": null,
"function_declaration": "def miller_rabin_test(n, k):",
"function_name": "miller_rabin_test",
"parameter_list": "(n, k)"
},
{
"docstring": null,
"function_declaration": "def find_primes_in_range(low, high, k):",
"function_name": "find_primes_in_range",
"param... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(n, k):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ret... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00008632",
"row_id": 8632,
"seed_ids": "[136]"
} | 0.550653 | Data_Structure_8632 | I | [
"miller_rabin_test",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"miller_rabin_test"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 122ddabda8117e8f740f971c5262955e8f8639a5 | 8915f3545a6cbd3e4b670862be60fc613c66791e | |||
v1.0 | instruct | Data_Structure | Data_Structure_8682_I | **Context**: In data processing and search systems, it is often required to quickly find ranges of elements matching certain criteria. For example, consider a sorted array of integers where you frequently need to determine the range of indices where a specific number appears. This can have applications in databases, se... | def binary_search(nums, target, find_first):
left, right = 0, len(nums) - 1
result = -1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
result = mid
if find_first:
right = mid - 1
else:
left = mid + 1
... | from solution import search_range
def test_search_range_found():
assert search_range([5, 7, 7, 8, 8, 8, 10], 8) == [3, 5]
def test_search_range_not_found():
assert search_range([5, 7, 7, 8, 8, 8, 10], 11) == [-1, -1]
assert search_range([], 1) == [-1, -1]
assert search_range([1], 0) == [-1, -1]
def t... | [
{
"docstring": null,
"function_declaration": "def binary_search(nums, target, find_first):",
"function_name": "binary_search",
"parameter_list": "(nums, target, find_first)"
},
{
"docstring": "Returns the starting and ending positions of the given target in the list.\nIf the target is not fo... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_range(nums, target):\n \"\"\"\n Returns the starting and ending positions of the target in a sorted array.\n If the target is not found, r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00008682",
"row_id": 8682,
"seed_ids": "[194]"
} | 0.565374 | Data_Structure_8682 | I | [
"binary_search",
"search_range"
] | 2 | [
[
"search_range",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 740c32977d43ce4766c0f76a7aaffd373f49e53c | 8f3cb6f6ca0a7b65689be679cfff999316e5d595 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8688_I | ### Question: Insertion Sort Implementation Using Binary Search
#### Objective
Write a function that uses the `search_insert` helper method to implement the Insertion Sort algorithm. The function should sort an array of integers in ascending order.
#### Detailed Description
The Insertion Sort algorithm sorts an array... | def search_insert(array, val):
"""
Binary search helper function to locate the index where `val` should be inserted
to maintain sorted order in `array`.
"""
lo, hi = 0, len(array)
while lo < hi:
mid = (lo + hi) // 2
if array[mid] < val:
lo = mid + 1
else:
... | def test_insertion_sort_empty():
assert insertion_sort([]) == []
def test_insertion_sort_single_element():
assert insertion_sort([1]) == [1]
def test_insertion_sort_multiple_elements():
assert insertion_sort([3, 1, 2]) == [1, 2, 3]
assert insertion_sort([4, 7, 5, 2, 6]) == [2, 4, 5, 6, 7]
assert i... | [
{
"docstring": "Binary search helper function to locate the index where `val` should be inserted\nto maintain sorted order in `array`.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "Sorts an ar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(array, val):\n \"\"\"\n Helper function to perform binary search to find the index where 'val' should be inserted in 'array'.\n \"\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00008688",
"row_id": 8688,
"seed_ids": "[199]"
} | 0.559842 | Data_Structure_8688 | I | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 6a66236f707133830c9fd7b52c7c5880c190b804 | 217bf35195353970e9f509f67a7b197bc7c1b4fe | |||
v1.0 | instruct | Data_Structure | Data_Structure_8690_I | ### Bit Manipulation Challenge
**Objective**:
Write a function that takes a non-negative integer, a list of bit manipulation commands, and returns the resulting integer after applying all the commands sequentially.
**Function Signature**:
```python
def manipulate_bits(num: int, commands: List[Tuple[str, int, Optional... | from typing import List, Tuple, Optional
def get_bit(num: int, i: int) -> int:
"""
Returns the bit value at position i.
"""
return (num >> i) & 1
def set_bit(num: int, i: int) -> int:
"""
Sets the bit at position i to 1.
"""
return num | (1 << i)
def clear_bit(num: int, i: int) -> int... | from solution import manipulate_bits
def test_set_command():
assert manipulate_bits(73, [("set", 1)]) == 75 # 1001001 -> 1001011
def test_clear_command():
assert manipulate_bits(75, [("clear", 6)]) == 11 # 1001011 -> 0001011
def test_update_command():
assert manipulate_bits(11, [("update", 2, 1)]) ==... | [
{
"docstring": "Returns the bit value at position i.",
"function_declaration": "def get_bit(num, i):",
"function_name": "get_bit",
"parameter_list": "(num, i)"
},
{
"docstring": "Sets the bit at position i to 1.",
"function_declaration": "def set_bit(num, i):",
"function_name": "set_... | [
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, Tuple, Optional\n\ndef manipulate_bits(num: int, commands: List[Tuple[str, int, Optional[int]]]) -> int:\n def get_bit(number: int... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00008690",
"row_id": 8690,
"seed_ids": "[212]"
} | 0.638924 | Data_Structure_8690 | I | [
"get_bit",
"set_bit",
"clear_bit",
"update_bit",
"manipulate_bits"
] | 5 | [
[
"manipulate_bits",
"clear_bit"
],
[
"manipulate_bits",
"set_bit"
],
[
"manipulate_bits",
"update_bit"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 93531ff2f6977ad07a9c7f2f1f6a83c9ccab169e | adcfc0f4bb8a70e003a135d177576d59870f6132 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8706_I | ### Coding Challenge: Count Strobogrammatic Numbers in a Range
**Problem Statement**:
A strobogrammatic number is a number that looks the same when rotated 180 degrees (it appears the same upside down). Write a function to count the total strobogrammatic numbers that exist in a range of two integers, `low` and `high` ... | def is_strobogrammatic(num):
"""
Check if a number is strobogrammatic.
"""
strobogrammatic_pairs = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
left, right = 0, len(num) - 1
while left <= right:
if num[left] not in strobogrammatic_pairs or strobogrammatic_pairs[num[left]] != num[ri... | from solution import count_strobogrammatic_in_range
def test_single_digit_range():
assert count_strobogrammatic_in_range("0", "9") == 3 # 0, 1, 8
def test_small_range():
assert count_strobogrammatic_in_range("50", "100") == 3 # 69, 88, 96
def test_no_strobogrammatic():
assert count_strobogrammatic_in_r... | [
{
"docstring": "Check if a number is strobogrammatic.",
"function_declaration": "def is_strobogrammatic(num):",
"function_name": "is_strobogrammatic",
"parameter_list": "(num)"
},
{
"docstring": "Count all strobogrammatic numbers in the inclusive range [low, high].",
"function_declaratio... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_strobogrammatic_in_range(low: str, high: str) -> int:\n \"\"\"\n Return the count of strobogrammatic numbers within the inclusive range [low, ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00008706",
"row_id": 8706,
"seed_ids": "[140]"
} | 0.588152 | Data_Structure_8706 | I | [
"is_strobogrammatic",
"count_strobogrammatic_in_range"
] | 2 | [
[
"count_strobogrammatic_in_range",
"is_strobogrammatic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e3f91016a23c0f7503adf0de2aedb80c9c058fbc | 5093b0285cc2589e2c3167cc05b149a01b4e4c14 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8716_I | ### Huffman Coding Question
#### Context
Huffman coding is a well-known method for compressing data without losing information. The algorithm assigns shorter binary codes to more frequent characters and longer codes to less frequent ones, thus reducing the overall size of the data.
#### Problem Statement
You are give... | import heapq
import os
from collections import defaultdict, Counter
import struct
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_hu... | import os
import pytest
from solution import compress_data, decompress_data
# Helper function to create test files
def create_test_file(file_path, content):
with open(file_path, 'w') as file:
file.write(content)
def test_huffman_compression_decompression():
input_path = 'test_input.txt'
compressed... | [] | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nfrom collections import defaultdict, Counter\nimport os\n\nclass HuffmanNode:\n def __init__(self, char=None, freq=0):\n self.char = c... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00008716",
"row_id": 8716,
"seed_ids": "[335]"
} | 0.611584 | Data_Structure_8716 | I | [
"build_huffman_tree",
"build_codes",
"compress_data",
"encode_huffman_tree",
"decode_huffman_tree",
"decode_huffman_tree_helper",
"decompress_data"
] | 7 | [
[
"compress_data",
"build_codes"
],
[
"compress_data",
"build_huffman_tree"
],
[
"compress_data",
"encode_huffman_tree"
],
[
"decode_huffman_tree",
"decode_huffman_tree_helper"
],
[
"decompress_data",
"decode_huffman_tree"
]
] | 5 | [] | false | [
"HuffmanNode"
] | true | pytest | true | [] | true | 2d6d85860e178f3c1c9d2de9060f2f278bbd6ddd | 449f6696efe3b3c36b87e0232075d77298a2632c | |||
v1.0 | instruct | Data_Structure | Data_Structure_8765_I | ### Question: Advanced Arithmetic Operations with Bitwise Optimization
#### Context
You are tasked with creating a mathematical utility library for arithmetic operations often needed in cryptographic applications. Handling very large integer operations efficiently and safely is critical. Therefore, bitwise operations ... | def optimized_gcd(a, b):
"""
Calculate the Greatest Common Divisor (GCD) of two integers `a` and `b` using bitwise operations.
"""
if a == 0:
return abs(b)
if b == 0:
return abs(a)
a, b = abs(a), abs(b)
shift = count_trailing_zeros(a | b)
a >>= count_trailing_ze... | from solution import optimized_gcd, optimized_lcm, count_trailing_zeros
def test_optimized_gcd():
assert optimized_gcd(34, 17) == 17
assert optimized_gcd(21, 6) == 3
assert optimized_gcd(100, 10) == 10
assert optimized_gcd(0, 5) == 5
assert optimized_gcd(5, 0) == 5
assert optimized_gcd(12, 15) ... | [
{
"docstring": "Calculate the Greatest Common Divisor (GCD) of two integers `a` and `b` using bitwise operations.",
"function_declaration": "def optimized_gcd(a, b):",
"function_name": "optimized_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate the Least Common Multiple (LCM) of... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_gcd(a, b):\n \"\"\"\n Calculate the Greatest Common Divisor (GCD) of two integers a and b using bitwise operations.\n \"\"\"\n if a ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00008765",
"row_id": 8765,
"seed_ids": "[166]"
} | 0.613041 | Data_Structure_8765 | I | [
"optimized_gcd",
"optimized_lcm",
"count_trailing_zeros"
] | 3 | [
[
"optimized_gcd",
"count_trailing_zeros"
],
[
"optimized_lcm",
"optimized_gcd"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 86d16725306c28f48be38b47def3f42588c24188 | 8a0edab7041a5650aaf66ba609bd1ab741457ee6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8772_I | ### Maximum Network Flow - Advanced Implementation
You are given a function `maximum_flow_dfs` which calculates the maximum flow in a network using the Ford-Fulkerson algorithm with Depth-First Search (DFS). The graph is represented by an adjacency matrix where `graph[i][j]` defines the capacity of the edge from node ... | from typing import List
from collections import deque
def bfs(residual_graph, source, sink, parent):
visited = [False] * len(residual_graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(residual_graph[u]):
if ... | from solution import maximum_flow_bfs
def test_simple_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow_bfs(graph) == 23
def test_no_flow():
... | [
{
"docstring": null,
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(adjacency_matrix):",
"function_name"... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List\n\ndef bfs(residual_graph: List[List[int]], parent: List[int], source: int, sink: int) -> bool:\n vi... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00008772",
"row_id": 8772,
"seed_ids": "[241]"
} | 0.595681 | Data_Structure_8772 | I | [
"bfs",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d1e3d0d70a4b808b23913f430b2e5ef77a22e9c7 | 864eda080fa8ac52305649a918c88146e82b4cb2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8776_I | Secure Key Exchange with Diffie-Hellman
Given an implementation of the Diffie-Hellman key exchange protocol, you need to write a function that validates the process of securely generating and exchanging keys between two parties, Alice and Bob.
#### Function Signature
```python
def validate_diffie_hellman(a: int, p: i... | def is_prime(n):
"""Check if a number is a prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def po... | from solution import validate_diffie_hellman, is_prime, find_primitive_root, diffie_hellman_key_exchange
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(23) == True
assert is_prime(24) == False
def test_find_primitive_root():
... | [
{
"docstring": "Check if a number is a prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Compute (base^exp) % mod efficiently.",
"function_declaration": "def power_modulo(base, exp, mod):",
"function_name": "p... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def 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_5 | {
"original_instruction": "",
"prompt_id": "00008776",
"row_id": 8776,
"seed_ids": "[146]"
} | 0.481159 | Data_Structure_8776 | I | [
"is_prime",
"power_modulo",
"find_primitive_root",
"diffie_hellman_key_exchange",
"validate_diffie_hellman"
] | 5 | [
[
"diffie_hellman_key_exchange",
"is_prime"
],
[
"diffie_hellman_key_exchange",
"power_modulo"
],
[
"find_primitive_root",
"is_prime"
],
[
"find_primitive_root",
"power_modulo"
],
[
"validate_diffie_hellman",
"diffie_hellman_key_exchange"
],
[
"validat... | 7 | [] | false | [] | false | pytest | true | [] | true | 302cb2f0cad16c46f9c792c03b1a0eca7514e4ee | 5ed307b761eedf7d22dc049f077131b772ce010c | |||
v1.0 | instruct | Data_Structure | Data_Structure_8806_I | You are required to implement a sorting algorithm using a binary heap. Your task is to implement a function that uses a max heap to sort an array of integers in ascending order and another function that uses a min heap to sort an array of integers in descending order. Additionally, simulate each step of the heapify pro... | def max_heapify(arr, n, i, iteration, simulation):
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], ... | from solution import max_heap_sort, min_heap_sort
def test_max_heap_sort():
assert max_heap_sort([3, 1, 5, 2, 4]) == [1, 2, 3, 4, 5]
assert max_heap_sort([]) == []
assert max_heap_sort([-1, -2, -3]) == [-3, -2, -1]
assert max_heap_sort([10, 20, 30, 5]) == [5, 10, 20, 30]
assert max_heap_sort([1, 2,... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, iteration, simulation):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, iteration, simulation)"
},
{
"docstring": null,
"function_declaration": "def max_heap_sort(arr, simulation=False):",
"func... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef max_heapify(arr: List[int], n: int, i: int, simulation: bool) -> None:\n largest = i\n left = 2 * i + 1\n right = 2 * ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00008806",
"row_id": 8806,
"seed_ids": "[8]"
} | 0.722024 | Data_Structure_8806 | 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 | true | [] | true | 74399ac47697eab0550f36cb081c0032f552c7aa | 716926ba6130fc77051c6a72c50c7d21bfbef219 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8915_I | ### Question: Implement and Compare Sorting Algorithms
#### Context:
Sorting is a fundamental operation in many applications, and understanding different sorting algorithms helps in choosing the most efficient one for a given context. You've seen Stooge Sort, an inefficient sorting algorithm. It's time to implement an... | import time
from typing import List
def stoogesort(arr: List[int], l: int, h: int) -> None:
if l >= h:
return
if arr[l] > arr[h]:
arr[l], arr[h] = arr[h], arr[l]
if h - l + 1 > 2:
t = (h - l + 1) // 3
stoogesort(arr, l, h - t)
stoogesort(arr, l + t, h)
stooge... | from solution import stoogesort, insertion_sort, compare_sorts
import time
def test_stoogesort():
arr = [5, 4, 3, 2, 1]
expected = [1, 2, 3, 4, 5]
stoogesort(arr, 0, len(arr) - 1)
assert arr == expected
def test_insertion_sort():
arr = [5, 4, 3, 2, 1]
expected = [1, 2, 3, 4, 5]
assert inse... | [
{
"docstring": null,
"function_declaration": "def stoogesort(arr, l, h):",
"function_name": "stoogesort",
"parameter_list": "(arr, l, h)"
},
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
... | [
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 time\nfrom typing import List\n\ndef stoogesort(arr: List[int], l: int, h: int) -> None:\n if l >= h:\n return\n if arr[l] > arr[h]:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00008915",
"row_id": 8915,
"seed_ids": "[10]"
} | 0.585104 | Data_Structure_8915 | I | [
"stoogesort",
"insertion_sort",
"compare_sorts"
] | 3 | [
[
"compare_sorts",
"insertion_sort"
],
[
"compare_sorts",
"stoogesort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fc35ca808e449d672cbbaa67fed6bcf9be1a2204 | 81edc4e9cf7fee8e0a4799a59df8836f695695f6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8944_I | ### Merge Sort Implementation Exercise
**Background**:
Merge Sort is a classic sorting algorithm that employs a divide-and-conquer approach to sort elements in an array. The algorithm recursively splits the array into smaller subarrays until subarrays of size one are obtained. It then merges these subarrays in a sorte... | from typing import List
def merge(left: List[int], right: List[int], merged: List[int]) -> None:
"""Merge two sorted sublists left and right into merged in sorted order."""
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged[k] = left[i]
i +=... | from solution import merge_sort
def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_identical_elements():
assert merge_sort([7, 7, 7, 7, 7]) == [7, 7, 7, 7, 7]
def test_merge_sort_sorted_array():
asser... | [
{
"docstring": "Merge two sorted sublists left and right into merged in sorted order.",
"function_declaration": "def merge(left, right, merged):",
"function_name": "merge",
"parameter_list": "(left, right, merged)"
},
{
"docstring": "Sorts the array using merge sort algorithm.",
"functio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_ha... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00008944",
"row_id": 8944,
"seed_ids": "[12]"
} | 0.698648 | Data_Structure_8944 | I | [
"merge",
"merge_sort"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 361ddf108bde908a88a0acb0f55c778d7e4e9784 | 0562e777be14a1814c70179a6a27b857b62f3b85 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8954_I | ### RSA Key Generation Enhanced
Given the RSA key generation algorithm provided, write a function that optimizes the modular inverse calculation by using the Extended Euclidean Algorithm for greater efficiency. Additionally, ensure the generated primes `p` and `q` are robust using a probabilistic primality test such a... | import random
from sympy import isprime
def modular_inverse(e, phi):
# Using the Extended Euclidean Algorithm
t1, t2 = 0, 1
r1, r2 = phi, e
while r2 != 0:
quotient = r1 // r2
r1, r2 = r2, r1 - quotient * r2
t1, t2 = t2, t1 - quotient * t2
if t1 < 0:
t1 += phi
ret... | from solution import enhanced_generate_key
def test_key_generation_small_k():
n, e, d = enhanced_generate_key(16, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
data = 20
encrypted = pow(data, e, n)
decrypted = pow(encrypted, d, n)
assert dec... | [
{
"docstring": null,
"function_declaration": "def modular_inverse(e, phi):",
"function_name": "modular_inverse",
"parameter_list": "(e, phi)"
},
{
"docstring": null,
"function_declaration": "def miller_rabin(n, k=40):",
"function_name": "miller_rabin",
"parameter_list": "(n, k=40... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime\n\ndef modular_inverse(e, phi):\n # Using the Extended Euclidean Algorithm\n t1, t2 = 0, 1\n r1, r2 = phi, e... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00008954",
"row_id": 8954,
"seed_ids": "[154]"
} | 0.553798 | Data_Structure_8954 | I | [
"modular_inverse",
"miller_rabin",
"generate_large_prime",
"enhanced_generate_key"
] | 4 | [
[
"enhanced_generate_key",
"generate_large_prime"
],
[
"enhanced_generate_key",
"modular_inverse"
],
[
"generate_large_prime",
"miller_rabin"
]
] | 3 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 969e9ea62d9ce971ad4a53a035f1769fc5462f5c | 979a422638667381e295a1ed979f971aebe12bca | |||
v1.0 | instruct | Data_Structure | Data_Structure_9066_I | Given a square matrix and an integer \( n \), implement a function to compute the power of the matrix raised to \( n \). Use matrix multiplication and identity matrix functions provided.
### Function Signature
```python
def matrix_power(matrix: list, n: int) -> list:
"""
Computes the n-th power of a given matr... | def identity_matrix(size):
"""
Creates and returns an identity matrix of the given size.
"""
return [[1 if i == j else 0 for j in range(size)] for i in range(size)]
def multiply_matrices(matrix1, matrix2):
"""
Multiplies two square matrices and returns the result.
"""
size = len(matrix1... | from solution import matrix_power
def test_identity_matrix():
matrix = [[1, 2], [3, 4]]
n = 0
result = matrix_power(matrix, n)
expected = [[1, 0], [0, 1]]
assert result == expected
def test_power_of_one():
matrix = [[1, 2], [3, 4]]
n = 1
result = matrix_power(matrix, n)
expected = ... | [
{
"docstring": "Creates and returns an identity matrix of the given size.",
"function_declaration": "def identity_matrix(size):",
"function_name": "identity_matrix",
"parameter_list": "(size)"
},
{
"docstring": "Multiplies two square matrices and returns the result.",
"function_declarati... | [
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 identity_matrix(size):\n \"\"\"\n Creates and returns an identity matrix of the given size.\n \"\"\"\n return [[1 if i == j else 0 for j in ra... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00009066",
"row_id": 9066,
"seed_ids": "[340]"
} | 0.550756 | Data_Structure_9066 | I | [
"identity_matrix",
"multiply_matrices",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity_matrix"
],
[
"matrix_power",
"multiply_matrices"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cd1063803c8186ac4fccc434f923c7feb97cd966 | 4ee35f6e1288981638edd2552874d8dbc9d45742 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9079_I | ### Array Rotation Problem
Suppose you are an engineer working on a new feature for a data streaming service. One of the functionalities involves manipulating a circular buffer where data is constantly being rotated. You need to implement an efficient array rotation algorithm to meet the high performance requirements ... | from typing import List
def rotate_array(array: List[int], k: int) -> List[int]:
"""
Rotates the array to the right by k steps.
:param array: List[int] - the array to be rotated.
:param k: int - the number of steps to rotate the array.
:return: List[int] - the rotated array.
"""
if not... | from solution import rotate_array
def test_rotate_array_basic():
assert rotate_array([1, 2, 3, 4, 5, 6, 7], 3) == [5, 6, 7, 1, 2, 3, 4]
def test_rotate_array_no_rotation():
assert rotate_array([1], 0) == [1]
assert rotate_array([], 5) == []
def test_rotate_array_single_element():
assert rotate_array(... | [
{
"docstring": "Rotates the array to the right by k steps.\n\n:param array: List[int] - the array to be rotated.\n:param k: int - the number of steps to rotate the array.\n:return: List[int] - the rotated array.",
"function_declaration": "def rotate_array(array, k):",
"function_name": "rotate_array",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rotate_array(array: List[int], k: int) -> List[int]:\n \"\"\"\n Rotates the array to the right by k steps.\n \n :pa... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009079",
"row_id": 9079,
"seed_ids": "[283]"
} | 0.559507 | Data_Structure_9079 | I | [
"rotate_array",
"reverse"
] | 2 | [
[
"rotate_array",
"reverse"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1916656853fadf0cd1c689f14582704c7adcd4f6 | f87a5326c57edae91ccf734c3dd4eecad076f84f | |||
v1.0 | instruct | Data_Structure | Data_Structure_9182_I | Your task is to implement a function that uses a max-heap to sort an array of integers in ascending order. You are provided with the definitions of `max_heap_sort` and `max_heapify` functions which can be used as reference. Additionally, you are required to simulate and print each iteration of the sorting process.
###... | def max_heapify(arr, n, i):
"""
Helper function to maintain the max-heap property.
"""
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i], arr... | from solution import max_heap_sort
def test_sorted_empty_list():
assert max_heap_sort([]) == []
def test_sorted_single_element():
assert max_heap_sort([10]) == [10]
def test_sorted_duplicate_elements():
assert max_heap_sort([1, 1, 1, 1]) == [1, 1, 1, 1]
def test_sorted_positive_numbers():
assert max... | [
{
"docstring": "Helper function to maintain the max-heap property.",
"function_declaration": "def max_heapify(arr, n, i):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Function to sort an array of integers in ascending order using a max-heap.",
"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 max_heapify(arr, n, i):\n \"\"\"\n Maintain the max-heap property for the subtree rooted at index i.\n \"\"\"\n largest = i # Initialize ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00009182",
"row_id": 9182,
"seed_ids": "[8]"
} | 0.662561 | Data_Structure_9182 | I | [
"max_heapify",
"max_heap_sort"
] | 2 | [
[
"max_heap_sort",
"max_heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 66d999ef90a381da9ef82afda247b2673e6be0ba | bf42d3d0635f4effeeb0409290cabbc524faafb7 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9187_I | ### Endianness Conversion and Validation
**Objective**: Write functions to convert integers to bytes (both big-endian and little-endian) and convert bytes back to integers. Additionally, implement a validation function to ensure accuracy of the conversion processes.
### Specifications
1. **Function**: `int_to_bytes_... | def int_to_bytes_big_endian(num):
"""
Convert an integer to its big-endian byte representation.
"""
return num.to_bytes((num.bit_length() + 7) // 8 or 1, 'big')
def int_to_bytes_little_endian(num):
"""
Convert an integer to its little-endian byte representation.
"""
return num.to_bytes(... | def test_int_to_bytes_big_endian_zero():
assert int_to_bytes_big_endian(0) == b'\x00'
def test_int_to_bytes_big_endian_positive():
assert int_to_bytes_big_endian(4660) == b'\x12\x34'
def test_int_to_bytes_little_endian_zero():
assert int_to_bytes_little_endian(0) == b'\x00'
def test_int_to_bytes_little_e... | [
{
"docstring": "Convert an integer to its big-endian byte representation.",
"function_declaration": "def int_to_bytes_big_endian(num):",
"function_name": "int_to_bytes_big_endian",
"parameter_list": "(num)"
},
{
"docstring": "Convert an integer to its little-endian byte representation.",
... | [
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 int_to_bytes_big_endian(num: int) -> bytes:\n \"\"\"\n Convert an integer to its big-endian byte representation.\n \"\"\"\n return num.to_byte... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00009187",
"row_id": 9187,
"seed_ids": "[216]"
} | 0.504348 | Data_Structure_9187 | I | [
"int_to_bytes_big_endian",
"int_to_bytes_little_endian",
"bytes_big_endian_to_int",
"bytes_little_endian_to_int",
"validate_conversion"
] | 5 | [
[
"validate_conversion",
"bytes_big_endian_to_int"
],
[
"validate_conversion",
"bytes_little_endian_to_int"
],
[
"validate_conversion",
"int_to_bytes_big_endian"
],
[
"validate_conversion",
"int_to_bytes_little_endian"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | dd91a820071a92f11b70dbc7d72cf3af939638a0 | 4ad58deff606bbc06fb2a378b81c240651c0cd74 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9200_I | ### Primitive Root Determination and Totient Calculation
#### Problem Statement
You are given a series of functions related to primitive root determination and Euler's totient function. These functions can be very useful in fields such as cryptography. Your task is to write a function that combines these individual fu... | from math import gcd
def euler_totient(n):
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1
if n > 1:
result -= result // n
return result
def find_order(a, n):
if gcd(a, n) !... | from solution import primitive_root_presence
def test_primitive_root_presence_for_prime():
assert primitive_root_presence(7) == True, "Test case for prime number 7 failed."
def test_primitive_root_presence_for_non_prime():
assert primitive_root_presence(10) == False, "Test case for non-prime number 10 failed.... | [
{
"docstring": null,
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def find_order(a, n):",
"function_name": "find_order",
"parameter_list": "(a, n)"
},
{
"docstri... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def euler_totient(n):\n \"\"\"\n Compute the Euler's Totient function ϕ(n) for a given integer n.\n \"\"\"\n if n == 1:\n return 1\n res... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00009200",
"row_id": 9200,
"seed_ids": "[160]"
} | 0.537867 | Data_Structure_9200 | I | [
"euler_totient",
"find_order",
"find_primitive_root",
"primitive_root_presence"
] | 4 | [
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"find_order"
],
[
"primitive_root_presence",
"find_primitive_root"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 30d9cdf50916d555616f3a60064b8314c3b8d218 | a929f5b6b4b2ab8a7a563be11863ed229cd2346b | |||
v1.0 | instruct | Data_Structure | Data_Structure_9228_I | #### Context:
You are tasked with improving the performance of a network optimization software. One of the core functionalities is to calculate the maximum flow from a source to a sink in a network represented by an adjacency matrix.
#### Problem Statement:
Write a function `find_maximum_flow(graph)` that computes the... | from typing import List
from collections import deque
def bfs(residual_graph, source, sink, parent):
visited = [False] * len(residual_graph)
queue = deque([source])
visited[source] = True
while queue:
current = queue.popleft()
for idx, capacity in enumerate(residual_graph[current]):
... | from solution import find_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 find_maximum_flow(graph) == 23
def test_single_pat... | [
{
"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 find_maximum_flow(graph):",
"function_name": "find_ma... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(graph, source, sink, parent):\n visited = [False] * len(graph)\n queue = deque([source])\n visited[source] =... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009228",
"row_id": 9228,
"seed_ids": "[229]"
} | 0.665524 | Data_Structure_9228 | I | [
"bfs",
"find_maximum_flow"
] | 2 | [
[
"find_maximum_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9f13e7422e509e385246f8ea1431151504a72c7d | 35fe6ca4a1b2c5f05d41dc494f957b6b35804108 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9241_I | Merge Sort Implementation
#### Context
You have been asked to implement a sorting algorithm for a software application that processes large datasets efficiently. Given the need for consistent performance regardless of the input data and the preservation of the relative order of equivalent elements, you've decided to u... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts the input list of integers using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(... | from solution import merge_sort
def test_merge_sort_with_empty_list():
assert merge_sort([]) == []
def test_merge_sort_with_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_with_multiple_elements():
assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
def test_merge_sort_with_r... | [
{
"docstring": "Sorts the input list of integers using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into a single sorted list.",
"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": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list using the merge sort algorithm.\n :param arr: List of... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009241",
"row_id": 9241,
"seed_ids": "[12]"
} | 0.666688 | Data_Structure_9241 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 79c2211ff3ff94317c4ddee72124f47659aa6bf6 | 0f854bab4eb5292f967f953954d167866d01ad0d | |||
v1.0 | instruct | Data_Structure | Data_Structure_9282_I | You are given an array of floating-point numbers in the range [0, 1). Implement a function `optimized_bucket_sort` that sorts this array using the Bucket Sort algorithm. Each bucket should be sorted using the Insertion Sort algorithm.
### Expected Input and Output
- **Input**:
```python
def optimized_bucket_sort(... | from typing import List
def insertion_sort(bucket: List[float]) -> List[float]:
for i in range(1, len(bucket)):
key = bucket[i]
j = i - 1
while j >= 0 and key < bucket[j]:
bucket[j + 1] = bucket[j]
j -= 1
bucket[j + 1] = key
return bucket
def optimized_b... | from solution import optimized_bucket_sort
def test_bucket_sort_normal_case():
assert optimized_bucket_sort([0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12]) == [0.12, 0.17, 0.21, 0.26, 0.39, 0.72, 0.78, 0.94]
def test_bucket_sort_different_case():
assert optimized_bucket_sort([0.42, 0.32, 0.97, 0.13, 0.58, 0... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(bucket):",
"function_name": "insertion_sort",
"parameter_list": "(bucket)"
},
{
"docstring": null,
"function_declaration": "def optimized_bucket_sort(arr):",
"function_name": "optimized_bucket_sort",
"parameter_list... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[float]) -> List[float]:\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009282",
"row_id": 9282,
"seed_ids": "[26]"
} | 0.579723 | Data_Structure_9282 | I | [
"insertion_sort",
"optimized_bucket_sort"
] | 2 | [
[
"optimized_bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d8e33358c64e158b77b2766ced23bb9519d02e54 | 7dcab94feef8c3d824ed58bddf0dd4ce8fd9d500 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9307_I | ## Maximum Flow Problem: Advanced Implementation with Edge Cases Handling
### Context
You are a software engineer tasked with optimizing traffic flow in a city’s road network. You need to model the flow of traffic using a graph, where intersections are represented by vertices, roads by edges, and the maximum capacity ... | from collections import deque
def bfs(level, capacity, source, sink, n):
visited = [False] * n
queue = deque([source])
visited[source] = True
level[source] = 0
while queue:
node = queue.popleft()
for i in range(n):
if not visited[i] and capacity[node][i]:
... | def test_compute_max_flow_simple():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert compute_max_flow(capacity... | [
{
"docstring": null,
"function_declaration": "def bfs(level, capacity, source, sink, n):",
"function_name": "bfs",
"parameter_list": "(level, capacity, source, sink, n)"
},
{
"docstring": null,
"function_declaration": "def dfs(flow, capacity, level, start, sink, n):",
"function_name"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List\n\ndef compute_max_flow(capacity: List[List[int]], source: int, sink: int) -> int:\n n = len(capacit... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00009307",
"row_id": 9307,
"seed_ids": "[240]"
} | 0.626036 | Data_Structure_9307 | I | [
"bfs",
"dfs",
"compute_max_flow"
] | 3 | [
[
"compute_max_flow",
"bfs"
],
[
"compute_max_flow",
"dfs"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | d7035a1703f0ae5613d132f2675a80015fbb7d64 | 892d42bc1c32ef2c99d2ba2e45b67db5b86c9248 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9397_I | ### Shell Sort Enhancement
Your task is to implement a function following the principles of Shell Sort, but with an optimized gap sequence. One such sequence is Sedgewick's gap sequence: gaps chosen as 4^k + 3*2^(k-1) + 1 for `k >= 1`. This should improve performance over the simple halving gap sequence given in the pr... | from typing import List
def sedgewick_gaps(size):
"""Generate Sedgewick's gap sequence for a given list size."""
k = 0
gaps = []
while True:
gap = (4**k + 3 * 2**(k-1) + 1) if k > 0 else 1
if gap > size:
break
gaps.insert(0, gap)
k += 1
return gaps
def o... | from solution import optimized_shell_sort
def test_optimized_shell_sort_example_cases():
assert optimized_shell_sort([12, 34, 54, 2, 3]) == [2, 3, 12, 34, 54]
assert optimized_shell_sort([4, 3, 2, 1]) == [1, 2, 3, 4]
assert optimized_shell_sort([]) == []
assert optimized_shell_sort([5]) == [5]
def tes... | [
{
"docstring": "Generate Sedgewick's gap sequence for a given list size.",
"function_declaration": "def sedgewick_gaps(size):",
"function_name": "sedgewick_gaps",
"parameter_list": "(size)"
},
{
"docstring": "Sorts an array using Shell Sort with Sedgewick's gap sequence.",
"function_decl... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef optimized_shell_sort(arr: List[int]) -> List[int]:\n def generate_sedgewick_gaps(n):\n gaps = []\n k = 1\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00009397",
"row_id": 9397,
"seed_ids": "[22]"
} | 0.600728 | Data_Structure_9397 | I | [
"sedgewick_gaps",
"optimized_shell_sort"
] | 2 | [
[
"optimized_shell_sort",
"sedgewick_gaps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d390997d92207a6f117142d8f95fe0e72215e6ed | 0922183d0881296dc51add382abdc0a40fab96d4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9423_I | ### Question: Implement an Enhanced Diffie-Hellman Key Exchange with Optimized Prime Generation
#### Problem Statement:
In this task, you are required to optimize the Diffie-Hellman key exchange algorithm by implementing your own prime number generator using the Miller-Rabin primality test. Additionally, ensure that t... | import random
def miller_rabin_pass(a, s, d, n):
"""Performs one iteration of the Miller-Rabin Primality Test"""
a_to_power = pow(a, d, n)
if a_to_power == 1:
return True
for i in range(s - 1):
if a_to_power == n - 1:
return True
a_to_power = (a_to_power * a_to_power... | from solution import generate_large_prime, find_primitive_root, optimized_diffie_hellman
def test_generate_large_prime():
prime = generate_large_prime(16)
assert is_prime(prime)
assert prime.bit_length() == 16
def test_find_primitive_root():
prime = generate_large_prime(16)
primitive_root = find_p... | [
{
"docstring": "Performs one iteration of the Miller-Rabin Primality Test",
"function_declaration": "def miller_rabin_pass(a, s, d, n):",
"function_name": "miller_rabin_pass",
"parameter_list": "(a, s, d, n)"
},
{
"docstring": "Uses the Miller-Rabin Primality Test to check if a number is pri... | [
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 miller_rabin_pass(a, s, d, n):\n \"\"\"Performs one iteration of the Miller-Rabin Primality Test\"\"\"\n a_to_power = pow(a, d, n)\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00009423",
"row_id": 9423,
"seed_ids": "[146]"
} | 0.501727 | Data_Structure_9423 | I | [
"miller_rabin_pass",
"is_prime",
"generate_large_prime",
"find_primitive_root",
"optimized_diffie_hellman"
] | 5 | [
[
"find_primitive_root",
"is_prime"
],
[
"generate_large_prime",
"is_prime"
],
[
"is_prime",
"miller_rabin_pass"
],
[
"optimized_diffie_hellman",
"find_primitive_root"
],
[
"optimized_diffie_hellman",
"generate_large_prime"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 04b4a64aabbc46488da1b269bb6f1ba392c13f5e | 75bf7505a0a393ab780713823f0aef76a3e95783 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9438_I | ### Diffie-Hellman Key Exchange Implementation
### Problem Statement
You are tasked with implementing the Diffie-Hellman key exchange process for secure communication between two parties, Alice and Bob. From the context given above, design functions using Python that perform key generation, key exchange, and shared ke... | import math
from random import randint
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 fi... | from solution import is_prime, find_primitive_root, diffie_hellman_key_exchange
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(29) == True
assert is_prime(100) == False
def test_find_primitive_root():
assert set(find_primi... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def find_order(a, n):",
"function_name": "find_order",
"parameter_list": "(a, n)"
},
{
"docstring": null,... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom random import randint\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00009438",
"row_id": 9438,
"seed_ids": "[146]"
} | 0.522864 | Data_Structure_9438 | I | [
"is_prime",
"find_order",
"euler_totient",
"find_primitive_root",
"alice_private_key",
"alice_public_key",
"bob_private_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"diffie_hellman_key_exchange"
] | 11 | [
[
"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... | 10 | [] | false | [] | false | pytest | true | [] | true | f88885b1379c0b7c60618cb5e94f020b80e06410 | cd85c2150d6f012689f8d7132a9199a0b652eaf9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9447_I | You are tasked with implementing an in-place sorting algorithm known as Pancake Sort. This algorithm sorts an array by repeatedly flipping (reversing) the unsorted portion of the array to move the largest unsorted element to its correct position. Your implementation should follow the typical steps of the Pancake Sort a... | def flip(arr, k):
"""
This helper function reverses the order of the first k elements in the array.
"""
start = 0
while start < k:
arr[start], arr[k] = arr[k], arr[start]
start += 1
k -= 1
def pancake_sort(arr):
"""
This function sorts an array using the Pancake Sort... | from solution import pancake_sort
def test_pancake_sort():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
assert pancake_sort([10, 9, 8, 7]) == [7, 8, 9, 10]
assert pancake_sort([5, 2, 2, 5]) == [2, 2, 5, 5]
assert pancake_sort([1]) == [1]
assert pancake_sort([-1, 0, 1]) == [-1, 0, 1]
assert... | [
{
"docstring": "This helper function reverses the order of the first k elements in the array.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "This function sorts an array using the Pancake Sort algorithm.",
"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": "def pancake_sort(arr):\n def flip(sub_arr, k):\n \"\"\"\n Function to reverse the first k elements of sub_arr\n \"\"\"\n start ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009447",
"row_id": 9447,
"seed_ids": "[9]"
} | 0.741091 | Data_Structure_9447 | I | [
"flip",
"pancake_sort"
] | 2 | [
[
"pancake_sort",
"flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fec6536c8751ce949ca11c541f4de5d2a8d4b090 | bea2879d0512f23297c0239b24d01a7e7bc7ef5e | |||
v1.0 | instruct | Data_Structure | Data_Structure_9454_I | ### Nearest Neighbor with Optimized Search
#### Context
You are tasked with implementing an optimized version of the nearest neighbor search algorithm for a machine learning project. This implementation should be efficient and handle typical edge cases well. Your goal is to provide a faster search process by consideri... | import numpy as np
def preprocess_training_set(tSet: dict) -> dict:
"""
Normalizes the vectors in the training set by adjusting each feature to [0, 1] scale.
"""
flattened_tSet = np.array(list(tSet.keys()))
mins = np.min(flattened_tSet, axis=0)
maxs = np.max(flattened_tSet, axis=0)
nor... | from solution import preprocess_training_set, optimized_nearest_neighbor
def test_preprocess_training_set():
tSet = {
(1.0, 2.0): 'A',
(3.0, 4.0): 'B'
}
normalized = preprocess_training_set(tSet)
expected = {
(0.0, 0.0): 'A',
(1.0, 1.0): 'B'
}
assert normalized =... | [
{
"docstring": "Normalizes the vectors in the training set by adjusting each feature to [0, 1] scale.",
"function_declaration": "def preprocess_training_set(tSet):",
"function_name": "preprocess_training_set",
"parameter_list": "(tSet)"
},
{
"docstring": "Normalizes the input vector x by the... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef normalize_vector(v):\n \"\"\"\n Normalize a vector to the range [0, 1]\n \"\"\"\n arr = np.array(v)\n min_val = np.mi... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00009454",
"row_id": 9454,
"seed_ids": "[260]"
} | 0.619299 | Data_Structure_9454 | I | [
"preprocess_training_set",
"normalize_vector",
"optimized_nearest_neighbor"
] | 3 | [
[
"optimized_nearest_neighbor",
"normalize_vector"
],
[
"optimized_nearest_neighbor",
"preprocess_training_set"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 8f1ba3b0ec15c2320c6eea47813d40617843fa12 | 60a1ec6bff0c55151d3ed2711acdc85533ea054f | |||
v1.0 | instruct | Data_Structure | Data_Structure_9543_I | **Problem Statement:**
You are provided with a list of integers and your task is to sort this list using a method derived from the highly inefficient Bogo Sort for educational purposes. To challenge your understanding, you will need to implement a function `alternating_bogo_sort` which sorts the list alternatively by ... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Check if the given list is sorted in non-decreasing order.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def alternating_bogo_sort(arr: List[int]) -> List[int]:
"""
Sorts the list by alternatin... | from solution import alternating_bogo_sort
def test_alternating_bogo_sort():
# Regular case with multiple elements
assert alternating_bogo_sort([3, 1, 4, 1, 5, 9]) == [1, 1, 3, 4, 5, 9]
# Case with repeated elements
assert alternating_bogo_sort([2, 3, 5, 2, 2]) == [2, 2, 2, 3, 5]
# Single... | [
{
"docstring": "Check if the given list is sorted in non-decreasing order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the list by alternating between shuffling and reversing until it is sorted.\nThis metho... | [
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 alternating_bogo_sort(arr: List[int]) -> List[int]:\n def is_sorted(arr: List[int]) -> bool:\n return ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009543",
"row_id": 9543,
"seed_ids": "[16]"
} | 0.629757 | Data_Structure_9543 | I | [
"is_sorted",
"alternating_bogo_sort"
] | 2 | [
[
"alternating_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d0776df620e55254f3725f6407c1435a6eacb698 | b5290d293bf49782e0d0493bd5d57419261399bc | |||
v1.0 | instruct | Data_Structure | Data_Structure_9578_I | You are tasked with implementing an RSA encryption key generator, encryption, and decryption mechanism in Python. Your implementation will be used to securely transmit data between two parties. The generator function should produce public and private keys for encryption and decryption.
### Function Specifications
###... | import random
from sympy import isprime
from sympy import nextprime
from math import gcd
def generate_large_prime(bits):
"""Generates a large prime number of the specified bit length."""
while True:
number = random.getrandbits(bits)
number |= (1 << bits - 1) | 1 # Ensure high bit and low bit a... | import pytest
from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(128, seed=42) # using a small bit length for test speed
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert n.bit_length() >= 128
def test_encryption_... | [
{
"docstring": "Generates a large prime number of the specified bit length.",
"function_declaration": "def generate_large_prime(bits):",
"function_name": "generate_large_prime",
"parameter_list": "(bits)"
},
{
"docstring": "Generates the RSA key pairs.\n\nArgs:\nk (int): Number of bits in th... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_key(k, seed=None):\n if seed is not None:\n random.seed(seed)\n \n def g... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00009578",
"row_id": 9578,
"seed_ids": "[154]"
} | 0.708745 | Data_Structure_9578 | I | [
"generate_large_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_large_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 4b6c5c53437cb83a76d44095325b412f1f7923c0 | 9366e74383a920924ae69d69818c8ff3131482b3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9594_I | ### Reversing the Order of Words in a Sentence
You are given a list of sentences, and you need to reverse the order of words in each sentence. Words are defined as sequences of characters separated by spaces.
Write a function `reverse_sentences(sentences)` that accepts a list of strings `sentences` and returns a new ... | def reverse_words(sentence):
"""
Reverses the order of words in a single sentence.
"""
words = sentence.split()
reversed_words = words[::-1]
return ' '.join(reversed_words)
def reverse_sentences(sentences):
"""
Reverses the order of words in each sentence in a list of sentences.
"""... | from solution import reverse_words, reverse_sentences
# Unit tests for reverse_words function
def test_reverse_words_single_word():
assert reverse_words("Hello") == "Hello"
def test_reverse_words_two_words():
assert reverse_words("Hello world") == "world Hello"
def test_reverse_words_multiple_words():
as... | [
{
"docstring": "Reverses the order of words in a single sentence.",
"function_declaration": "def reverse_words(sentence):",
"function_name": "reverse_words",
"parameter_list": "(sentence)"
},
{
"docstring": "Reverses the order of words in each sentence in a list of sentences.",
"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": "def reverse_words(sentence):\n \"\"\"\n Reverse the order of words in a single sentence.\n \n Args:\n sentence (str): A sentence containing wor... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009594",
"row_id": 9594,
"seed_ids": "[69]"
} | 0.705013 | Data_Structure_9594 | I | [
"reverse_words",
"reverse_sentences"
] | 2 | [
[
"reverse_sentences",
"reverse_words"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3acbe5094cf26e5613c49d6c72165d1199b6ec3e | 1701416334e0ae09d303f3af62dca6f9ba684147 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9634_I | ### Task:
Write a Python program to:
1. Generate RSA keys using the provided RSA key generation algorithm.
2. Encrypt and decrypt a given piece of data using the generated keys.
### Requirements:
1. Implement a function `generate_key(k, seed=None)` to generate RSA keys.
2. Implement a function `encrypt(data, e, n)` to... | import random
from sympy import isprime, mod_inverse
def generate_prime(bits):
while True:
p = random.getrandbits(bits)
if isprime(p):
return p
def generate_key(k, seed=None):
if seed is not None:
random.seed(seed)
p = generate_prime(k // 2)
q = generate_prime(... | from solution import generate_key, encrypt, decrypt
def test_rsa_encryption_decryption():
(n, e, d) = generate_key(32, seed=42) # small key size for test
data = 42
encrypted = encrypt(data, e, n)
decrypted = decrypt(encrypted, d, n)
assert decrypted == data
def test_rsa_encryption_decryption_with... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bits):",
"function_name": "generate_prime",
"parameter_list": "(bits)"
},
{
"docstring": null,
"function_declaration": "def generate_key(k, seed=None):",
"function_name": "generate_key",
"parameter_list": "(k, seed=... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom math import gcd\n\ndef generate_key(k, seed=None):\n if seed is not None:\n random.seed(seed)\n \n def is_prime(n):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00009634",
"row_id": 9634,
"seed_ids": "[154]"
} | 0.743437 | Data_Structure_9634 | I | [
"generate_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | db5657c71d1c94e6e58b50133ba11e03a89b58ea | ff82fa04c62827c7e5af209669063a04d446a5ce | |||
v1.0 | instruct | Data_Structure | Data_Structure_9644_I | ### Scenario
You are building a search feature for a library system. The system maintains a dynamic set of books, allowing for insertions, deletions, and lookups of book records by their unique identifiers (ID).
### Task
Implement a Binary Search Tree (BST) to manage the library’s book records. You need to implement ... | class TreeNode:
def __init__(self, key: int):
self.left = None
self.right = None
self.val = key
def insert(root: TreeNode, key: int) -> TreeNode:
if root is None:
return TreeNode(key)
else:
if root.val < key:
root.right = insert(root.right, key)
e... | import pytest
from solution import TreeNode, insert, delete, search
def test_insert():
root = None
root = insert(root, 8)
root = insert(root, 3)
root = insert(root, 10)
assert root.val == 8
assert root.left.val == 3
assert root.right.val == 10
def test_delete_leaf():
root = None
ro... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key: int, left=None, right=None):\n self.key = key\n self.left = left\n self.right = right\n\ndef... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00009644",
"row_id": 9644,
"seed_ids": "[287]"
} | 0.488045 | Data_Structure_9644 | I | [
"insert",
"minValueNode",
"delete",
"search"
] | 4 | [
[
"delete",
"minValueNode"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 1e4fda3f61f0374ce5e5cf29d880b68a8c0f516c | 9120f048038b943750e6daf774f5049ef208541a | |||
v1.0 | instruct | Data_Structure | Data_Structure_9703_I | ### Red-Black Tree Insert Validation
As a part of maintaining a large dataset, you need to ensure that the Red-Black Tree properties are never violated when inserting new elements. You are tasked with implementing a function that inserts a new value into a Red-Black tree and ensures all the Red-Black properties are up... | class RBNode:
def __init__(self, value, color, parent=None, left=None, right=None):
self.value = value
self.color = color # 0 for black and 1 for red
self.parent = parent
self.left = left
self.right = right
def left_rotate(root, x):
y = x.right
x.right = y.left
... | from solution import RBNode, red_black_insert
def is_red_black_tree_valid(root):
if root is None:
return True, 1
if root.color == 1 and ((root.left and root.left.color == 1) or (root.right and root.right.color == 1)):
return False, 0
is_left_valid, left_black_height = is_red_black_tree_va... | [] | [
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": "class RBNode:\n def __init__(self, value, color=1, parent=None, left=None, right=None):\n self.value = value\n self.color = color # 0 for bla... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00009703",
"row_id": 9703,
"seed_ids": "[314]"
} | 0.470744 | Data_Structure_9703 | I | [
"left_rotate",
"right_rotate",
"insert_fixup",
"red_black_insert"
] | 4 | [
[
"insert_fixup",
"left_rotate"
],
[
"insert_fixup",
"right_rotate"
],
[
"red_black_insert",
"insert_fixup"
]
] | 3 | [] | false | [
"RBNode"
] | true | pytest | true | [] | true | f4d684f9e5a7b5c69f19f6f7154936570880b23b | b1d650a2d90a8984bf42d3b672331f769e30c360 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9714_I | ### Question: Implement Optimized Median Heap Sort
You are tasked with implementing a modified version of the Heap Sort algorithm. Instead of using only a max heap or min heap, you will use a combination of both to efficiently find the median value during the sorting process.
#### Scenario:
Given an array of integer... | import heapq
from typing import List
def insert_to_heaps(max_heap: List[int], min_heap: List[int], value: int) -> float:
if not max_heap or value <= -max_heap[0]:
heapq.heappush(max_heap, -value)
else:
heapq.heappush(min_heap, value)
if len(max_heap) > len(min_heap) + 1:
heapq.... | from solution import median_heap_sort, insert_to_heaps
def test_median_heap_sort():
assert median_heap_sort([7, 1, 5, 3, 9, 2]) == [1, 2, 3, 5, 7, 9]
def test_median_heap_sort_single_element():
assert median_heap_sort([1]) == [1]
def test_median_heap_sort_two_elements():
assert median_heap_sort([2, 1]) =... | [
{
"docstring": null,
"function_declaration": "def insert_to_heaps(max_heap, min_heap, value):",
"function_name": "insert_to_heaps",
"parameter_list": "(max_heap, min_heap, value)"
},
{
"docstring": null,
"function_declaration": "def median_heap_sort(arr):",
"function_name": "median_h... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nfrom typing import List, Tuple\n\ndef insert_to_heaps(max_heap: List[int], min_heap: List[int], value: int) -> float:\n \"\"\"\n Insert an... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00009714",
"row_id": 9714,
"seed_ids": "[8]"
} | 0.702424 | Data_Structure_9714 | I | [
"insert_to_heaps",
"median_heap_sort"
] | 2 | [
[
"median_heap_sort",
"insert_to_heaps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8b47796082c29b694d36b726508a9949f2e770ca | e00af88bc9eeff5f866b9e2139051e34ab8b1648 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9731_I | ### Context
Network flow problems are fundamental in optimization and have various applications like network routing, resource allocation, and bipartite matching. The following question will test your understanding of maximum flow algorithms.
### Problem Statement
You are given a network graph represented by an NxN c... | from collections import deque
def bfs(level, capacity, source, sink):
queue = deque([source])
level[source] = 0
while queue:
u = queue.popleft()
for v in range(len(capacity)):
if level[v] < 0 and capacity[u][v] > 0:
level[v] = level[u] + 1
qu... | import pytest
from solution import max_flow
def test_example_case():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert max_flow(capaci... | [
{
"docstring": null,
"function_declaration": "def bfs(level, capacity, source, sink):",
"function_name": "bfs",
"parameter_list": "(level, capacity, source, sink)"
},
{
"docstring": null,
"function_declaration": "def dfs(flow, capacity, current_node, sink, level, start):",
"function_... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(level, capacity, source, sink, N):\n \"\"\"\n Perform BFS and return True if there is an augmenting path.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009731",
"row_id": 9731,
"seed_ids": "[240]"
} | 0.605963 | Data_Structure_9731 | I | [
"bfs",
"dfs",
"max_flow"
] | 3 | [
[
"max_flow",
"bfs"
],
[
"max_flow",
"dfs"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 40f5dbd530907c38cc8e539abff730556bef91ee | 150ef17f10ba1b4c150f9924ef39dae84bece070 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9739_I | ### Coding Assessment: Implement a Modified Primality Test
You are tasked with implementing a variation of the Rabin-Miller Primality Test algorithm. This variation requires you to consider a list of prime candidates and return a list of results indicating whether each candidate is probably prime or guaranteed composi... | import random
def is_probably_prime(n, k):
"""
Rabin-Miller Primality Test to check if a number is probably prime.
"""
# Base cases
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0:
return False
# Decompose n-1 as d * 2^r
r, d = 0, n - ... | from solution import prime_candidates
def test_single_prime_low_k():
assert prime_candidates([2], 5) == [True]
assert prime_candidates([3], 5) == [True]
def test_single_composite_low_k():
assert prime_candidates([4], 5) == [False]
assert prime_candidates([9], 5) == [False]
def test_mixed_candidates()... | [
{
"docstring": "Rabin-Miller Primality Test to check if a number is probably prime.",
"function_declaration": "def is_probably_prime(n, k):",
"function_name": "is_probably_prime",
"parameter_list": "(n, k)"
},
{
"docstring": "Determine the primality of each number in the list of candidates u... | [
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 is_prime(n, k):\n \"\"\"Use the Rabin-Miller algorithm to return True if n is probably prime, and False if it is guaranteed composite.... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00009739",
"row_id": 9739,
"seed_ids": "[136]"
} | 0.654267 | Data_Structure_9739 | I | [
"is_probably_prime",
"prime_candidates"
] | 2 | [
[
"prime_candidates",
"is_probably_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 87044dc270ac81081f5b207cd66673707a2ea3c7 | ea508c29e21d74538b33724f3df954c0b5ed2bc8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9747_I | ### Hailstone Sequence Analysis and Longest Sequence Finder
Implement a function `find_longest_hailstone_sequence` that finds the integer within a given range `[low, high]` that generates the longest Hailstone sequence, and returns the starting integer, the length of the sequence, and the sequence itself.
### Input:
... | def hailstone(n):
"""
Generate the Hailstone sequence starting from n.
"""
sequence = []
while n != 1:
sequence.append(n)
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
sequence.append(1)
return sequence
def find_longest_hailstone_sequence(low, hi... | from solution import hailstone, find_longest_hailstone_sequence
def test_hailstone_sequence():
assert hailstone(1) == [1]
assert hailstone(2) == [2, 1]
assert hailstone(3) == [3, 10, 5, 16, 8, 4, 2, 1]
def test_find_longest_hailstone_sequence_range_1_to_10():
result = find_longest_hailstone_sequence(1... | [
{
"docstring": "Generate the Hailstone sequence starting from n.",
"function_declaration": "def hailstone(n):",
"function_name": "hailstone",
"parameter_list": "(n)"
},
{
"docstring": "Finds the integer within the range [low, high] that generates \nthe longest Hailstone sequence.\n\nParamete... | [
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 hailstone(n):\n \"\"\"\n Generate the Hailstone sequence starting from n.\n \"\"\"\n sequence = []\n while n != 1:\n sequence.append... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00009747",
"row_id": 9747,
"seed_ids": "[167]"
} | 0.563107 | Data_Structure_9747 | I | [
"hailstone",
"find_longest_hailstone_sequence"
] | 2 | [
[
"find_longest_hailstone_sequence",
"hailstone"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5a043a0ca757b108aec5636cac6177c0605f7426 | 1d81b01b25d9f9ce300c9c0d59678d9b8663a354 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9750_I | You have been given an array of integers that you need to sort. Normally, you would use efficient algorithms like quicksort, mergesort, or heapsort. However, as a part of an educational exercise, you are required to implement Bogo Sort. Your task is to demonstrate your understanding of algorithmic efficiency by impleme... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr: List[int], simulation: bool = False) -> List[int]:
"""
So... | from solution import bogo_sort
def test_bogo_sort_already_sorted():
assert bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_bogo_sort_reverse_sorted():
assert bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_bogo_sort_unsorted():
assert bogo_sort([3, 1, 2, 5, 4]) == [1, 2, 3, 4, 5]
def test_... | [
{
"docstring": "Check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sort the array using the highly inefficient Bogo Sort algorithm. Optionally, print\nthe array at each iteration of shuffli... | [
1,
1
] | 2 | 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 bogo_sort(arr: List[int], simulation: bool = False) -> List[int]:\n def is_sorted(arr):\n return all(a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009750",
"row_id": 9750,
"seed_ids": "[16]"
} | 0.571953 | Data_Structure_9750 | I | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d21f47e6077eb158b06253fdb6e2bb32c3767359 | 089029c747073337605cc2c95a4472caeb4c96cf | |||
v1.0 | instruct | Data_Structure | Data_Structure_9781_I | ### Bucket Sort Enhancement Challenge
#### Background
Bucket sort is excellent for sorting datasets that are uniformly distributed over a range. The basic bucket sort implementation provided uses insertion sort for sorting individual buckets, which can be inefficient in some scenarios, especially with large datasets.
... | from typing import List
def quick_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(r... | from solution import bucket_sort
def test_bucket_sort_normal_case():
assert bucket_sort([29, 25, 3, 49, 9, 37, 21, 43]) == [3, 9, 21, 25, 29, 37, 43, 49]
def test_bucket_sort_empty_array():
assert bucket_sort([]) == []
def test_bucket_sort_single_element():
assert bucket_sort([1]) == [1]
def test_bucket... | [
{
"docstring": null,
"function_declaration": "def quick_sort(arr):",
"function_name": "quick_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": "from typing import List\nimport math\n\n# Using Python's built-in Timsort which is very efficient\ndef efficient_sort(arr: List[int]) -> List[int]:\n \"\"\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009781",
"row_id": 9781,
"seed_ids": "[26]"
} | 0.550653 | Data_Structure_9781 | I | [
"quick_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"quick_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9f07df8a51dbf235863169117223d28f40e1bc87 | 08112473b81c37bf4b6021a53ec400b65532fe01 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9792_I | Nearest Neighbor Classification
You are given a training dataset where each data point is represented as a key in a dictionary, and the corresponding label is the value. Implement a function that, given a new data point, returns the label of the nearest data point in the training set using the Euclidean distance metri... | import math
def euclidean_distance(pt1, pt2):
"""
Calculate the Euclidean distance between two points.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(pt1, pt2)))
def classify_nearest_neighbor(x: tuple, tSet: dict) -> any:
"""
Classifies the given point x by finding the nearest neighbor ... | from solution import classify_nearest_neighbor
def test_classify_nearest_neighbor_example():
x = (1, 2)
tSet = {
(0, 0): 'A',
(1, 1): 'B',
(2, 2): 'C'
}
assert classify_nearest_neighbor(x, tSet) == 'B'
def test_classify_nearest_neighbor_single_point():
x = (1, 2)
tSet =... | [
{
"docstring": "Calculate the Euclidean distance between two points.",
"function_declaration": "def euclidean_distance(pt1, pt2):",
"function_name": "euclidean_distance",
"parameter_list": "(pt1, pt2)"
},
{
"docstring": "Classifies the given point x by finding the nearest neighbor in the tra... | [
0,
0,
0,
1,
1,
0,
1,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import Any, Dict, Tuple\n\ndef euclidean_distance(a: Tuple[float], b: Tuple[float]) -> float:\n return math.sqrt(sum((a_i - b_i)**... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00009792",
"row_id": 9792,
"seed_ids": "[260]"
} | 0.668289 | Data_Structure_9792 | I | [
"euclidean_distance",
"classify_nearest_neighbor"
] | 2 | [
[
"classify_nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cf1aec5494627881dd5f10c42fe28a26f52930a9 | c44e7419d9ec0c06f0bf5b16829711f1d1d8f53d | |||
v1.0 | instruct | Data_Structure | Data_Structure_9856_I | ### Matrix Operations and Exponentiation
**Scenario**:
You are working on a project that involves a lot of matrix operations, particularly matrix exponentiation. You are given a task to optimize the calculation of matrix powers.
**Problem Statement**:
Implement the function `matrix_exponentiation(mat: list, n: int)... | def multiply(matA, matB):
"""
Multiplies two square matrices matA and matB.
"""
d = len(matA)
result = [[0] * d for _ in range(d)]
for i in range(d):
for j in range(d):
for k in range(d):
result[i][j] += matA[i][k] * matB[k][j]
return result
def... | from solution import multiply, identity, matrix_exponentiation
def test_multiply():
matA = [
[1, 2],
[3, 4]
]
matB = [
[2, 0],
[1, 2]
]
expected = [
[4, 4],
[10, 8]
]
assert multiply(matA, matB) == expected
def test_identity():
expected =... | [
{
"docstring": "Multiplies two square matrices matA and matB.",
"function_declaration": "def multiply(matA, matB):",
"function_name": "multiply",
"parameter_list": "(matA, matB)"
},
{
"docstring": "Returns the identity matrix of dimension n x n.",
"function_declaration": "def identity(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": "def multiply(matA, matB):\n \"\"\"\n Multiplies two matrices matA and matB.\n \"\"\"\n d = len(matA)\n result = [[0] * d for _ in range(d)]\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009856",
"row_id": 9856,
"seed_ids": "[340]"
} | 0.572622 | Data_Structure_9856 | I | [
"multiply",
"identity",
"matrix_exponentiation"
] | 3 | [
[
"matrix_exponentiation",
"identity"
],
[
"matrix_exponentiation",
"multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 935642c50c8c8ba87770342b85e2ca8def3b53b2 | 6b58f9d8dead7d14e70fa63081db7fb62b2eecfc | |||
v1.0 | instruct | Data_Structure | Data_Structure_9883_I | You are tasked with implementing two encoding schemes, Elias γ and Elias δ, which are universal coding algorithms for positive integers. These encodings are useful for compressing numbers without requiring knowledge of their upper bounds.
Implement the following functions:
1. `elias_gamma_encode(x: int) -> str`: Thi... | def elias_gamma_encode(x: int) -> str:
"""
Computes the Elias Gamma encoding of a given positive integer x.
"""
if x <= 0:
raise ValueError("Input must be a positive integer.")
# Find the binary representation of x
binary_representation = bin(x)[2:]
# Compute the length of the ... | from solution import elias_gamma_encode, elias_delta_encode
def test_elias_gamma_encode():
# Basic cases
assert elias_gamma_encode(1) == "1"
assert elias_gamma_encode(2) == "010"
assert elias_gamma_encode(3) == "011"
assert elias_gamma_encode(4) == "00100"
assert elias_gamma_encode(5) == "00101... | [
{
"docstring": "Computes the Elias Gamma encoding of a given positive integer x.",
"function_declaration": "def elias_gamma_encode(x):",
"function_name": "elias_gamma_encode",
"parameter_list": "(x)"
},
{
"docstring": "Computes the Elias Delta encoding of a given positive integer x.",
"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 elias_gamma_encode(x: int) -> str:\n \"\"\"\n Returns the Elias gamma encoding of a given positive integer x.\n \"\"\"\n if x <= 0:\n r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009883",
"row_id": 9883,
"seed_ids": "[333]"
} | 0.479627 | Data_Structure_9883 | I | [
"elias_gamma_encode",
"elias_delta_encode"
] | 2 | [
[
"elias_delta_encode",
"elias_gamma_encode"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 45ae1510d870f2f0311f8be51adc8bcc0daaab6b | 5888c9b531cd0ba5afed98dc50ddc2134e388cfc | |||
v1.0 | instruct | Data_Structure | Data_Structure_9900_I | You are given two singly linked lists that might intersect at some point in the list. Your task is to write a function that finds and returns the node at which the two lists intersect. If the lists do not intersect, return `None`.
### Scenario
Imagine you have two sets of friends who journey separately and you want to... | class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def get_length_and_tail(node):
length = 0
while node:
length += 1
if node.next is None:
return length, node
node = node.next
return length, None
def intersection(h1: No... | import pytest
from solution import Node, intersection
def create_intersecting_lists():
# create linked list as:
# 1 -> 3 -> 5
# \
# 7 -> 9 -> 11
# /
# 2 -> 4 -> 6
a1 = Node(1)
b1 = Node(3)
c1 = Node(5)
d = Node(7)
a2 = Node(2)
b2 = Nod... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef get_count_and_tail(head):\n count = 0\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00009900",
"row_id": 9900,
"seed_ids": "[245]"
} | 0.570945 | Data_Structure_9900 | I | [
"get_length_and_tail",
"intersection"
] | 2 | [
[
"intersection",
"get_length_and_tail"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | d474cd15d87c2c89dcbb2b075ce40bc82a380e3e | ed1b2c00e63b9ccc979e6204e9247305fe338ac6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9929_I | ### Problem Description
You are given a directed graph representing a flow network with nodes representing junctions and edges representing pipes with specific capacities. Your task is to determine the maximum amount of flow that can be sent from the source node (the first node) to the sink node (the last node) using ... | from collections import deque
def bfs(residual_graph, source, sink, parent):
visited = [False] * len(residual_graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(residual_graph[u]):
if not visited[... | from solution import maximum_flow_bfs
def test_example_1():
adjacency_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 maximum_flow_bfs(adjacency_matrix) == 23
de... | [
{
"docstring": null,
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(adjacency_matrix):",
"function_name"... | [
0,
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 collections import deque\nfrom typing import List\n\ndef bfs(residual_graph, source, sink, parent):\n visited = [False] * len(residual_graph)\n que... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00009929",
"row_id": 9929,
"seed_ids": "[229]"
} | 0.60528 | Data_Structure_9929 | I | [
"bfs",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e2d8204d9aa9a504ae8fdc59f7df4ecb3a0daf25 | 2c20ec85d927cbe462ef75c029d8c745140643f4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_9953_I | ### Question: Advanced Arithmetic Operations with Constraints
You are tasked with implementing several arithmetic operations on integers for a numerical library. Your implementation should not only be correct but optimized for large numbers and edge cases.
#### Task
Implement the following functions:
1. **Greatest C... | def gcd(a, b):
"""
Returns the greatest common divisor of a and b using Euclid's Algorithm.
"""
a, b = abs(a), abs(b)
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""
Returns the least common multiple of a and b.
"""
return abs(a * b) // gcd(a, b)
def trailing_zero(... | from solution import gcd, lcm, trailing_zero, gcd_bit
def test_gcd():
assert gcd(34, 17) == 17
assert gcd(21, 6) == 3
assert gcd(48, 18) == 6
assert gcd(-48, 18) == 6
assert gcd(48, -18) == 6
def test_lcm():
assert lcm(21, 6) == 42
assert lcm(48, 18) == 144
assert lcm(-21, 6) == 42
... | [
{
"docstring": "Returns the greatest common divisor of a and b using Euclid's Algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the least common multiple of a and b.",
"function_declaration": "def lcm(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(a: int, b: int) -> int:\n \"\"\"\n Returns the greatest common divisor of a and b using Euclid's algorithm.\n Handles negative inputs by taki... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00009953",
"row_id": 9953,
"seed_ids": "[166]"
} | 0.631261 | Data_Structure_9953 | I | [
"gcd",
"lcm",
"trailing_zero",
"gcd_bit"
] | 4 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8c1c4f4845938dcd8f55bc8e422e068db230478a | 271682e7724775285df5ef5c2e45c5667880e54a | |||
v1.0 | instruct | Data_Structure | Data_Structure_10062_I | Modular Cryptography
#### Context
You are tasked with implementing a module for a cryptographic system that involves computations of multiplicative inverses under a given modulus. A critical part of RSA encryption/decryption algorithms uses the modular inverse for various operations. Given your expertise in number the... | def extended_gcd(a, b):
"""
Implements the Extended Euclidean Algorithm.
Returns a tuple (s, t, g) such that s * a + t * b = g where g is the gcd of a and b.
:param a: Integer
:param b: Integer
:return: Tuple of integers (s, t, g)
"""
old_s, s = 1, 0
old_t, t = 0, 1
old_r, r = a... | from solution import extended_gcd, modular_inverse
def test_extended_gcd_basic():
s, t, g = extended_gcd(30, 20)
assert s == 1 and t == -1 and g == 10
def test_extended_gcd_coprime():
s, t, g = extended_gcd(17, 31)
assert s * 17 + t * 31 == g == 1
def test_extended_gcd_zero_case():
s, t, ... | [
{
"docstring": "Implements the Extended Euclidean Algorithm.\nReturns a tuple (s, t, g) such that s * a + t * b = g where g is the gcd of a and b.\n\n:param a: Integer\n:param b: Integer\n:return: Tuple of integers (s, t, g)",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def extended_gcd(a, b):\n \"\"\"\n Returns a tuple (s, t, g) where:\n - s, t are the coefficients such that sa + tb = gcd(a, b)\n - g is the gcd o... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00010062",
"row_id": 10062,
"seed_ids": "[161]"
} | 0.569045 | Data_Structure_10062 | I | [
"extended_gcd",
"modular_inverse"
] | 2 | [
[
"modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1dd81d16f1350a64a5c5610b3e0bcef5bffbfd8e | 8cc47f908b26089ce9786ffcc3b15126eab24e95 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10089_I | ### Prime Number Sequence Checker
**Objective:**
Implement a function that checks whether every number in a given list is a prime number. The function should return a list of Boolean values correspondingly.
**Function Signature:**
```python
def check_prime_sequence(lst: List[int]) -> List[bool]:
pass
```
**Input... | from typing import List
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def chec... | from solution import check_prime_sequence
def test_check_prime_sequence_basic():
assert check_prime_sequence([1, 2, 3, 4, 5, 6, 23, -17, 0, 19]) == [False, True, True, False, True, False, True, False, False, True]
assert check_prime_sequence([33, 34, 35, 36, 37, 38, 39]) == [False, False, False, False, True, F... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def check_prime_sequence(lst):",
"function_name": "check_prime_sequence",
"parameter_list": "(lst)"
}
] | [
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 is_prime(n: int) -> bool:\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if n <= 1:\n return False... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00010089",
"row_id": 10089,
"seed_ids": "[143]"
} | 0.780882 | Data_Structure_10089 | I | [
"is_prime",
"check_prime_sequence"
] | 2 | [
[
"check_prime_sequence",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f527e6f7f4e9a894b90471e46bea2886ffc3f4fc | 446f6d9f90d4c4072510a375bab9a257fe38cfd9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10368_I | You are tasked with implementing an optimized version of the Insertion Sort algorithm. Your task is to write a function that enhances the insertion sort by utilizing a binary search to determine the correct position of the current element. This improvement aims to reduce the number of comparisons within the inner while... | from typing import List
def binary_search(arr: List[int], val: int, start: int, end: int) -> int:
"""
A helper function to perform binary search on the array.
It returns the position where the value should be inserted.
"""
if start == end:
if arr[start] > val:
return start
... | from solution import optimized_insertion_sort
def test_sorted_array():
assert optimized_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert optimized_insertion_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_random_array():
assert optimized_insertion_sort([29, 10,... | [
{
"docstring": "A helper function to perform binary search on the array.\nIt returns the position where the value should be inserted.",
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docst... | [
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 binary_search(arr, val, start, end):\n \"\"\"\n Helper function to perform binary search and find the index where the value should be inserted.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00010368",
"row_id": 10368,
"seed_ids": "[7]"
} | 0.586182 | Data_Structure_10368 | I | [
"binary_search",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ca3c32f1cd961e6be442e2b8cf47860b5a328df | d50ef5d300ded0fd7f9ef16f0c26fe6fadfecd75 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10414_I | ### Question: Advanced GCD and LCM Calculations
In this task, you'll work on optimizing and applying fundamental arithmetic algorithms, specifically the greatest common divisor (GCD) and the lowest common multiple (LCM).
#### Task 1: Enhanced Euclidean GCD Function
Write a function `enhanced_gcd(a: int, b: int) -> in... | def enhanced_gcd(a, b):
"""
Calculate the GCD of two integers using the Euclidean Algorithm.
Return the other number if either input is zero.
"""
while b:
a, b = b, a % b
return abs(a)
def robust_lcm(a, b):
"""
Compute the LCM of two integers using the GCD function.
Return z... | from solution import enhanced_gcd, robust_lcm, bitwise_gcd
def test_enhanced_gcd():
assert enhanced_gcd(48, 18) == 6
assert enhanced_gcd(-48, 18) == 6
assert enhanced_gcd(0, 18) == 18
assert enhanced_gcd(18, 0) == 18
assert enhanced_gcd(0, 0) == 0
assert enhanced_gcd(7, 5) == 1
assert enhan... | [
{
"docstring": "Calculate the GCD of two integers using the Euclidean Algorithm.\nReturn the other number if either input is zero.",
"function_declaration": "def enhanced_gcd(a, b):",
"function_name": "enhanced_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Compute the LCM of two intege... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_gcd(a: int, b: int) -> int:\n \"\"\"\n Returns the greatest common divisor (GCD) of the integers a and b using the Euclidean Algorithm.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00010414",
"row_id": 10414,
"seed_ids": "[166]"
} | 0.618745 | Data_Structure_10414 | I | [
"enhanced_gcd",
"robust_lcm",
"bitwise_gcd"
] | 3 | [
[
"robust_lcm",
"enhanced_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fad33f67dc9ab35fe8eb35a1a76c4d1c6386f0ec | 9bc672d8339d538b7b580471ef3752f5fdc921c5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10473_I | ### Bogo sort deluxe
Bogo Sort is an entertaining but impractically inefficient sorting algorithm that shuffles the elements randomly until they are sorted. Your task is to implement a modified version of Bogo Sort -- `bogo_sort_deluxe`, that adds a counter and stops after a predetermined number of shuffles to provide... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted in ascending order
"""
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def bogo_sort_deluxe(arr, max_shuffles):
"""
Bogo Sort Deluxe which shuffles the array randomly until it is sorted
or the n... | from solution import bogo_sort_deluxe
def test_bogo_sort_deluxe_sorted_array():
assert bogo_sort_deluxe([1, 2, 3], 5) == [1, 2, 3]
def test_bogo_sort_deluxe_reverse_sorted_array():
result = bogo_sort_deluxe([3, 2, 1], 1000)
assert result == [1, 2, 3] or result is None
def test_bogo_sort_deluxe_with_zero_... | [
{
"docstring": "Helper function to check if the array is sorted in ascending order",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Bogo Sort Deluxe which shuffles the array randomly until it is sorted\nor the number ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if an array is sorted in non-decreasing order.\n \"\"\"\n for i in range(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00010473",
"row_id": 10473,
"seed_ids": "[16]"
} | 0.621414 | Data_Structure_10473 | I | [
"is_sorted",
"bogo_sort_deluxe"
] | 2 | [
[
"bogo_sort_deluxe",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 86fceb908ec2dd2a206dfcb70086969810a6755f | ab0d027836f5e3bf96160208882908b4fcb58072 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10504_I | ### Magic Number Function Implementation
**Scenario**:
You are developing a feature that utilizes the concept of magic numbers in a puzzle game. Players can enter any non-negative integer to check if it is classified as a magic number based on the summation of its digits.
Write a function `is_magic_number(n: int) -> ... | def digit_sum(n):
"""
Calculates the sum of the digits of a non-negative integer n.
"""
return sum(int(digit) for digit in str(n))
def is_magic_number(n: int) -> bool:
"""
Determines if a given non-negative integer is a magic number.
A magic number is defined as a number that reduces to 1 a... | from solution import is_magic_number
def test_is_magic_number_true():
assert is_magic_number(50113) == True
assert is_magic_number(1234) == True
assert is_magic_number(199) == True
assert is_magic_number(37) == True # 37 -> 3+7=10 -> 1+0=1
def test_is_magic_number_false():
assert is_magic_number(... | [
{
"docstring": "Calculates the sum of the digits of a non-negative integer n.",
"function_declaration": "def digit_sum(n):",
"function_name": "digit_sum",
"parameter_list": "(n)"
},
{
"docstring": "Determines if a given non-negative integer is a magic number.\nA magic number is defined as a ... | [
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 is_magic_number(n: int) -> bool:\n \"\"\"\n Determines whether the given non-negative integer n is a magic number.\n A magic number is defined su... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00010504",
"row_id": 10504,
"seed_ids": "[132]"
} | 0.576108 | Data_Structure_10504 | I | [
"digit_sum",
"is_magic_number"
] | 2 | [
[
"is_magic_number",
"digit_sum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 97efba3cf0ca32dc0f66bc631cc97829408315c8 | c8673219fb806e4703d8b9cafaca300482726335 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10557_I | ### Radix Sort Implementation Challenge
You are given an integer array `arr` that needs to be sorted in non-decreasing order. Implement the Radix Sort algorithm to sort the array.
#### Function Signature
```python
def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
```
#### Input
* `arr`: A list ... | from typing import List
def counting_sort_for_radix(arr: List[int], exp: int, base: int = 10) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * base
for i in range(n):
index = (arr[i] // exp) % base
count[index] += 1
for i in range(1, base):
count[i] +=... | from solution import radix_sort
def test_radix_sort_basic_cases():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort([1]) == [1]
assert radix_sort([1000]) == [1000]
def test_rad... | [
{
"docstring": null,
"function_declaration": "def counting_sort_for_radix(arr, exp, base=10):",
"function_name": "counting_sort_for_radix",
"parameter_list": "(arr, exp, base=10)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort_for_radix(arr: List[int], exp: int, base: int = 10) -> List[int]:\n n = len(arr)\n output = [0] * n \n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00010557",
"row_id": 10557,
"seed_ids": "[15]"
} | 0.685283 | Data_Structure_10557 | I | [
"counting_sort_for_radix",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort_for_radix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7f46fb68437275acc5372536b1b974aac358bf57 | c7c0015ae4f7204e87672aca78bfb90586a5f5d7 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10604_I | ### Insertion Sort Implementation with Additional Requirements
**Context**: You have been hired to optimize the sorting operations of a software dealing with customer orders. One of the tasks involves ensuring that a list of order values is sorted efficiently given different types of input scenarios.
**Task**: Write ... | from typing import List
def binary_search(arr: List[int], val: int, start: int, end: int) -> int:
"""
Helper function to perform binary search to find the index to insert `val`
"""
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
start = mid + 1
else:
... | from solution import optimized_insertion_sort
def test_sorted_array():
arr = [1, 2, 3, 4, 5]
assert optimized_insertion_sort(arr, 2) == [1, 2, 3, 4, 5]
def test_unsorted_array():
arr = [5, 2, 9, 1, 5, 6]
assert optimized_insertion_sort(arr, 3) == [1, 2, 5, 5, 6, 9]
def test_single_element_array():
... | [
{
"docstring": "Helper function to perform binary search to find the index to insert `val`",
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "Function to perform optimized inser... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef binary_search(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Helper function to perform binary search... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00010604",
"row_id": 10604,
"seed_ids": "[7]"
} | 0.599886 | Data_Structure_10604 | I | [
"binary_search",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1c94e465aa25b05a8a941814b0801c84ee46e5b4 | f738429496c086ba34fec7e656df3b1a480bf85c | |||
v1.0 | instruct | Data_Structure | Data_Structure_10611_I | ### Coding Challenge: Enhanced Diffie-Hellman Key Exchange with Error Handling
#### Context
Diffie-Hellman key exchange is a method that empowers two parties to establish a shared secret over an unsecured channel. However, for enhanced security and efficient operation, we must ensure that the inputs provided (large pr... | def is_prime(n):
"""
Check if n is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return Tr... | import pytest
from solution import secure_diffie_hellman, is_prime, find_primitive_root
def test_prime_check():
assert is_prime(23) == True
assert is_prime(10) == False
assert is_prime(100003) == True
assert is_prime(100000007) == True
assert is_prime(1000000) == False
def test_find_primitive_root... | [
{
"docstring": "Check if n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find the primitive root of p.",
"function_declaration": "def find_primitive_root(p):",
"function_name": "find_primitive_... | [
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 sympy\n\ndef is_primitive_root(a, p):\n \"\"\"\n Checks if `a` is a primitive root of `p`.\n \"\"\"\n if sympy.isprime(p):\n require... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00010611",
"row_id": 10611,
"seed_ids": "[146]"
} | 0.483487 | Data_Structure_10611 | I | [
"is_prime",
"find_primitive_root",
"secure_diffie_hellman"
] | 3 | [
[
"secure_diffie_hellman",
"find_primitive_root"
],
[
"secure_diffie_hellman",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a1a0b32867386338be8780a6c883f52e17589b4a | cf815acddca1ba4b76945f7105825300f9022050 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10631_I | RSA Encryption/Decryption System
#### Context
You have been tasked to design a secure communication module that uses the RSA encryption algorithm to protect data being transmitted between clients and a server. To achieve this, you need to implement functions to generate RSA keys, encrypt data, and decrypt data.
#### ... | import random
from typing import Tuple
from sympy import isprime, mod_inverse
def generate_prime(bits: int, seed = None) -> int:
if seed is not None:
random.seed(seed)
while True:
num = random.getrandbits(bits)
if isprime(num):
return num
def generate_key(k: int, seed: int ... | from solution import generate_key, encrypt, decrypt
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_encrypt_decrypt():
k = 32
seed = 42
dat... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bits, seed=None):",
"function_name": "generate_prime",
"parameter_list": "(bits, seed=None)"
},
{
"docstring": null,
"function_declaration": "def generate_key(k, seed=None):",
"function_name": "generate_key",
"param... | [
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 Tuple\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime(bits: int, seed = None) -> int:\n if seed is not None... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00010631",
"row_id": 10631,
"seed_ids": "[154]"
} | 0.675986 | Data_Structure_10631 | I | [
"generate_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | f3f5ab5b790c5e69e1468d8a3744be69de467b3b | 7b558c6497f73c2d453811d8dc76092e8c6c1e76 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10649_I | ### Problem Description
You have been provided with the algorithm for inverting an n x n matrix. Your task is to extend this functionality by implementing a function that can handle special cases more efficiently and handle larger matrices with an optimized determinant calculation.
### Requirements
1. **Optimize Det... | from typing import List
import numpy as np
def is_square_matrix(matrix: List[List[float]]) -> bool:
return all(len(row) == len(matrix) for row in matrix)
def lu_decomposition(matrix: List[List[float]]) -> (List[List[float]], List[List[float]], List[int]):
n = len(matrix)
L = [[0.0] * n for _ in range(n)]
... | from solution import advanced_invert_matrix
import numpy as np
def test_square_matrix():
non_square_matrix = [
[1, 2, 3],
[4, 5, 6]
]
assert advanced_invert_matrix(non_square_matrix) == [[-1]]
def test_singular_matrix():
singular_matrix = [
[1, 2],
[2, 4]
]
asse... | [
{
"docstring": null,
"function_declaration": "def is_square_matrix(matrix):",
"function_name": "is_square_matrix",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def lu_decomposition(matrix):",
"function_name": "lu_decomposition",
"parameter_list": ... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef lu_decomposition(matrix: List[List[float]]):\n n = len(matrix)\n L = [[0.0] * n for _ in range(n)]\n U = [[0.0] * n fo... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00010649",
"row_id": 10649,
"seed_ids": "[347]"
} | 0.490232 | Data_Structure_10649 | I | [
"is_square_matrix",
"lu_decomposition",
"determinant",
"advanced_invert_matrix"
] | 4 | [
[
"advanced_invert_matrix",
"determinant"
],
[
"advanced_invert_matrix",
"is_square_matrix"
],
[
"determinant",
"is_square_matrix"
],
[
"determinant",
"lu_decomposition"
]
] | 4 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | a3f7c9c3618cf36691669a5084f53f2702ccc66e | be36740079f6fa64c5bb1d430916287ad5556433 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10681_I | **Question**: Write a function `maximum_flow_bfs` that computes the maximum flow from a source node (node 0) to a sink node (last node, n-1) in a directed graph represented by a n x n adjacency matrix. Your function should use the Breadth-First Search (BFS) approach to find augmenting paths. You should also consider ed... | from collections import deque
def bfs(graph, source, sink, parent):
visited = [False] * len(graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(graph[u]):
if not visited[v] and capacity > 0:
... | from solution import maximum_flow_bfs
def test_simple_path():
graph = [
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]
]
assert maximum_flow_bfs(graph) == 1
def test_example_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0... | [
{
"docstring": null,
"function_declaration": "def bfs(graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(graph):",
"function_name": "maximum_flow_bfs",
"pa... | [
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 collections import deque\n\ndef bfs(graph, source, sink, parent):\n visited = [False] * len(graph)\n queue = deque([source])\n visited[source] =... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00010681",
"row_id": 10681,
"seed_ids": "[241]"
} | 0.604959 | Data_Structure_10681 | I | [
"bfs",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 03e95a220e5c22ac346aab6504050f749da223aa | cbd1b6d2d2c7498cd9e28777bb34abf61678046d | |||
v1.0 | instruct | Data_Structure | Data_Structure_10780_I | **Scenario**: You are tasked with implementing a sorting algorithm for a large dataset in a constrained environment where memory usage needs to be minimized. You need to use in-place sorting, and the dataset consists of integers. The requirement also includes that detailed simulation logs must be produced during the al... | from typing import List, Tuple
def heapify(arr: List[int], n: int, i: int, simulation: bool=False) -> int:
iterations = 1
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... | from solution import descending_heap_sort
def test_sort_simple_array():
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_arr, iterations = descending_heap_sort(arr)
assert sorted_arr == [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
assert iterations > 0
def test_sort_with_negative_numbers():
arr = [0, -10, 5, 3... | [
{
"docstring": null,
"function_declaration": "def heapify(arr, n, i, simulation=False):",
"function_name": "heapify",
"parameter_list": "(arr, n, i, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def descending_heap_sort(arr, simulation=False):",
"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 heapify(arr: List[int], n: int, i: int, simulation: bool=False) -> int:\n iterations = 1\n largest = i\n left =... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00010780",
"row_id": 10780,
"seed_ids": "[8]"
} | 0.609746 | Data_Structure_10780 | I | [
"heapify",
"descending_heap_sort"
] | 2 | [
[
"descending_heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2c0c466d610ae3d2296117dbde239444708b10ef | 3dd4d5a0451d38ae4e623cc65edd3da0db7fd289 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10781_I | ### Question: Optimized Least Common Multiple Calculation
#### Problem Statement
Implement an optimized function to calculate the Least Common Multiple (LCM) of two integers. Your implementation should leverage an efficient algorithm to compute the Greatest Common Divisor (GCD) as a part of the process. You are expect... | def gcd(a, b):
"""
Computes the Greatest Common Divisor (GCD) of two integers using the Euclidean algorithm.
"""
a, b = abs(a), abs(b)
while b:
a, b = b, a % b
return a
def optimized_lcm(a, b):
"""
Computes the Least Common Multiple (LCM) of two integers a and b.
Handles neg... | import pytest
from solution import optimized_lcm
def test_lcm_positive_numbers():
assert optimized_lcm(21, 14) == 42
def test_lcm_one_zero():
assert optimized_lcm(0, 15) == 0
assert optimized_lcm(15, 0) == 0
def test_lcm_both_non_zero():
assert optimized_lcm(12, 18) == 36
def test_lcm_negative_numbe... | [
{
"docstring": "Computes the Greatest Common Divisor (GCD) of two integers using the Euclidean algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the Least Common Multiple (LCM) of two integers a and b.\nHandl... | [
0,
0,
1,
1,
1,
1,
1,
1,
1
] | 7 | easy | 0.778 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(x, y):\n \"\"\"\n Compute the Greatest Common Divisor (GCD) of x and y using the Euclidean algorithm.\n \"\"\"\n while y != 0:\n (x... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00010781",
"row_id": 10781,
"seed_ids": "[166]"
} | 0.654225 | Data_Structure_10781 | I | [
"gcd",
"optimized_lcm"
] | 2 | [
[
"optimized_lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6e05cc4dff4ec0940a7685b9abf0eacbba43b8cd | 91e65fe6d7b69fc11307b3afd5b1d325c07763c5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10793_I | **Scenario**:
You are tasked with developing a feature for a text-processing software which involves reversing strings. Your main goal is to ensure that this feature is implemented efficiently. As part of the evaluation, you should demonstrate your understanding of both recursive and iterative approaches, as well as ... | def reverse_string(s: str, method: str) -> str:
"""
Reverse a string using the specified method.
Args:
s (str): The string to be reversed.
method (str): The method to use for reversing the string, one of 'recursive', 'iterative', 'pythonic', 'ultra_pythonic'.
Returns:
str: The reve... | from solution import reverse_string
def test_reverse_string_recursive():
assert reverse_string("hello", "recursive") == "olleh"
assert reverse_string("a", "recursive") == "a"
assert reverse_string("", "recursive") == ""
def test_reverse_string_iterative():
assert reverse_string("world", "iterative") =... | [
{
"docstring": "Reverse a string using the specified method.\n\nArgs:\ns (str): The string to be reversed.\nmethod (str): The method to use for reversing the string, one of 'recursive', 'iterative', 'pythonic', 'ultra_pythonic'.\n\nReturns:\nstr: The reversed string.",
"function_declaration": "def reverse_s... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def reverse_string(s: str, method: str) -> str:\n \"\"\"\n Reverses the string `s` based on the specified `method`.\n \n Args:\n s (str): The s... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00010793",
"row_id": 10793,
"seed_ids": "[61]"
} | 0.717929 | Data_Structure_10793 | I | [
"reverse_string",
"_recursive_reverse",
"_iterative_reverse"
] | 3 | [
[
"reverse_string",
"_iterative_reverse"
],
[
"reverse_string",
"_recursive_reverse"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5a39b44c864c4dbff5b5d4c05cb1216428dbb392 | e39993afca1cca3b7b2b206acef2888f26fd1011 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10801_I | ### Question: Implement Enhanced Nearest Neighbor Algorithm
#### Scenario
You are working on a machine learning project for classifying objects based on their features in a multidimensional space. The classification is performed using a Nearest Neighbor algorithm. Given new data points, you must classify these using a... | from typing import Tuple, Dict, Any, Optional
import numpy as np
from scipy.spatial import KDTree
def enhanced_distance(x: Tuple[float, ...], y: Tuple[float, ...]) -> float:
"""
Calculates the Euclidean distance between two vectors x and y.
"""
return np.linalg.norm(np.array(x) - np.array(y))
def enha... | import pytest
from solution import enhanced_distance, enhanced_nearest_neighbor
def test_enhanced_distance():
assert pytest.approx(enhanced_distance((1.0, 2.0), (4.0, 6.0)), 0.01) == 5.0
assert pytest.approx(enhanced_distance((0.0, 0.0), (0.0, 0.0)), 0.01) == 0.0
assert pytest.approx(enhanced_distance((1.5... | [
{
"docstring": "Calculates the Euclidean distance between two vectors x and y.",
"function_declaration": "def enhanced_distance(x, y):",
"function_name": "enhanced_distance",
"parameter_list": "(x, y)"
},
{
"docstring": "Returns the class/value of the nearest neighbor for the input vector x ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Tuple, Dict, Any\nimport math\n\ndef enhanced_distance(x: Tuple[float, ...], y: Tuple[float, ...]) -> float:\n \"\"\"\n Returns the E... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00010801",
"row_id": 10801,
"seed_ids": "[260]"
} | 0.641173 | Data_Structure_10801 | I | [
"enhanced_distance",
"enhanced_nearest_neighbor"
] | 2 | [
[
"enhanced_nearest_neighbor",
"enhanced_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 24712148306d30678db4c963c25c7172e35314d3 | 8b9c56309cc48329e23fdcc543a378c4e1342297 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10802_I | **Context**: A large digital library maintains vast collections of e-books and articles. For efficient content retrieval and plagiarism detection, the library needs an optimized text search feature that can quickly locate instances of specific phrases within large bodies of text.
**Task**: You are provided with the Kn... | from typing import List, Dict
def knuth_morris_pratt(text: str, pattern: str) -> List[int]:
"""
KMP algorithm to find all occurrences of the pattern in the text.
"""
n, m = len(text), len(pattern)
lps = [0] * m
j = 0 # index for pattern
occurrences = []
# Preprocess the pattern - crea... | from solution import find_phrases
def test_find_phrases_single_occurrence():
text = "abracadabra"
phrases = ["abra", "cad"]
expected = {"abra": [0, 7], "cad": [4]}
assert find_phrases(text, phrases) == expected
def test_find_phrases_multiple_occurrences():
text = "abababab"
phrases = ["ab", "a... | [
{
"docstring": "KMP algorithm to find all occurrences of the pattern in the text.",
"function_declaration": "def knuth_morris_pratt(text, pattern):",
"function_name": "knuth_morris_pratt",
"parameter_list": "(text, pattern)"
},
{
"docstring": "Find occurrences of each phrase in the text usin... | [
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, Dict\n\ndef knuth_morris_pratt(text: str, pattern: str) -> List[int]:\n \"\"\"\n KMP algorithm to find all occurrences of the p... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00010802",
"row_id": 10802,
"seed_ids": "[93]"
} | 0.492031 | Data_Structure_10802 | I | [
"knuth_morris_pratt",
"find_phrases"
] | 2 | [
[
"find_phrases",
"knuth_morris_pratt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2566a19dbfe8fea658ce8314803d9ce47c31b9ca | 20c2b57e8fbea95de1e9966378f2c7a9cf45ec2c | |||
v1.0 | instruct | Data_Structure | Data_Structure_10859_I | ### Maximum Flow with Residual Graph and BFS
**Scenario**:
You are tasked with optimizing a city's water distribution network. The city's water network can be represented as a flow network with nodes representing junctions and directed edges representing pipes with specific capacities. You need to determine the maximu... | from typing import List
from collections import deque
def bfs_capacity_path(graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:
visited = [False] * len(graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, cap... | from solution import maximum_flow_bfs
def test_simple_case():
graph = [
[0, 1],
[0, 0]
]
assert maximum_flow_bfs(graph) == 1
def test_example_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
... | [
{
"docstring": null,
"function_declaration": "def bfs_capacity_path(graph, source, sink, parent):",
"function_name": "bfs_capacity_path",
"parameter_list": "(graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(adjacency_matrix):",
"func... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(residual_graph, source, sink, parent):\n visited = [False] * len(residual_graph)\n que... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00010859",
"row_id": 10859,
"seed_ids": "[241]"
} | 0.594862 | Data_Structure_10859 | I | [
"bfs_capacity_path",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs_capacity_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d839a5c5cd2f474aa7ee4f5d384e55d38c93af10 | 2f56c03dd1501a26ab39b5587c06bd49777fb3eb | |||
v1.0 | instruct | Data_Structure | Data_Structure_10861_I | ### Run-Length Encoding Compression and Decompression
You are given a simple data compression algorithm called Run-Length Encoding (RLE). Your task is to demonstrate your understanding of this algorithm by overriding the existing function `encode_rle` to enhance its functionality and writing a new function `compress_r... | def encode_rle(input: str) -> str:
"""
Compresses the input string using Run-Length Encoding (RLE).
"""
if not input:
return ''
encoded_str = []
count = 1
for i in range(1, len(input)):
if input[i] == input[i - 1]:
count += 1
else:
en... | from solution import encode_rle, decode_rle, compress_rle
def test_encode_rle():
assert encode_rle("aaabb") == "3a2b"
assert encode_rle("abcdef") == "1a1b1c1d1e1f"
assert encode_rle("aabbaa") == "2a2b2a"
assert encode_rle("") == ""
assert encode_rle("a") == "1a"
def test_decode_rle():
assert d... | [
{
"docstring": "Compresses the input string using Run-Length Encoding (RLE).",
"function_declaration": "def encode_rle(input):",
"function_name": "encode_rle",
"parameter_list": "(input)"
},
{
"docstring": "Decompresses an RLE encoded string back to its original form.",
"function_declara... | [
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 encode_rle(input: str) -> str:\n \"\"\"\n Returns the Run-Length Encoded (RLE) string of the input.\n \"\"\"\n if not input:\n return \... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00010861",
"row_id": 10861,
"seed_ids": "[334]"
} | 0.696229 | Data_Structure_10861 | I | [
"encode_rle",
"decode_rle",
"compress_rle"
] | 3 | [
[
"compress_rle",
"encode_rle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2bbed65a0630d98a77b10ae515211c572d9d40cb | f1c8f24e3068fb8e5e6fef7b2aef4bc6702826e6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10888_I | ### Matrix Chain Multiplication Problem
You are designing an efficient system for computing powers of matrices. Given a square matrix, you need to implement a function to compute the power of this matrix using the technique of matrix exponentiation by repeated squaring.
#### Function Signature
```python
def matrix_po... | from typing import List
def matrix_multiply(a: List[List[int]], b: List[List[int]]) -> List[List[int]]:
"""
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):
for k in range(n):
re... | from solution import matrix_power
def test_matrix_power_identity():
assert matrix_power([[1]], 5) == [[1]]
assert matrix_power(
[
[1, 0],
[0, 1]
], 10
) == [
[1, 0],
[0, 1]
]
def test_matrix_power_zero_exponent():
assert matrix_power(
... | [
{
"docstring": "Multiplies two square matrices a and b.",
"function_declaration": "def matrix_multiply(a, b):",
"function_name": "matrix_multiply",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the power of a matrix using exponentiation by squaring.",
"function_declaration": "de... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n n = len(A)\n result = [[0] * n for _ in ran... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00010888",
"row_id": 10888,
"seed_ids": "[340]"
} | 0.535769 | Data_Structure_10888 | I | [
"matrix_multiply",
"matrix_power"
] | 2 | [
[
"matrix_power",
"matrix_multiply"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 17e6c9aee5ede80a70b5e7e8035dcd6bfcdde1cb | 3846f2106e6bd7fec25a8f1a800bdfe39437abb2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10918_I | ## Problem: Implement and Optimize a Stooge Sort
Stooge Sort is an interesting but inefficient sorting algorithm. Given its educational value, you are tasked with implementing this algorithm and then also implementing an optimized version of Merge Sort to compare performance.
### Steps:
1. Implement the `stooge_sort` ... | import time
def stooge_sort(arr, l, h):
if l >= h:
return
if arr[l] > arr[h]:
arr[l], arr[h] = arr[h], arr[l]
if h - l + 1 > 2:
t = (h - l + 1) // 3
stooge_sort(arr, l, h - t)
stooge_sort(arr, l + t, h)
stooge_sort(arr, l, h - t)
def merge_sort(arr):
if ... | from solution import stooge_sort, merge_sort, compare_sorting_algorithms
def test_stooge_sort():
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
expected_sorted_arr = sorted(arr)
stooge_sort(arr, 0, len(arr) - 1)
assert arr == expected_sorted_arr
def test_merge_sort():
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3,... | [
{
"docstring": null,
"function_declaration": "def stooge_sort(arr, l, h):",
"function_name": "stooge_sort",
"parameter_list": "(arr, l, h)"
},
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\n\ndef stooge_sort(arr, l, h):\n \"\"\"\n Recursively sorts the array using Stooge Sort algorithm.\n \"\"\"\n if l >= h:\n retu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00010918",
"row_id": 10918,
"seed_ids": "[10]"
} | 0.539295 | Data_Structure_10918 | I | [
"stooge_sort",
"merge_sort",
"compare_sorting_algorithms"
] | 3 | [
[
"compare_sorting_algorithms",
"merge_sort"
],
[
"compare_sorting_algorithms",
"stooge_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1c19e5896bb5d1fe608e4cc4b97d3cd443ee0201 | 754cb79d80dd7a02517f843c89717b19d0b67b77 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10935_I | ### Question 1: Intersection of Two Linked Lists
You are provided with the structure of a linked list and your task is to determine if two singly-linked lists intersect, and if so, return the node at which they intersect.
### Constraints
* The two linked lists must retain their original structure after the function ... | class Node:
def __init__(self, data):
self.data = data
self.next = None
def get_length(node):
length = 0
while node:
length += 1
node = node.next
return length
def find_intersection(head1, head2):
if not head1 or not head2:
return None
# Get the len... | from solution import Node, find_intersection
def test_find_intersection():
a1 = Node(1)
b1 = Node(3)
c1 = Node(5)
d = Node(7)
a2 = Node(2)
b2 = Node(4)
c2 = Node(6)
e = Node(9)
f = Node(11)
a1.next = b1
b1.next = c1
c1.next = d
a2.next = b2
b2.next = c2
c2.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": "class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\ndef get_length(node):\n length = 0\n while node:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00010935",
"row_id": 10935,
"seed_ids": "[245]"
} | 0.554297 | Data_Structure_10935 | I | [
"get_length",
"find_intersection"
] | 2 | [
[
"find_intersection",
"get_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 74b9b857bce0af72e1bbdc9cd628abbfe0176163 | c84e254f3a4b11ce6ebf74cc43ddcc32ef360527 | |||
v1.0 | instruct | Data_Structure | Data_Structure_10979_I | Implement a Simple Diffie-Hellman Key Exchange Process
#### Context
Alice and Bob want to securely communicate with each other over an insecure network. To do this, they decide to use the Diffie-Hellman key exchange method to establish a shared secret key. However, they need your help to ensure the correctness and sec... | import math
from random import randint
def prime_check(num):
if num <= 1:
return False
if num == 2 or num == 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
... | import pytest
from solution import secure_diffie_hellman, prime_check, find_primitive_root
def test_prime_check():
assert prime_check(23) == True
assert prime_check(10) == False
assert prime_check(2) == True
assert prime_check(1) == False
def test_find_primitive_root():
assert set(find_primitive_r... | [
{
"docstring": null,
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def find_order(a, n):",
"function_name": "find_order",
"parameter_list": "(a, n)"
},
{
"docstri... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom random import randint\n\ndef prime_check(num):\n if num <= 1:\n return False\n if num == 2 or num == 3:\n return True\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00010979",
"row_id": 10979,
"seed_ids": "[146]"
} | 0.531359 | Data_Structure_10979 | I | [
"prime_check",
"find_order",
"euler_totient",
"find_primitive_root",
"secure_diffie_hellman"
] | 5 | [
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"find_order"
],
[
"secure_diffie_hellman",
"find_primitive_root"
],
[
"secure_diffie_hellman",
"prime_check"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 8a878114154c345a294db9454bc3724e02ad0c97 | 4c0810f69441d33f0d180e349cfcf224093831ad | |||
v1.0 | instruct | Data_Structure | Data_Structure_11036_I | ### Exchange Sort Optimization Challenge
**Scenario**:
You are working on optimizing a sorting routine in a legacy system where algorithms are chosen based on specific dataset characteristics. The system currently employs the Exchange Sort algorithm, which is efficient on small arrays due to its simplicity but not s... | def exchange_sort(arr):
"""
Implements the Exchange Sort algorithm.
:param arr: A list of integers that need to be sorted.
:return: A sorted list of integers in non-decreasing order.
"""
n = len(arr)
for i in range(n):
for j in range(i + 1, n):
if arr[i] > arr[j]:
... | from solution import optimized_sort
def test_optimized_sort_small_array():
assert optimized_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
assert optimized_sort([3]) == [3]
assert optimized_sort([10, -1, 2, 8, 0, 5, 4]) == [-1, 0, 2, 4, 5, 8, 10]
def test_optimized_sort_large_array():
assert optimized... | [
{
"docstring": "Implements the Exchange Sort algorithm.\n\n:param arr: A list of integers that need to be sorted.\n:return: A sorted list of integers in non-decreasing order.",
"function_declaration": "def exchange_sort(arr):",
"function_name": "exchange_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 exchange_sort(arr):\n n = len(arr)\n for i in range(n):\n for j in range(i + 1, n):\n if arr[i] > arr[j]:\n arr[i],... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011036",
"row_id": 11036,
"seed_ids": "[28]"
} | 0.610737 | Data_Structure_11036 | I | [
"exchange_sort",
"merge_sort",
"merge",
"optimized_sort"
] | 4 | [
[
"merge_sort",
"merge"
],
[
"optimized_sort",
"exchange_sort"
],
[
"optimized_sort",
"merge_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | aa5b73ca97cac3b160cff34538ca6b249b3292f7 | b2c8630f9e320ede10264f9150ad5aa1ac7f7fcd | |||
v1.0 | instruct | Data_Structure | Data_Structure_11045_I | ### Elias Gamma and Delta Encoding Algorithms
#### Problem Statement
You are tasked with implementing two encoding algorithms for compressing positive integers: Elias Gamma encoding and Elias Delta encoding.
Each encoded value must follow specific rules:
1. **Elias Gamma Encoding**:
- Calculate the unary represen... | import math
def elias_gamma(x: int) -> str:
if x <= 0:
raise ValueError("Input must be a positive integer.")
if x == 1: # Special case for 1
return "1"
N = int(math.log2(x))
# Unary part (1 + floor(log2(x)))
unary_part = '0' * N + '1'
# Binary part (x - 2^fl... | def test_elias_gamma():
assert elias_gamma(1) == "1"
assert elias_gamma(2) == "010"
assert elias_gamma(3) == "011"
assert elias_gamma(4) == "00100"
assert elias_gamma(5) == "00101"
assert elias_gamma(6) == "00110"
assert elias_gamma(7) == "00111"
assert elias_gamma(8) == "0001000"
as... | [
{
"docstring": null,
"function_declaration": "def elias_gamma(x):",
"function_name": "elias_gamma",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def elias_delta(x):",
"function_name": "elias_delta",
"parameter_list": "(x)"
}
] | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef elias_gamma(x: int) -> str:\n \"\"\"\n Returns the Elias Gamma encoded string of a positive integer x.\n x should be >= 1.\n \"... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00011045",
"row_id": 11045,
"seed_ids": "[333]"
} | 0.524062 | Data_Structure_11045 | I | [
"elias_gamma",
"elias_delta"
] | 2 | [
[
"elias_delta",
"elias_gamma"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 96ad858df3eb1c7743c40b62888bf691123b8136 | a5ce11226695ead7c63bb48e4a638410ddfa67d5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_11064_I | **Problem Statement**:
You are provided with a list of positive integers, and your task is to implement the `radix_sort` function to sort this list in ascending order. The `radix_sort` should be implemented as described in the provided algorithm analysis.
**Function Signature**:
```python
def radix_sort(arr: List[int]... | from typing import List
def counting_sort(arr: List[int], exp: int) -> List[int]:
n = len(arr)
output = [0] * n # output array to store sorted numbers
count = [0] * 10 # count array to store count of occurrences of digits
# Store count of occurrences in count[]
for i in range(n):
index =... | from solution import radix_sort
def test_radix_sort_example_1():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_example_2():
assert radix_sort([3, 1, 4, 1, 5]) == [1, 1, 3, 4, 5]
def test_radix_sort_empty_list():
assert radix_sort([]) == []
... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_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 counting_sort(arr, exp):\n \"\"\"\n A function to do counting sort of arr[] according to\n the digit represented by ex... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011064",
"row_id": 11064,
"seed_ids": "[15]"
} | 0.670031 | Data_Structure_11064 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b766660d81c61679b2ee828a22a5aaf7eeda6bfe | 6c444f1398361296801059fe0ff7113238ba6e83 | |||
v1.0 | instruct | Data_Structure | Data_Structure_11194_I | ### Maximum Flow Problem
You're given a directed graph represented by a capacity matrix, a source node, and a sink node. Your task is to implement three different algorithms to find the maximum flow from the source to the sink node: Ford-Fulkerson (DFS-based), Edmonds-Karp (BFS-based), and Dinic's Algorithm.
#### Inpu... | from collections import deque
# Ford-Fulkerson Algorithm using DFS
def dfs_find_path(capacity, residual_capacity, source, sink, parent):
visited = [False] * len(capacity)
stack = [source]
while stack:
node = stack.pop()
if node == sink:
return True
for next_node in ... | def test_ford_fulkerson():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert ford_fulkerson(capacity, source, sink) == 23
def test_edm... | [
{
"docstring": null,
"function_declaration": "def dfs_find_path(capacity, residual_capacity, source, sink, parent):",
"function_name": "dfs_find_path",
"parameter_list": "(capacity, residual_capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def ford_fulker... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\n# Ford-Fulkerson Algorithm using DFS\ndef dfs_find_path(capacity, residual_capacity, source, sink, parent):\n visited = [F... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00011194",
"row_id": 11194,
"seed_ids": "[240]"
} | 0.589893 | Data_Structure_11194 | I | [
"dfs_find_path",
"ford_fulkerson",
"bfs_find_path",
"edmonds_karp",
"bfs_level_graph",
"dfs_flow",
"dinic"
] | 7 | [
[
"dinic",
"bfs_level_graph"
],
[
"dinic",
"dfs_flow"
],
[
"edmonds_karp",
"ford_fulkerson"
],
[
"ford_fulkerson",
"dfs_find_path"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 14e5a3a22cc28294f80460257d436889b88da895 | 14f62ecbbfb2cfd0cc7f08f9e9696a0c5c901588 | |||
v1.0 | instruct | Data_Structure | Data_Structure_11220_I | ### Coding Task
#### Scenario:
In your work as a software developer, you often encounter systems of simultaneous congruences while dealing with various cryptographic protocols. To ensure the security and efficiency of your system, you must implement a reliable function that finds solutions to these systems using the C... | from typing import List
def extended_gcd(a, b):
if a == 0:
return b, 0, 1
gcd, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y
def mod_inverse(a, m):
gcd, x, _ = extended_gcd(a, m)
if gcd != 1:
raise ValueError(f"No modular inverse for {a} and... | def test_basic_solution():
nums = [3, 5, 7]
rems = [2, 3, 2]
assert solve_chinese_remainder(nums, rems) == 23
def test_valid_multiple_solutions():
nums = [2, 3, 5]
rems = [1, 2, 3]
assert solve_chinese_remainder(nums, rems) == 23 # 23 % 2 = 1, 23 % 3 = 2, 23 % 5 = 3
def test_single_congru... | [
{
"docstring": null,
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def mod_inverse(a, m):",
"function_name": "mod_inverse",
"parameter_list": "(a, m)"
},
{
"d... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef solve_chinese_remainder(nums: List[int], rems: List[int]) -> int:\n if len(nums) != len(rems):\n raise ValueError(\"T... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00011220",
"row_id": 11220,
"seed_ids": "[158]"
} | 0.626489 | Data_Structure_11220 | I | [
"extended_gcd",
"mod_inverse",
"solve_chinese_remainder"
] | 3 | [
[
"mod_inverse",
"extended_gcd"
],
[
"solve_chinese_remainder",
"extended_gcd"
],
[
"solve_chinese_remainder",
"mod_inverse"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 4b9615b312fc087f43505702fcfe275898162b0d | 73fa52cb13b28b0c2e1e91928a2c86372a242469 | |||
v1.0 | instruct | Data_Structure | Data_Structure_11251_I | ### Prime Number Sequence Check
Given a list of integers, implement a function that returns a new list containing only the prime numbers from the original list.
## Function Signature
```python
def filter_primes(numbers: List[int]) -> List[int]:
pass
```
### Input
- A list of integers (`numbers`) where each eleme... | from typing import List
def is_prime(n: int) -> bool:
"""
Determines if a number is a prime number.
"""
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:
... | from solution import filter_primes
def test_filter_primes_basic():
assert filter_primes([10, 15, 3, 7, 23, 30]) == [3, 7, 23]
def test_filter_primes_empty_list():
assert filter_primes([]) == []
def test_filter_primes_no_primes():
assert filter_primes([4, 6, 8, 12, 14]) == []
def test_filter_primes_a... | [
{
"docstring": "Determines if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Filters out the prime numbers from the list of integers.",
"function_declaration": "def filter_primes(numbers):"... | [
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 is_prime(n: int) -> bool:\n \"\"\"\n Helper function to determine if a given number n is a prime number.\n \"\"\"\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011251",
"row_id": 11251,
"seed_ids": "[143]"
} | 0.682556 | Data_Structure_11251 | I | [
"is_prime",
"filter_primes"
] | 2 | [
[
"filter_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0176d06b109d342fca7c98018dff4116cce67f56 | 07f967393b352792f699bb1365e65d74b9963557 | |||
v1.0 | instruct | Data_Structure | Data_Structure_11284_I | ### Question
You are tasked with implementing a feature for a mathematical simulation that involves frequent calculations with matrices. Specifically, you need to create a function to take a matrix and raise it to a specified power efficiently.
Implement the function `matrix_exponentiation(matrix: list, power: int) ->... | def matrix_multiply(A, B):
n = len(A)
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += A[i][k] * B[k][j]
return result
def matrix_exponentiation(matrix, power):
if power == 0:
size = len(ma... | def test_matrix_exponentiation_with_zero_power():
matrix = [
[2, 3],
[4, 5]
]
power = 0
assert matrix_exponentiation(matrix, power) == [
[1, 0],
[0, 1]
]
def test_matrix_exponentiation_with_power_one():
matrix = [
[2, 3],
[4, 5]
]
power = ... | [
{
"docstring": null,
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def matrix_exponentiation(matrix, power):",
"function_name": "matrix_exponentiation",
"parame... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B.\n \"\"\"\n size = len(A)\n result = [[0] * size for _ in range(size)]\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011284",
"row_id": 11284,
"seed_ids": "[340]"
} | 0.550812 | Data_Structure_11284 | I | [
"matrix_multiply",
"matrix_exponentiation"
] | 2 | [
[
"matrix_exponentiation",
"matrix_multiply"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 25efbb73b9a8f1bf4c71011e446994a0e5061778 | 2f03922cbb54ca78935e6e9e2823f238260631cb | |||
v1.0 | instruct | Data_Structure | Data_Structure_11294_I | You are given an array of integers where each integer represents the size of matrices such that the ith matrix's dimension is array[i-1] x array[i]. Your task is to implement a function that calculates the minimum number of multiplications needed to multiply the chain of matrices optimally. Additionally, you need to pr... | def matrix_chain_order(array):
n = len(array) - 1 # Number of matrices
# Initialize the cost matrix
cost = [[float('inf')] * n for _ in range(n)]
# Initialize the solution matrix for optimal split positions
solution = [[0] * n for _ in range(n)]
# A single matrix multiplication cost is zer... | from solution import matrix_chain_order, get_optimal_order
def test_matrix_chain_order_base_case():
array = [10, 20]
cost, solution = matrix_chain_order(array)
assert cost == [[0]]
assert solution == [[0]]
def test_matrix_chain_order_simple_case():
array = [10, 20, 30]
cost, solution = matrix_... | [
{
"docstring": null,
"function_declaration": "def matrix_chain_order(array):",
"function_name": "matrix_chain_order",
"parameter_list": "(array)"
},
{
"docstring": null,
"function_declaration": "def print_optimal_parenthesization(solution, i, j):",
"function_name": "print_optimal_par... | [
0,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_chain_order(array):\n \"\"\"\n :param array: List[int] - An array where each element represents the dimension of matrices.\n :return: Tupl... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00011294",
"row_id": 11294,
"seed_ids": "[45]"
} | 0.543117 | Data_Structure_11294 | I | [
"matrix_chain_order",
"print_optimal_parenthesization",
"get_optimal_order"
] | 3 | [
[
"get_optimal_order",
"matrix_chain_order"
],
[
"get_optimal_order",
"print_optimal_parenthesization"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c7c6be9519cca7ec4f51898c78bfde1a9eb05c33 | 30f348978f2650a8e7142e578b9877f5ab88ce0e | |||
v1.0 | instruct | Data_Structure | Data_Structure_11310_I | Tree Traversal and Printing
You are given a hierarchical tree data structure representing different categories and their corresponding objects. Each object in the tree can have sub-objects denoted either by strings or further nested dictionaries. Your task is to implement a function `enhanced_tree_print(tree: dict) ->... | def enhanced_tree_print(tree, indent=0):
"""
Recursively print the tree structure in a readable nested format.
Args:
tree (dict): The tree structure to print.
indent (int): The current indentation level (used for recursive calls).
"""
for key, value in tree.items():
print(" " * ... | def test_empty_tree():
assert enhanced_tree_print({}) == None
def test_single_level_tree():
tree = {
'a': ['Adam', 'Book', 4],
}
assert enhanced_tree_print(tree) == None
def test_nested_tree():
tree = {
'a': ['Adam', 'Book', 4],
'b': ['Bill', {'Computer': 5, 'TV': 6}],
... | [
{
"docstring": "Recursively print the tree structure in a readable nested format.\n\nArgs:\ntree (dict): The tree structure to print.\nindent (int): The current indentation level (used for recursive calls).",
"function_declaration": "def enhanced_tree_print(tree, indent=0):",
"function_name": "enhanced_... | [
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 enhanced_tree_print(tree: dict, indent: str = '') -> None:\n \"\"\"\n Prints the tree structure in a readable nested format with clear indentation.\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011310",
"row_id": 11310,
"seed_ids": "[303]"
} | 0.502382 | Data_Structure_11310 | I | [
"enhanced_tree_print",
"print_list"
] | 2 | [
[
"enhanced_tree_print",
"print_list"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 09809c413f1b1e32e38e1732b7de75e013721256 | 23d825843cb49daba307f7143ecbb4314f0c70cb | |||
v1.0 | instruct | Data_Structure | Data_Structure_11339_I | ### Matrix Inversion Coding Challenge
#### Objective
Implement a function `invert_matrix(m)` that inverts a given n x n matrix.
#### Description
Given an n x n matrix represented by a list of lists, write a Python function `invert_matrix(m)` that returns the inverted matrix. The matrix inversion must follow these ste... | def determinant(matrix):
""" Recursively calculates the determinant of a square matrix """
if len(matrix) == 1:
return matrix[0][0]
if len(matrix) == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for c in range(len(matrix)):
minor = get... | from solution import invert_matrix
def test_invert_matrix_2x2():
assert invert_matrix([[4, 7], [2, 6]]) == [[0.6, -0.7], [-0.2, 0.4]]
def test_invert_matrix_3x3():
assert invert_matrix([[1, 2, 3], [0, 1, 4], [5, 6, 0]]) == [[-24.0, 18.0, 5.0], [20.0, -15.0, -4.0], [-5.0, 4.0, 1.0]]
def test_invert_matrix_sin... | [
{
"docstring": "Recursively calculates the determinant of a square matrix ",
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def get_minor(matrix, i, j):",
"function_name... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def invert_matrix(m):\n \"\"\"\n Inverts a given square matrix m using the method described in the prompt.\n \"\"\"\n def get_matrix_minor(m, i, j... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011339",
"row_id": 11339,
"seed_ids": "[347]"
} | 0.601673 | Data_Structure_11339 | I | [
"determinant",
"get_minor",
"matrix_of_minors",
"matrix_of_cofactors",
"transpose",
"invert_matrix"
] | 6 | [
[
"determinant",
"get_minor"
],
[
"invert_matrix",
"determinant"
],
[
"invert_matrix",
"matrix_of_cofactors"
],
[
"invert_matrix",
"transpose"
],
[
"matrix_of_cofactors",
"matrix_of_minors"
],
[
"matrix_of_minors",
"determinant"
],
[
"matri... | 7 | [] | false | [] | false | pytest | true | [] | true | 70fae485ff71600c7158bec5ed7f0a3ae8dd3ac2 | 38b8ccddea8412027231f6342907774dc36d4252 | |||
v1.0 | instruct | Data_Structure | Data_Structure_11361_I | ### Question
You are given a set of two positive integers and need to determine both their Greatest Common Divisor (GCD) and their Least Common Multiple (LCM). The catch is to implement the GCD using bitwise operations, as it can be faster for large integers. For this task:
#### Function Signature
```python
def gcd_bi... | def gcd_bit(a: int, b: int) -> int:
"""
Compute the greatest common divisor (GCD) of a and b using bitwise operations.
"""
if a == b:
return a
if a == 0:
return b
if b == 0:
return a
# Both a and b are even
if (~a & 1) and (~b & 1):
return gcd_bit(a >> 1,... | from solution import gcd_bit, lcm_using_gcd_bit
def test_gcd_bit():
assert gcd_bit(8, 12) == 4
assert gcd_bit(14, 21) == 7
assert gcd_bit(101, 103) == 1
assert gcd_bit(18, 24) == 6
assert gcd_bit(56, 98) == 14
assert gcd_bit(1, 1) == 1
assert gcd_bit(1, 10) == 1
assert gcd_bit(0, 10) ==... | [
{
"docstring": "Compute the greatest common divisor (GCD) of a and b using bitwise operations.",
"function_declaration": "def gcd_bit(a, b):",
"function_name": "gcd_bit",
"parameter_list": "(a, b)"
},
{
"docstring": "Compute the least common multiple (LCM) of a and b using their GCD.",
"... | [
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 greatest common divisor (GCD) of a and b using bitwise operations.\n \"\"\"\n if a == b... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00011361",
"row_id": 11361,
"seed_ids": "[166]"
} | 0.698915 | Data_Structure_11361 | I | [
"gcd_bit",
"lcm_using_gcd_bit"
] | 2 | [
[
"lcm_using_gcd_bit",
"gcd_bit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 51c70f63a62a0cd14b1e7dd618c9f0168e1682c1 | e16bb3a855e8533a650621c3899e070a20574cfd | |||
v1.0 | instruct | Data_Structure | Data_Structure_11410_I | ### Question: Implement Enhanced Insertion Sort using Binary Search
**Context**:
Imagine you are tasked with implementing an optimized version of the Insertion Sort algorithm that leverages binary search to determine the location where the next element should be inserted. This approach is intended to reduce the number... | from typing import List
def binary_search(arr: List[int], val: int, start: int, end: int) -> int:
"""
Binary search helper function to find the index where val should be inserted.
:param arr: List of sorted elements
:param val: Element to be inserted
:param start: Starting index for the search
... | from solution import insertion_sort_binary
def test_insertion_sort_binary_sorted():
assert insertion_sort_binary([1, 2, 3, 4, 5, 6]) == [1, 2, 3, 4, 5, 6]
def test_insertion_sort_binary_reverse():
assert insertion_sort_binary([6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6]
def test_insertion_sort_binary_unsorted()... | [
{
"docstring": "Binary search helper function to find the index where val should be inserted.\n:param arr: List of sorted elements\n:param val: Element to be inserted\n:param start: Starting index for the search\n:param end: Ending index for the search\n:return: The index where the val should be inserted",
... | [
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_binary(arr: List[int]) -> List[int]:\n def binary_search(sub_array, val):\n lo, hi = 0, len(sub_array)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011410",
"row_id": 11410,
"seed_ids": "[199]"
} | 0.554886 | Data_Structure_11410 | I | [
"binary_search",
"insertion_sort_binary"
] | 2 | [
[
"insertion_sort_binary",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 76da935f02c36af73e0a22e9034c44896083a043 | 12ce0a824aa185a051c0b90e46ea6eeb09613802 | |||
v1.0 | instruct | Data_Structure | Data_Structure_11473_I | - Bogo Sort Enhancement
#### Context
You have been provided with the highly inefficient Bogo Sort algorithm. Despite its impracticality in real-world applications, it serves as a good exercise to understand brute-force methods and randomness in algorithms.
#### Task
Write a function to implement a modified version of... | 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_with_cap(arr, max_shuffles):
"""
Sort the array using a capped Bogo Sort.
Par... | from solution import bogo_sort_with_cap
def test_bogo_sort_sorted_array():
assert bogo_sort_with_cap([1, 2, 3, 4], 10000) == [1, 2, 3, 4]
assert bogo_sort_with_cap([], 10000) == []
def test_bogo_sort_single_element_array():
assert bogo_sort_with_cap([1], 10000) == [1]
def test_bogo_sort_unsorted_array():... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sort the array using a capped Bogo Sort.\n\nParameters:\narr (list): A list of sortable elements.\nmax_... | [
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_with_cap(arr, max_shuffles):\n \"\"\"\n Sort the array using a capped Bogo Sort.\n \n Parameters:\n arr (list): ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011473",
"row_id": 11473,
"seed_ids": "[16]"
} | 0.595109 | Data_Structure_11473 | I | [
"is_sorted",
"bogo_sort_with_cap"
] | 2 | [
[
"bogo_sort_with_cap",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f5e224c0f6c97372862c573d8ddba94108599f76 | ae096a534892577092557a418a5bb956bddffccc | |||
v1.0 | instruct | Data_Structure | Data_Structure_11556_I | ### Matrix Inversion Problem
#### Context
In linear algebra, matrix inversion is a crucial operation for solving systems of linear equations, computing pseudoinverses, and performing various transformations. You are required to implement a function that takes an invertible \( n \times n \) matrix and returns its inver... | from typing import List
def determinant(matrix: List[List[float]], n: int) -> float:
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):
minor = [[matrix[i][j] for j in range(n) if j != c] for i i... | from solution import invert_matrix
def test_invert_2x2_matrix():
matrix = [
[4, 7],
[2, 6]
]
expected_result = [
[0.6, -0.7],
[-0.2, 0.4]
]
assert invert_matrix(matrix) == expected_result
def test_invert_3x3_matrix():
matrix = [
[1, 2, 3],
[0, 1,... | [
{
"docstring": null,
"function_declaration": "def determinant(matrix, n):",
"function_name": "determinant",
"parameter_list": "(matrix, n)"
},
{
"docstring": null,
"function_declaration": "def get_matrix_of_minors(matrix, n):",
"function_name": "get_matrix_of_minors",
"parameter_... | [
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 get_matrix_minor(matrix, i, j):\n return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]\n\ndef get_matrix_dete... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011556",
"row_id": 11556,
"seed_ids": "[347]"
} | 0.579364 | Data_Structure_11556 | I | [
"determinant",
"get_matrix_of_minors",
"get_cofactor_matrix",
"transpose",
"invert_matrix"
] | 5 | [
[
"get_cofactor_matrix",
"get_matrix_of_minors"
],
[
"get_matrix_of_minors",
"determinant"
],
[
"invert_matrix",
"determinant"
],
[
"invert_matrix",
"get_cofactor_matrix"
],
[
"invert_matrix",
"transpose"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | ee52bcb58a333dc6dbaf7eba45c88f78fb8b3d7e | bb601c2583acb66501199e0f8fbc7a39e3c4f0fe | |||
v1.0 | instruct | Data_Structure | Data_Structure_11566_I | ### Context:
You are working on a networking project where data packets need to be transmitted from one server to another along the maximum possible data routes. The network is represented as a directed graph, where the nodes are servers and edges represent bandwidth capacities. You need to compute the maximum data tra... | from collections import deque
def bfs(residual_graph, source, sink, parent):
visited = [False] * len(residual_graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(residual_graph[u]):
if visited[v] =... | from solution import maximum_flow_bfs
def test_general_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow_bfs(graph) == 23
def test_no_capacity_... | [
{
"docstring": null,
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bfs(adjacency_matrix):",
"function_name"... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs_search(source, sink, parent, residual_graph):\n \"\"\"\n Perform BFS to find the shortest augmenting path in re... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011566",
"row_id": 11566,
"seed_ids": "[229]"
} | 0.643365 | Data_Structure_11566 | I | [
"bfs",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0450fccd982118aa440ff9de6d7e32e2b6110202 | 81228cf763691dab0a71bf46f12fe51f67b748df | |||
v1.0 | instruct | Data_Structure | Data_Structure_11577_I | ### Scenario
You are working on a library management system and need an efficient way to organize books based on their unique IDs, which are large non-negative integers. Since the volume of books is immense, a high-performance sorting algorithm is required that can handle large datasets effectively.
### Objective
Writ... | from typing import List
def counting_sort_for_radix(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index ... | from solution import library_sort
def test_library_sort_with_small_list():
assert library_sort([3, 1, 2]) == [1, 2, 3]
def test_library_sort_with_identical_elements():
assert library_sort([432, 432, 432, 432]) == [432, 432, 432, 432]
def test_library_sort_with_example_list():
assert library_sort([170, 45... | [
{
"docstring": null,
"function_declaration": "def counting_sort_for_radix(arr, exp):",
"function_name": "counting_sort_for_radix",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def library_sort(book_ids):",
"function_name": "library_sort",
"param... | [
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 library_sort(book_ids: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of non-negative integers using Radix Sort.\n \... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011577",
"row_id": 11577,
"seed_ids": "[15]"
} | 0.590277 | Data_Structure_11577 | I | [
"counting_sort_for_radix",
"library_sort"
] | 2 | [
[
"library_sort",
"counting_sort_for_radix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 08f1c462bad0c9c24b9362edd08d2bfbc3b3173a | a62ae7cca2078575a0ef9ec65a8d7784635ea134 | |||
v1.0 | instruct | Data_Structure | Data_Structure_11586_I | ### Question: Two Sum with Multiple Methods
You are given a list of integers `numbers` sorted in ascending order, and a target integer `target`. Your task is to write a function `find_indices` that returns the list of indices of two numbers such that they add up to the `target`. There are three methods you should impl... | from typing import List, Tuple
def find_indices_binary_search(numbers: List[int], target: int) -> List[int]:
import bisect
for i in range(len(numbers)):
complement = target - numbers[i]
idx = bisect.bisect_left(numbers, complement, i + 1)
if idx < len(numbers) and numbers[idx] == comple... | from solution import find_indices
def test_find_indices_two_pointers():
assert find_indices([2, 7, 11, 15], 9) == [1, 2]
assert find_indices([1, 2, 3, 4, 4], 8) == [4, 5]
assert find_indices([-3, 3, 4, 90], 0) == [1, 2]
assert find_indices([5, 25, 75], 100) == [2, 3]
assert find_indices([1, 2, 3, 4... | [
{
"docstring": null,
"function_declaration": "def find_indices_binary_search(numbers, target):",
"function_name": "find_indices_binary_search",
"parameter_list": "(numbers, target)"
},
{
"docstring": null,
"function_declaration": "def find_indices_hash_table(numbers, target):",
"func... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef find_indices(numbers: List[int], target: int) -> List[int]:\n def find_indices_binary_search():\n def binary_search(l... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00011586",
"row_id": 11586,
"seed_ids": "[195]"
} | 0.582291 | Data_Structure_11586 | I | [
"find_indices_binary_search",
"find_indices_hash_table",
"find_indices_two_pointers",
"find_indices"
] | 4 | [
[
"find_indices",
"find_indices_two_pointers"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4cc0fb924ab1b181515f847e552b6fed7b4318e1 | 64f16752664959d48c91b23e14681b28b0281bf2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_11589_I | ### Coding Problem: Extended Euclidean Algorithm and Modular Arithmetic Solver
#### Objective:
Your task is to write a Python function that takes two integers and returns their GCD, as well as coefficients that satisfy Bézout's identity. Additionally, you will implement a function that computes a modular inverse using... | def extended_gcd(a: int, b: int) -> (int, int, int):
"""
Applies the Extended Euclidean Algorithm to find the coefficients x and y such that:
a*x + b*y = gcd(a, b)
Returns a tuple (x, y, gcd).
"""
if b == 0:
return (1, 0, a)
else:
x1, y1, gcd = extended_gcd(b, a % b)
... | from solution import extended_gcd, modular_inverse
def test_extended_gcd_basic():
s, t, gcd = extended_gcd(30, 20)
assert gcd == 10
assert s * 30 + t * 20 == gcd
def test_extended_gcd_coprime():
s, t, gcd = extended_gcd(35, 64)
assert gcd == 1
assert s * 35 + t * 64 == gcd
def test_extended_g... | [
{
"docstring": "Applies the Extended Euclidean Algorithm to find the coefficients x and y such that:\na*x + b*y = gcd(a, b)\n\nReturns a tuple (x, y, gcd).",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Find... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def extended_gcd(a: int, b: int) -> (int, int, int):\n \"\"\"\n Return a tuple (s, t, g), such that\n s * a + t * b = g\n where g is the greatest ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011589",
"row_id": 11589,
"seed_ids": "[161]"
} | 0.67477 | Data_Structure_11589 | I | [
"extended_gcd",
"modular_inverse"
] | 2 | [
[
"modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fca13af0d8eeaf86d275be72d9e29110cd9d60ab | 8bfe3bfa6062ac0f6cf9db1cb74c2f57e9b16e7c | |||
v1.0 | instruct | Data_Structure | Data_Structure_11750_I | ### Array Rotation Challenge
#### Objectives:
Given an array of integers and a non-negative integer k, rotate the array to the right by k steps. Implement the function `rotate_array(array, k)` using different approaches:
1. Simple shift method.
2. Reverse segment method.
3. Slicing concatenation method.
#### Requirem... | def rotate_simple(array, k):
n = len(array)
k %= n
for _ in range(k):
temp = array[n - 1]
for j in range(n - 1, 0, -1):
array[j] = array[j - 1]
array[0] = temp
return array
def rotate_reverse(array, k):
def reverse(arr, start, end):
while start < end:
... | from solution import rotate_simple, rotate_reverse, rotate_slice, rotate_array
def test_rotate_simple():
assert rotate_simple([1, 2, 3, 4, 5, 6, 7], 3) == [5, 6, 7, 1, 2, 3, 4]
assert rotate_simple([1, 2, 3, 4, 5], 2) == [4, 5, 1, 2, 3]
assert rotate_simple([1, 2, 3, 4], 0) == [1, 2, 3, 4]
assert rotat... | [
{
"docstring": null,
"function_declaration": "def rotate_simple(array, k):",
"function_name": "rotate_simple",
"parameter_list": "(array, k)"
},
{
"docstring": null,
"function_declaration": "def rotate_reverse(array, k):",
"function_name": "rotate_reverse",
"parameter_list": "(ar... | [
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 rotate_array(array, k):\n def rotate_simple(array, k):\n n = len(array)\n k %= n\n for _ in range(k):\n temp = array.po... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011750",
"row_id": 11750,
"seed_ids": "[283]"
} | 0.597051 | Data_Structure_11750 | I | [
"rotate_simple",
"rotate_reverse",
"rotate_slice",
"rotate_array"
] | 4 | [
[
"rotate_array",
"rotate_reverse"
],
[
"rotate_array",
"rotate_simple"
],
[
"rotate_array",
"rotate_slice"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 45a489d547ea2bd2bf1645400fbb851e2e4dff77 | dfe25f129dfa6eb9c1a2b6bbbedc78f3c8062e7c | |||
v1.0 | instruct | Data_Structure | Data_Structure_11753_I | **Problem Statement**:
You are tasked with implementing the in-place sorting algorithm, Quick Sort, to help in organizing arrays of integers more efficiently. Your implementation should aim for average-case time complexity of O(n log(n)) and handle edge cases explicitly.
**Requirements**:
1. Develop a function `quick... | from typing import List
def insertion_sort(arr: List[int], low: int, high: int) -> None:
for i in range(low + 1, high + 1):
key = arr[i]
j = i - 1
while j >= low and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def median_of_three(arr: List[int]... | import pytest
from solution import quick_sort
def test_quick_sort_empty_array():
assert quick_sort([]) == []
def test_quick_sort_single_element():
assert quick_sort([1]) == [1]
def test_quick_sort_already_sorted():
assert quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_quick_sort_reverse_sorted(... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, low, high):",
"function_name": "insertion_sort",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[int], left: int, right: int):\n for i in range(left + 1, right + 1):\n key = arr[i]\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011753",
"row_id": 11753,
"seed_ids": "[25]"
} | 0.583534 | Data_Structure_11753 | I | [
"insertion_sort",
"median_of_three",
"partition",
"quick_sort_recursive",
"quick_sort"
] | 5 | [
[
"partition",
"median_of_three"
],
[
"quick_sort",
"quick_sort_recursive"
],
[
"quick_sort_recursive",
"insertion_sort"
],
[
"quick_sort_recursive",
"partition"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 9321dd0d385cf014b5ec61762ff9d4572fd99169 | aa3a12fa12f9e009d55700b61a0cb1b284f2ff46 | |||
v1.0 | instruct | Data_Structure | Data_Structure_11780_I | ### Bogo Sort Enhancement and Comparative Analysis
You are tasked with enhancing the Bogo Sort algorithm provided above, and writing a comparative function to demonstrate the impracticality of Bogo Sort against another efficient sorting algorithm (e.g., Quick Sort).
#### Task
1. **Enhanced Bogo Sort**: Write a functi... | 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 enhanced_bogo_sort(arr, max_iterations):
"""
Enhanced Bogo Sort that adds a limit to the number ... | import pytest
from solution import enhanced_bogo_sort, quick_sort, compare_sorts
def test_is_sorted():
assert is_sorted([1, 2, 3, 4, 5])
assert not is_sorted([1, 3, 2, 4, 5])
def test_enhanced_bogo_sort_sorted():
arr = [1, 2, 3]
sorted_arr, iterations = enhanced_bogo_sort(arr, 100)
assert sorted_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 adds a limit to the number of iterations.\nIf the array is not sorted within th... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if the array is sorted.\n \"\"\"\n for i in range(len(arr) - 1):\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00011780",
"row_id": 11780,
"seed_ids": "[16]"
} | 0.559613 | Data_Structure_11780 | I | [
"is_sorted",
"enhanced_bogo_sort",
"quick_sort",
"compare_sorts"
] | 4 | [
[
"compare_sorts",
"enhanced_bogo_sort"
],
[
"compare_sorts",
"quick_sort"
],
[
"enhanced_bogo_sort",
"is_sorted"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 15fb6871a7670deb753b553ce6627b63ac13ced8 | a24739e643084ac3e16f83a60998394acfb70e5f | |||
v1.0 | instruct | Data_Structure | Data_Structure_11874_I | ### **Assessing Your Understanding of Diffie-Hellman Key Exchange**
You are given the following task to implement a function to securely exchange a secret key between two parties (Alice and Bob) using the steps of the Diffie-Hellman key exchange protocol. Given a prime number \( p \) and its primitive root \( a \), Al... | import random
from typing import Optional
def mod_exp(base: int, exp: int, mod: int) -> int:
"""Helper function to perform modular exponentiation."""
result = 1
base = base % mod
while exp > 0:
if exp % 2:
result = (result * base) % mod
exp = exp >> 1
base = (base * ... | from solution import diffie_hellman_key_exchange
def test_diffie_hellman_basic():
assert diffie_hellman_key_exchange(5, 23) == True
def test_diffie_hellman_edge_case_primitive_root_at_lower_bound():
assert diffie_hellman_key_exchange(2, 23) == True
def test_diffie_hellman_invalid_input_primitive_root():
... | [
{
"docstring": "Helper function to perform modular exponentiation.",
"function_declaration": "def mod_exp(base, exp, mod):",
"function_name": "mod_exp",
"parameter_list": "(base, exp, mod)"
},
{
"docstring": "Implementation of the Diffie-Hellman key exchange protocol.",
"function_declara... | [
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 mod_exp(base, exp, mod):\n result = 1\n while exp > 0:\n if exp % 2 == 1:\n result = (result * base) % mod\n base = (base *... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011874",
"row_id": 11874,
"seed_ids": "[146]"
} | 0.508247 | Data_Structure_11874 | I | [
"mod_exp",
"diffie_hellman_key_exchange"
] | 2 | [
[
"diffie_hellman_key_exchange",
"mod_exp"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d210480be9a91fe031abbd921c078b4dc0ab5b25 | a067ff543156a22a7ec404e095e849ec9117bade | |||
v1.0 | instruct | Data_Structure | Data_Structure_11905_I | **Context**:
You are a developer at a company where you often need to sort large datasets efficiently. Your task is to implement the merge sort algorithm, ensuring it works correctly for all possible inputs.
**Task**:
Implement the `merge_sort` function provided. The function should sort an array of integers in ascend... | def merge_sort(arr):
"""
Merge Sort algorithm to sort an array.
:param arr: List[int] - The input array of integers to be sorted
:return: List[int] - The sorted array
"""
# Base case
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
ri... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_unsorted_list():
assert merge... | [
{
"docstring": "Merge Sort algorithm to sort an array.\n:param arr: List[int] - The input array of integers to be sorted\n:return: List[int] - The sorted array",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merge ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Merge Sort algorithm to sort an array.\n :param arr: List[int] - The input array of integers to be sorted\n :retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011905",
"row_id": 11905,
"seed_ids": "[12]"
} | 0.669255 | Data_Structure_11905 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8c5fa6d2942b8987d0ae083d69807d6911af83a3 | b2cbb6eb3b5c35e73e2ddff38eb82a44f2f94ec3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_11910_I | ### Shell Sort Enhancement
Shell Sort is an improved insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, taking every `h`th element (where `h` is an integer variable constantly decreasing) yields a sorted list. Initially, the gap ... | def generate_sedgewick_gaps(n):
"""
Generates the Sedgewick gap sequence up to the largest gap less than n.
"""
gaps = []
index = 0
gap = 0
while True:
if index % 2 == 0:
gap = 9 * (4**index - 2**index) + 1
else:
gap = 8 * (2**(index + 1) - 1) + 1... | from solution import enhanced_shell_sort
def test_enhanced_shell_sort_normal_case():
assert enhanced_shell_sort([12, 34, 54, 2, 3]) == [2, 3, 12, 34, 54]
def test_enhanced_shell_sort_with_negative_numbers():
assert enhanced_shell_sort([7, -4, 1, 8, -5, 2]) == [-5, -4, 1, 2, 7, 8]
def test_enhanced_shell_sort... | [
{
"docstring": "Generates the Sedgewick gap sequence up to the largest gap less than n.",
"function_declaration": "def generate_sedgewick_gaps(n):",
"function_name": "generate_sedgewick_gaps",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def enhanced_shell_sor... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef sedgewick_gaps(max_length: int) -> List[int]:\n gaps = []\n k = 0\n while True:\n gap1 = 4**k + 3 * 2**(k - 1) ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011910",
"row_id": 11910,
"seed_ids": "[22]"
} | 0.620218 | Data_Structure_11910 | I | [
"generate_sedgewick_gaps",
"enhanced_shell_sort"
] | 2 | [
[
"enhanced_shell_sort",
"generate_sedgewick_gaps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c92bade6109d8c337ce73ee02928cdb6f88c5bb3 | 08c319273d5877a52859cd32e3d8fb88647de59d | |||
v1.0 | instruct | Data_Structure | Data_Structure_11922_I | ### Context
Quick Sort is a highly efficient sorting algorithm, but it can suffer from poor performance with certain types of input. To mitigate this, advanced versions of Quick Sort use techniques like median-of-three pivot selection or hybrid approaches. These methods are designed to optimize the pivot selection and ... | def insertion_sort(arr, left, right):
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 median_of_three(arr, left, right):
mid = (left + right) // 2
if arr[lef... | from solution import optimized_quick_sort
def test_optimized_quick_sort_example():
arr = [23, 45, 12, 56, 1, 34, 22, 76, 64, 43]
sorted_arr = optimized_quick_sort(arr, threshold=5)
assert sorted_arr == sorted(arr)
def test_optimized_quick_sort_empty():
arr = []
sorted_arr = optimized_quick_sort(ar... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def median_of_three(arr, left, right):",
"function_name": "median_of_three"... | [
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 insertion_sort(arr, left, right):\n for i in range(left + 1, right + 1):\n key = arr[i]\n j = i - 1\n while j >= left and arr[j] >... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00011922",
"row_id": 11922,
"seed_ids": "[25]"
} | 0.561997 | Data_Structure_11922 | I | [
"insertion_sort",
"median_of_three",
"partition",
"quick_sort_recursive",
"optimized_quick_sort"
] | 5 | [
[
"optimized_quick_sort",
"quick_sort_recursive"
],
[
"partition",
"median_of_three"
],
[
"quick_sort_recursive",
"insertion_sort"
],
[
"quick_sort_recursive",
"partition"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 8594872e97e7032c565b5fb0c9a2b2bca7bcda01 | 4cc5cea2e3059ba61dd1fdd7d60bdb19171551d7 | |||
v1.0 | instruct | Data_Structure | Data_Structure_11957_I | ### Radix Sort Enhancement and Analysis
You are tasked with enhancing the provided radix sort implementation and analyzing its performance with various datasets. Here, you need to:
1. **Improve the Function**: Modify the given radix sort function to handle potential edge cases such as empty arrays and arrays containi... | from typing import List, Tuple
import time
def enhanced_radix_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers using the radix sort algorithm.
Raises ValueError for empty lists and lists containing non-integer values.
"""
if not arr:
raise ValueError("Input array is empty")
... | from solution import enhanced_radix_sort, measure_performance
import pytest
def test_enhanced_radix_sort_empty_array():
with pytest.raises(ValueError, match="Input array is empty"):
enhanced_radix_sort([])
def test_enhanced_radix_sort_non_integer_values():
with pytest.raises(ValueError, match="All ele... | [
{
"docstring": "Sorts a list of integers using the radix sort algorithm. \nRaises ValueError for empty lists and lists containing non-integer values.",
"function_declaration": "def enhanced_radix_sort(arr):",
"function_name": "enhanced_radix_sort",
"parameter_list": "(arr)"
},
{
"docstring":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport time\n\ndef enhanced_radix_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of integers using radix sor... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011957",
"row_id": 11957,
"seed_ids": "[15]"
} | 0.561106 | Data_Structure_11957 | I | [
"enhanced_radix_sort",
"measure_performance"
] | 2 | [
[
"measure_performance",
"enhanced_radix_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 19f47d4fd2f5e9c8b3e8ae30f3c85054d882ae82 | c440b135acc8cdda4574cc5bec39a7f74073469a | |||
v1.0 | instruct | Data_Structure | Data_Structure_12020_I | ### Coding Challenge: Implement a Custom Sort Algorithm
### Objective
Design and implement a sorting algorithm that is more efficient than Bogo Sort. You can choose any deterministic sorting algorithm (e.g., Quick Sort, Merge Sort, etc.) and explain why it is an improvement over Bogo Sort.
### Problem Statement
Imple... | def efficient_sort(arr):
"""
This function uses the Merge Sort algorithm to sort an array in non-decreasing order.
Merge Sort has a time complexity of O(n log n), which is significantly better than Bogo Sort,
which has an average time complexity of O((n*n!)).
Merge Sort is chosen due to i... | from solution import efficient_sort
def test_empty_array():
assert efficient_sort([]) == []
def test_single_element():
assert efficient_sort([1]) == [1]
def test_sorted_array():
assert efficient_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert efficient_sort([5, 4, 3,... | [
{
"docstring": "This function uses the Merge Sort algorithm to sort an array in non-decreasing order.\n\nMerge Sort has a time complexity of O(n log n), which is significantly better than Bogo Sort, \nwhich has an average time complexity of O((n*n!)).\n\nMerge Sort is chosen due to its stable sort nature and it... | [
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_sort(arr):\n \"\"\"\n Implements the Merge Sort algorithm to sort the array in non-decreasing order.\n Merge Sort is chosen for its eff... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012020",
"row_id": 12020,
"seed_ids": "[16]"
} | 0.661051 | Data_Structure_12020 | I | [
"efficient_sort",
"_merge"
] | 2 | [
[
"efficient_sort",
"_merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bc353f8c4e26045bcb2a7b6da046f6d19fce12b7 | 5fff391acdf34c2048201a18ba0ae0267a303b53 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.