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_18439_I | Alice and Bob want to establish a secret key using the Diffie-Hellman key exchange protocol. However, they need to ensure that the prime number p and the generator a they use are valid to guarantee the security of their key exchange.
Write a function `secure_diffie_hellman(p, a, verbose=False)` that:
1. Validates if `... | def is_prime(n):
"""Check if the input number n is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True... | def test_secure_diffie_hellman_valid_inputs():
assert secure_diffie_hellman(23, 5, verbose=True) == True
def test_secure_diffie_hellman_invalid_generator():
assert secure_diffie_hellman(23, 10) == False
def test_secure_diffie_hellman_large_prime_valid_primitive_root():
assert secure_diffie_hellman(97, 5) ... | [
{
"docstring": "Check if the input number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find a primitive root for prime p.",
"function_declaration": "def find_primitive_root(p):",
"function_name": "fi... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime\n\ndef find_order(a, p):\n \"\"\"\n Find the order of a modulo p.\n \"\"\"\n for k in range(1, p):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018439",
"row_id": 18439,
"seed_ids": "[146]"
} | 0.518363 | Data_Structure_18439 | I | [
"is_prime",
"find_primitive_root",
"find_prime_factors",
"secure_diffie_hellman"
] | 4 | [
[
"find_primitive_root",
"find_prime_factors"
],
[
"find_primitive_root",
"is_prime"
],
[
"secure_diffie_hellman",
"find_primitive_root"
],
[
"secure_diffie_hellman",
"is_prime"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 550e77aeefdfb2acfc17d073a627cedc8694c292 | 96acb60d7b62baabbdc950aee6b5c93e793e40d8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_18539_I | **Objective**: Demonstrate understanding of sorting algorithms and their efficiency.
**Context**:
Bogo Sort is an intentionally inefficient sorting algorithm that works by repeatedly shuffling the array until it happens to be in order. Despite its inefficiency, it provides a good educational example of how randomizati... | import random
def is_sorted(arr):
"""
Helper function to check if an array is sorted.
"""
return all(arr[i] <= arr[i+1] for i in range(len(arr) - 1))
def efficient_bogo_sort(arr):
"""
Attempts to improve upon the Bogo Sort algorithm by recognizing sorted subarrays
and only shuffling the u... | from solution import efficient_bogo_sort
def test_sorted_array():
assert efficient_bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert efficient_bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_duplicate_elements():
assert efficient_bogo_sort([3, 1, 4, 1, 5, 9, 2, ... | [
{
"docstring": "Helper function to check if an array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Attempts to improve upon the Bogo Sort algorithm by recognizing sorted subarrays \nand only shuffling th... | [
0,
0,
0,
0,
0,
0,
1,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\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_8 | {
"original_instruction": "",
"prompt_id": "00018539",
"row_id": 18539,
"seed_ids": "[16]"
} | 0.602556 | Data_Structure_18539 | I | [
"is_sorted",
"efficient_bogo_sort"
] | 2 | [
[
"efficient_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1bb8ed143c68c2ce7d7ce1f6a6ae9f7441e734e1 | a4bf9bf9869626d2a21e2b14ff86610185cbf3ac | |||
v1.0 | instruct | Data_Structure | Data_Structure_18618_I | ### Prime Number Range Finder
You are given a function, `prime_check(n)`, which correctly identifies whether a number `n` is prime or not. Your task is to use this to implement a new function `find_primes_in_range(start, end)` that will find all prime numbers in a given inclusive range `[start, end]`.
#### Function S... | from typing import List
def prime_check(n: int) -> bool:
"""
Determines if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
... | from solution import find_primes_in_range
def test_find_primes_in_range_basic():
assert find_primes_in_range(10, 20) == [11, 13, 17, 19]
def test_find_primes_in_range_single_prime():
assert find_primes_in_range(2, 2) == [2]
def test_find_primes_in_range_no_primes():
assert find_primes_in_range(14, 16) ==... | [
{
"docstring": "Determines if a number is prime.",
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers in the range [start, end].",
"function_declaration": "def find_primes_in_range(star... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef prime_check(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018618",
"row_id": 18618,
"seed_ids": "[143]"
} | 0.649346 | Data_Structure_18618 | I | [
"prime_check",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 974914a1aee311a205ba2595fb62ae6f006284b5 | 6451f8abb1f495710fff570da97cd43fc5ba56d1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_18644_I | ### RSA Encryption and Decryption
You are required to implement a key pair generation function and utilize it to carry out encryption and decryption using the RSA algorithm.
**Function Specs**:
1. **generate_key(k: int) -> Tuple[int, int, int]**
- Generates and returns an RSA key pair — public key (n, e) and pr... | import random
from sympy import isprime, mod_inverse
from typing import Tuple
def generate_prime_candidate(length):
# Generates an odd integer randomly in the range from 2^(length-1) to 2^length.
p = random.getrandbits(length)
# Apply a mask to set MSB and LSB to 1 to ensure prime candidate of length 'leng... | from solution import generate_key, encrypt, decrypt
def test_generate_key_length():
n, e, d = generate_key(16)
assert len(bin(n)) - 2 == 16, "Modulus length should be 16 bits"
def test_encrypt_decrypt_small_data():
k = 16
data = 20
n, e, d = generate_key(k)
encrypted_data = encrypt(data, e, n)... | [
{
"docstring": null,
"function_declaration": "def generate_prime_candidate(length):",
"function_name": "generate_prime_candidate",
"parameter_list": "(length)"
},
{
"docstring": null,
"function_declaration": "def generate_prime_number(length):",
"function_name": "generate_prime_numbe... | [
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 math import gcd\n\ndef generate_prime(bits):\n \"\"\" Generates a prime number of specified bit length. \"\"\"\n while True:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018644",
"row_id": 18644,
"seed_ids": "[154]"
} | 0.725871 | Data_Structure_18644 | I | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 2c5589e5609bac18942d85cb9e2069fd9e7b813c | b8531d6b2a0d9c78d0791b80d0fe54f546cd7bb0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_18647_I | Write a Python function `fibonacci_matrix(n: int) -> int` to compute the nth Fibonacci number using matrix exponentiation.
### Input:
* A single integer \( n \) (0 ≤ n ≤ 10^18)
### Output:
* The nth Fibonacci number.
### Constraints:
* The result should be returned modulo \( 10^9 + 7 \).
### Function Signature
```... | def matrix_multiply(A, B, mod):
"""
Multiplies two 2x2 matrices A and B under modulo `mod`.
"""
return [
[(A[0][0] * B[0][0] + A[0][1] * B[1][0]) % mod, (A[0][0] * B[0][1] + A[0][1] * B[1][1]) % mod],
[(A[1][0] * B[0][0] + A[1][1] * B[1][0]) % mod, (A[1][0] * B[0][1] + A[1][1] * B[1][1])... | import pytest
from solution import fibonacci_matrix
def test_fibonacci_matrix_base_cases():
assert fibonacci_matrix(0) == 0
assert fibonacci_matrix(1) == 1
def test_fibonacci_matrix_small_numbers():
assert fibonacci_matrix(2) == 1
assert fibonacci_matrix(3) == 2
assert fibonacci_matrix(4) == 3
... | [
{
"docstring": "Multiplies two 2x2 matrices A and B under modulo `mod`.",
"function_declaration": "def matrix_multiply(A, B, mod):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B, mod)"
},
{
"docstring": "Computes the n-th power of a 2x2 matrix under modulo `mod`.",
"funct... | [
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": "def fibonacci_matrix(n: int) -> int:\n MOD = 10**9 + 7\n\n def matrix_mult(A, B):\n \"\"\"Multiplies two 2x2 matrices A and B under modulo.\"\"\"... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00018647",
"row_id": 18647,
"seed_ids": "[340]"
} | 0.676355 | Data_Structure_18647 | I | [
"matrix_multiply",
"matrix_power",
"fibonacci_matrix"
] | 3 | [
[
"fibonacci_matrix",
"matrix_power"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e0254d6be94dfe0c1f9e2eb2d4cf1398bad94140 | dff50535b5603e00619d7e2de9262a66d70f6d6d | |||
v1.0 | instruct | Data_Structure | Data_Structure_18670_I | ### Word Squares Generation with Prefix-based Backtracking
You are given a list of unique words. A word square is a sequence of words such that the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).
Write a function `generate_word_squares(words)` that produces all possible word sq... | from typing import List, Dict
def build_prefix_dict(words: List[str]) -> Dict[str, List[str]]:
prefix_dict = {}
for word in words:
for i in range(len(word)):
prefix = word[:i]
if prefix in prefix_dict:
prefix_dict[prefix].append(word)
else:
... | import pytest
from solution import generate_word_squares
def test_generate_word_squares_example1():
words = ["area","lead","wall","lady","ball"]
expected_output = [
["wall", "area", "lead", "lady"],
["ball", "area", "lead", "lady"]
]
assert generate_word_squares(words) == expected_outpu... | [
{
"docstring": null,
"function_declaration": "def build_prefix_dict(words):",
"function_name": "build_prefix_dict",
"parameter_list": "(words)"
},
{
"docstring": null,
"function_declaration": "def backtrack(index, word_square, results, prefix_dict):",
"function_name": "backtrack",
... | [
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, Dict\n\ndef build_prefix_dict(words: List[str]) -> Dict[str, List[str]]:\n prefix_dict = {}\n for word in words:\n for i... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00018670",
"row_id": 18670,
"seed_ids": "[87]"
} | 0.592972 | Data_Structure_18670 | I | [
"build_prefix_dict",
"backtrack",
"generate_word_squares"
] | 3 | [
[
"generate_word_squares",
"backtrack"
],
[
"generate_word_squares",
"build_prefix_dict"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1c4323a2eca17a5ce306d53b700b5a24e9b6ccd8 | 064d298a13842b51f97e644aebca7cf3ec93b7e7 | |||
v1.0 | instruct | Data_Structure | Data_Structure_18682_I | You are tasked with implementing a secure communication system between two parties (Alice and Bob) using Diffie-Hellman Key Exchange. The system should ensure that both parties can share a common secret key securely over an insecure channel.
Write a function `secure_communication(a: int, p: int) -> tuple` that perform... | import random
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return... | from solution import secure_communication, is_prime, find_primitive_root
def test_secure_communication():
a, p = 5, 23
alice_shared_key, bob_shared_key = secure_communication(a, p)
assert alice_shared_key == bob_shared_key
def test_invalid_prime():
a, p = 5, 22
try:
secure_communication(a,... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find a primitive root of p.",
"function_declaration": "def find_primitive_root(p):",
"function_name": "find_primitive_root... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00018682",
"row_id": 18682,
"seed_ids": "[146]"
} | 0.438165 | Data_Structure_18682 | I | [
"is_prime",
"find_primitive_root",
"secure_communication"
] | 3 | [
[
"secure_communication",
"find_primitive_root"
],
[
"secure_communication",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 48c364379c16373e3ead2eb43375b1df2bf345ab | 152251f63b12116e7fd9731dbfd33729d13c6e48 | |||
v1.0 | instruct | Data_Structure | Data_Structure_18741_I | You are given a list of pairwise coprime positive integers `nums` and a list of corresponding remainders `rems`. Your task is to implement an optimized function to solve the system of congruences using the Chinese Remainder Theorem (CRT).
#### Function Signature
```python
def optimized_chinese_remainder(nums: List[int... | from typing import List, Tuple
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
"""
Returns a tuple (g, x, y), where g is the greatest common divisor of a and b, and
x and y are the coefficients of Bézout's identity, i.e., a*x + b*y = g
"""
if a == 0:
return (b, 0, 1)
else:
... | from solution import optimized_chinese_remainder
def test_optimized_chinese_remainder_basic():
assert optimized_chinese_remainder([3, 5, 7], [2, 3, 2]) == 23
def test_optimized_chinese_remainder_single_congruence():
assert optimized_chinese_remainder([5], [3]) == 3
def test_optimized_chinese_remainder_pairwi... | [
{
"docstring": "Returns a tuple (g, x, y), where g is the greatest common divisor of a and b, and \nx and y are the coefficients of Bézout's identity, i.e., a*x + b*y = g",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"do... | [
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 extended_gcd(a: int, b: int) -> Tuple[int, int, int]:\n \"\"\"\n Returns a tuple (g, x, y), where g is the greates... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00018741",
"row_id": 18741,
"seed_ids": "[158]"
} | 0.571966 | Data_Structure_18741 | I | [
"extended_gcd",
"optimized_chinese_remainder"
] | 2 | [
[
"optimized_chinese_remainder",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5cdac370f3c88506d5a28f43043b1fd347591770 | db3000fe89ee76c653abf477ab15b43e42028eaf | |||
v1.0 | instruct | Data_Structure | Data_Structure_18778_I | ### Question
You work for a data processing company that frequently sorts large datasets of integers. Your task is to implement the radix sort algorithm for the company. However, you need to modify the radix sort algorithm provided in the code snippet to handle negative integers as well.
### Description
Given an arr... | def counting_sort(arr, exp):
"""
A helper function to perform counting sort based on the digit represented by exp (10^i).
"""
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = abs(arr[i]) // exp
count[index % 10] += 1
for i in range(1, 10... | from solution import extended_radix_sort
def test_empty_list():
assert extended_radix_sort([]) == []
def test_single_element():
assert extended_radix_sort([5]) == [5]
assert extended_radix_sort([-5]) == [-5]
def test_all_positive_numbers():
assert extended_radix_sort([170, 45, 75, 802, 24, 2, 66]) ==... | [
{
"docstring": "A helper function to perform counting sort based on the digit represented by exp (10^i).",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "A helper function to perform radix sort on an... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # Store count occurrences in count[]\n for i in range(n):... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00018778",
"row_id": 18778,
"seed_ids": "[15]"
} | 0.637684 | Data_Structure_18778 | I | [
"counting_sort",
"radix_sort",
"extended_radix_sort"
] | 3 | [
[
"extended_radix_sort",
"radix_sort"
],
[
"radix_sort",
"counting_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 98e6389408d2eda7c60d6bf247ae756e8ab388dd | 273030d18784cb0e1c61ee768522bd522b51023b | |||
v1.0 | instruct | Data_Structure | Data_Structure_18784_I | ### Matrix Power Calculation
You are given a square matrix `A` of dimensions `d x d` and an integer `n`. Your task is to compute the matrix `A` raised to the power of `n` (A^n) efficiently.
Write a function `matrix_power(A: list, n: int) -> list` that takes a list of lists `A` representing a square matrix and an integ... | def matrix_multiply(A, B):
# Matrix multiplication of A and B
dim = len(A)
C = [[0] * dim for _ in range(dim)]
for i in range(dim):
for j in range(dim):
C[i][j] = sum(A[i][k] * B[k][j] for k in range(dim))
return C
def identity_matrix(dim):
# Create an identity matrix of dim... | from solution import matrix_power
def test_identity_power():
A = [
[1, 2],
[3, 4]
]
n = 0
expected = [
[1, 0],
[0, 1]
]
assert matrix_power(A, n) == expected
def test_power_one():
A = [
[1, 2],
[3, 4]
]
n = 1
expected = A
asse... | [
{
"docstring": null,
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def identity_matrix(dim):",
"function_name": "identity_matrix",
"parameter_list": "(dim)"
}... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_multiply(A, B):\n # Matrix multiplication of A and B\n dim = len(A)\n C = [[0] * dim for _ in range(dim)]\n for i in range(dim):\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00018784",
"row_id": 18784,
"seed_ids": "[340]"
} | 0.583404 | Data_Structure_18784 | I | [
"matrix_multiply",
"identity_matrix",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity_matrix"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f81d94da42e2f72ead6a0e7c9427f1ed7de77891 | 0cbd1e9f75686b6d59cfa54634f6dbe4fa52453d | |||
v1.0 | instruct | Data_Structure | Data_Structure_18814_I | ### Question: Implement a Custom Pancake Sort Variant
As a software development challenge, you are tasked with implementing a customized variant of the Pancake Sort algorithm. This variant should additionally include a feature where a predefined threshold value splits the sorting process. Any elements greater than the ... | def flip(arr, k):
"""Helper function to flip the first k elements of the list."""
arr[:k] = arr[:k][::-1]
def pancake_sort(arr, indices):
"""Pancake sort the elements of arr specified by the indices."""
n = len(indices)
for i in range(n, 1, -1):
# Index of the maximum element in the unsorte... | def test_custom_pancake_sort():
assert custom_pancake_sort([3, 6, 4, 7, 2, 5], 4) == [5, 6, 7, 2, 3, 4]
assert custom_pancake_sort([10, 9, 1, 2, 15, 20], 12) == [15, 20, 1, 2, 9, 10]
assert custom_pancake_sort([8, 4, 6, 2, 3, 5, 1], 5) == [6, 8, 1, 2, 3, 4, 5]
assert custom_pancake_sort([], 5) == []
... | [
{
"docstring": "Helper function to flip the first k elements of the list.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Pancake sort the elements of arr specified by the indices.",
"function_declaration": "def panc... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def flip(arr, k):\n \"\"\"\n Reverses the order of the first k elements of the array.\n \"\"\"\n start = 0\n while start < k:\n arr[star... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00018814",
"row_id": 18814,
"seed_ids": "[9]"
} | 0.651176 | Data_Structure_18814 | I | [
"flip",
"pancake_sort",
"custom_pancake_sort"
] | 3 | [
[
"custom_pancake_sort",
"pancake_sort"
],
[
"pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 9ee69388788f85235168936a0912b47178bf9db2 | 0c72436cd17ec883d717594349365d4abafecea9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_18933_I | You need to implement a function to detect cycles in a directed graph. A cycle in a directed graph is a path that starts and ends at the same vertex and has at least one edge.
### Function Signature
```python
def has_cycle(graph: DirectedGraph) -> bool:
"""
:param graph: DirectedGraph - The directed graph inst... | class DirectedGraph:
def __init__(self, adjacency_list):
self.adjacency_list = adjacency_list
def _dfs(vertex, visited, rec_stack, graph):
visited.add(vertex)
rec_stack.add(vertex)
for neighbor in graph.adjacency_list.get(vertex, []):
if neighbor not in visited:
if _dfs(nei... | from solution import has_cycle, DirectedGraph
def test_cycle_present():
graph_data = {
'A': ['B'],
'B': ['C'],
'C': ['A']
}
graph = DirectedGraph(graph_data)
assert has_cycle(graph) == True
def test_no_cycle():
graph_data = {
'A': ['B'],
'B': ['C'],
... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class DirectedGraph:\n def __init__(self, graph_data):\n \"\"\"\n Initializes the directed graph with given adjacency list.\n :param g... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018933",
"row_id": 18933,
"seed_ids": "[223]"
} | 0.609252 | Data_Structure_18933 | I | [
"_dfs",
"has_cycle"
] | 2 | [
[
"has_cycle",
"_dfs"
]
] | 1 | [] | false | [
"DirectedGraph"
] | true | pytest | true | [] | true | 03ae860f4091aef75b70adeee1e6ee2a41bac0d2 | f567197dc96d48a301266ccb1618b4d06cfb127d | |||
v1.0 | instruct | Data_Structure | Data_Structure_18962_I | ### Prime Number Filter
You are given a list of integers and your task is to filter out the prime numbers using the provided efficient prime-checking algorithm.
#### Function Signature
```python
def filter_primes(number_list: List[int]) -> List[int]:
"""
Given a list of integers, return a new list containing ... | from typing import List
def is_prime(n: int) -> bool:
"""
Efficient prime-checking algorithm to determine if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
limit = int(n**0.5) + 1
for i in range(3, limit, 2):
... | from solution import filter_primes
def test_filter_primes_simple():
assert filter_primes([10, 15, 2, 3, 5, 30, 31, 37, 0, -7, 101]) == [2, 3, 5, 31, 37, 101]
def test_filter_primes_empty():
assert filter_primes([]) == []
def test_filter_primes_no_primes():
assert filter_primes([4, 6, 8, 10, 12, 14]) == [... | [
{
"docstring": "Efficient prime-checking algorithm to determine if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given a list of integers, return a new list containing only the prime numbers.",
"fu... | [
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 is_prime(n: int) -> bool:\n \"\"\"\n Check if the given number n is a prime number.\n \n Args:\n n (int): Number... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018962",
"row_id": 18962,
"seed_ids": "[143]"
} | 0.658547 | Data_Structure_18962 | I | [
"is_prime",
"filter_primes"
] | 2 | [
[
"filter_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c28344cdbf7bdf4f83952385c9724de283156162 | d3d267c6cb88bfa6672b42ecbd2d8ffe367760bc | |||
v1.0 | instruct | Data_Structure | Data_Structure_18988_I | ### Question: Implement Radix Sort with Handling for Negative Numbers
Given a list of integers, write a function `radix_sort_with_negatives` to sort the list in ascending order using Radix Sort. The standard Radix Sort works well for non-negative integers, but your implementation should be able to handle negative inte... | def counting_sort(arr, exp, simulation):
n = len(arr)
output = [0] * n
count = [0] * 10
# Count occurrences
for i in range(n):
index = abs(arr[i]) // exp
count[index % 10] += 1
# Compute cumulative count
for i in range(1, 10):
count[i] += count[i - 1]
# Build o... | def test_radix_sort_with_negatives():
from solution import radix_sort_with_negatives
# Test with mixed values including negatives
assert radix_sort_with_negatives([170, 45, 75, -45, -75, 90, -802, 24, 2, 66], simulation=False) == [-802, -75, -45, 2, 24, 45, 66, 75, 90, 170]
# Test with no values
as... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
},
{
"docstring": null,
"function_declaration": "def radix_sort_with_negatives(arr, simulation=False):",
"function_nam... | [
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 counting_sort(arr, exp, simulation):\n \"\"\" A function to do counting sort of arr[] according to the digit represented by exp. \"\"\"\n n = len(ar... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018988",
"row_id": 18988,
"seed_ids": "[15]"
} | 0.650721 | Data_Structure_18988 | I | [
"counting_sort",
"radix_sort_with_negatives"
] | 2 | [
[
"radix_sort_with_negatives",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 24a92e8957f85a192b5ceacfb716cc19be0e5356 | a8d7efd349002fa67c574f8018db3fd096b1a887 | |||
v1.0 | instruct | Data_Structure | Data_Structure_18989_I | ### Question: Full Binary Tree Construction and Inorder Traversal
#### Problem Statement:
You are required to construct a full binary tree from the given preorder and postorder traversals. A full binary tree is defined as a tree where every node has either zero or two children. Once the tree is constructed, you need t... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def construct_tree(pre, post):
if not pre or not post:
return None
root_val = pre[0]
root = TreeNode(root_val)
if len(pre) == 1:
ret... | from solution import construct_inorder
def test_construct_inorder_basic():
pre = [1, 2, 4, 8, 9, 5, 3, 6, 7]
post = [8, 9, 4, 5, 2, 6, 7, 3, 1]
expected_inorder = [8, 4, 9, 2, 5, 1, 6, 3, 7]
assert construct_inorder(pre, post) == expected_inorder
def test_construct_inorder_single_node():
pre = [1]... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef cons... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018989",
"row_id": 18989,
"seed_ids": "[300]"
} | 0.567976 | Data_Structure_18989 | I | [
"construct_tree",
"inorder_traversal",
"construct_inorder"
] | 3 | [
[
"construct_inorder",
"construct_tree"
],
[
"construct_inorder",
"inorder_traversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | f7f2228b5fbbba7e0875b32ad47c8d5d70cc3cc9 | 0d4e62ad22e0555ba0720dd7751d5230df633563 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19067_I | ### Maximum Network Flow Challenge
#### Context
You are working as a network engineer and have been tasked with optimizing the transportation of goods over a network of pipelines. Each pipeline has a maximum capacity indicating the maximum flow of goods it can handle per unit time. Your objective is to determine the m... | from typing import List
from collections import deque
def bfs_level_graph(capacity, level, 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[... | from solution import max_flow_dinics
def test_max_flow_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_dini... | [
{
"docstring": null,
"function_declaration": "def bfs_level_graph(capacity, level, source, sink):",
"function_name": "bfs_level_graph",
"parameter_list": "(capacity, level, source, sink)"
},
{
"docstring": null,
"function_declaration": "def send_flow(u, flow, sink, level, capacity, start... | [
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 max_flow_dinics(capacity: List[List[int]], source: int, sink: int) -> int:\n n = len(capacity... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019067",
"row_id": 19067,
"seed_ids": "[240]"
} | 0.577138 | Data_Structure_19067 | I | [
"bfs_level_graph",
"send_flow",
"max_flow_dinics"
] | 3 | [
[
"max_flow_dinics",
"bfs_level_graph"
],
[
"max_flow_dinics",
"send_flow"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ead41584e3fd827b3e044b05e859e9ef2efc35ea | def279617ea1eef3b92724e5679638912f56bb71 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19080_I | **RSA Key Generation and Encryption-Decryption**
**Objective**: Implement the missing part of the RSA encryption-decryption system and ensure correct functionality by generating RSA keys, and using them to encrypt and decrypt data.
**Scenario**:
You are developing a system for secure communication between clients and... | import random
from math import gcd
from sympy import isprime
def generate_prime(bits):
"""Generate a prime number with the given number of bits."""
while True:
p = random.getrandbits(bits)
if isprime(p):
return p
def modinv(a, m):
"""Return the modular inverse of a modulo m."""... | from solution import generate_key, encrypt, decrypt
def test_rsa_key_generation():
n, e, d = generate_key(512, seed=42)
assert n.bit_length() == 512
assert e > 1
assert d > 1
def test_rsa_encryption_decryption():
n, e, d = generate_key(512, seed=42)
data = 12345
encrypted_data = encrypt(da... | [
{
"docstring": "Generate a prime number with the given number of bits.",
"function_declaration": "def generate_prime(bits):",
"function_name": "generate_prime",
"parameter_list": "(bits)"
},
{
"docstring": "Return the modular inverse of a modulo m.",
"function_declaration": "def modinv(a... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_large_prime(bits, seed=None):\n if seed is not None:\n random.seed(seed)\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00019080",
"row_id": 19080,
"seed_ids": "[154]"
} | 0.56803 | Data_Structure_19080 | I | [
"generate_prime",
"modinv",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_prime"
],
[
"generate_key",
"modinv"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 9072b56e85ef449881be0c432ca85af37b4247f6 | d0a70f7f1f6539f89147d3c16ae57300f535fe79 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19106_I | ### Heap Sort Implementation
Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure to sort elements. You are required to implement two variants of the heap sort algorithm:
1. **max_heap_sort**: Use this to sort an array in ascending order by repeatedly creating a max heap and moving... | from typing import List
def max_heapify(arr: List[int], n: int, i: int, simulation: bool = False):
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
... | from solution import max_heap_sort, min_heap_sort
def test_max_heap_sort():
assert max_heap_sort([3, 19, 1, 14, 8, 7]) == [1, 3, 7, 8, 14, 19]
assert max_heap_sort([4, 10, 3, 5, 1]) == [1, 3, 4, 5, 10]
assert max_heap_sort([12, 11, 13, 5, 6, 7]) == [5, 6, 7, 11, 12, 13]
assert max_heap_sort([38, 27, 43... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, simulation=False):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def max_heap_sort(arr, simulation=False):",
"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 max_heapify(arr, n, i, simulation):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n and arr[i] < arr[left]:\n larg... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019106",
"row_id": 19106,
"seed_ids": "[8]"
} | 0.712534 | Data_Structure_19106 | 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 | 5d23536423163fc414fce67b455d393b9815add9 | f4b3492ecbd58ba45ec36bf525e40123a6361d27 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19133_I | ### Interpolation Search Enhancement
The existing implementation of the interpolation search performs well on uniformly distributed data. However, it can be enhanced by adding additional checks to handle non-uniformly distributed arrays better and avoid potential performance pitfalls.
#### Objective
Your task is to e... | def fallback_binary_search(array, search_key, low, high):
while low <= high:
mid = (low + high) // 2
if array[mid] == search_key:
return mid
elif array[mid] < search_key:
low = mid + 1
else:
high = mid - 1
return -1
def enhanced_interpolation_... | from solution import enhanced_interpolation_search
def test_enhanced_interpolation_search_found():
array = [-25, -12, -1, 10, 12, 15, 20, 41, 55]
assert enhanced_interpolation_search(array, -1) == 2
def test_enhanced_interpolation_search_not_found():
array = [5, 10, 12, 14, 17, 20, 21]
assert enhanced... | [
{
"docstring": null,
"function_declaration": "def fallback_binary_search(array, search_key, low, high):",
"function_name": "fallback_binary_search",
"parameter_list": "(array, search_key, low, high)"
},
{
"docstring": null,
"function_declaration": "def enhanced_interpolation_search(array... | [
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 fallback_binary_search(array, search_key, low, high):\n while low <= high:\n mid = (low + high) // 2\n if array[mid] == search_key:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019133",
"row_id": 19133,
"seed_ids": "[192]"
} | 0.483976 | Data_Structure_19133 | I | [
"fallback_binary_search",
"enhanced_interpolation_search"
] | 2 | [
[
"enhanced_interpolation_search",
"fallback_binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dfa97c9cc2eb7d42b7acb566055d1b3d30a4e0d8 | 1c703e369c4eb6d5dcfd7f356e5ece80a2be67c6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19184_I | ### Problem: Optimize Fibonacci Calculation
You are given three methods to compute the n-th Fibonacci number: recursive, list-based dynamic programming, and iterative. Each method has different performance characteristics. Your task is to combine these methods into a hybrid solution that intelligently chooses the best... | def fib_recursive(n):
if n <= 1:
return n
return fib_recursive(n-1) + fib_recursive(n-2)
def fib_dynamic(n):
if n == 0:
return 0
fib_list = [0, 1]
for i in range(2, n + 1):
fib_list.append(fib_list[-1] + fib_list[-2])
return fib_list[n]
def fib_iterative(n):
if n ==... | import pytest
from solution import fib_hybrid
def test_fib_recursive():
for i in range(10):
assert fib_hybrid(i) == fib_recursive(i)
def test_fib_dynamic():
for i in range(10, 51):
assert fib_hybrid(i) == fib_dynamic(i)
def test_fib_iterative():
large_values = [51, 100, 500, 1000, 5000, 1... | [
{
"docstring": null,
"function_declaration": "def fib_recursive(n):",
"function_name": "fib_recursive",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def fib_dynamic(n):",
"function_name": "fib_dynamic",
"parameter_list": "(n)"
},
{
"docstring":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fib_recursive(n):\n if n <= 1:\n return n\n return fib_recursive(n-1) + fib_recursive(n-2)\n\ndef fib_dynamic(n):\n if n == 0:\n re... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019184",
"row_id": 19184,
"seed_ids": "[37]"
} | 0.725726 | Data_Structure_19184 | I | [
"fib_recursive",
"fib_dynamic",
"fib_iterative",
"fib_hybrid"
] | 4 | [
[
"fib_hybrid",
"fib_dynamic"
],
[
"fib_hybrid",
"fib_iterative"
],
[
"fib_hybrid",
"fib_recursive"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 36feaa147e46c3919c9b4aeec6a1176ccf2c0191 | bdc6d42a235eb0660ed9633f117ebce259546b34 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19193_I | ### Key Exchange with Enhanced Security
Alice and Bob want to share a secret key through an insecure channel by leveraging the Diffie-Hellman key exchange method. Implement a function `secure_diffie_hellman(p, a)` that verifies if the given `p` is a prime and `a` is a primitive root of `p` before performing the key ex... | import random
from sympy import isprime, primerange
def is_primitive_root(a, p):
"""
Check if a is a primitive root of prime p or not.
"""
if not isprime(p):
return False
required_set = set(num for num in range(1, p))
actual_set = {pow(a, d, p) for d in range(1, p)}
return requir... | from solution import secure_diffie_hellman # Ensure to name your file appropriately or adjust the import here
def test_valid_prime_and_primitive_root():
p = 23
a = 5
assert secure_diffie_hellman(p, a) == True
def test_invalid_prime():
p = 24
a = 5
assert secure_diffie_hellman(p, a) == None
d... | [
{
"docstring": "Check if a is a primitive root of prime p or not.",
"function_declaration": "def is_primitive_root(a, p):",
"function_name": "is_primitive_root",
"parameter_list": "(a, p)"
},
{
"docstring": null,
"function_declaration": "def secure_diffie_hellman(p, a):",
"function_n... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019193",
"row_id": 19193,
"seed_ids": "[146]"
} | 0.426097 | Data_Structure_19193 | I | [
"is_primitive_root",
"secure_diffie_hellman"
] | 2 | [
[
"secure_diffie_hellman",
"is_primitive_root"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | d09cf0acb6bc7a85d13325400cf59d28099f639a | fa174b427819ad0c63d405c3d0a2c525f6e55656 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19217_I | #### Scenario
Suppose you have been given a dataset of integer values representing ages of people in a population. The ages are in the range [0, 100). Due to some analysis needs, you are required to sort these ages using a custom bucket sort algorithm. Each bucket will contain ages within a certain range, and you will ... | from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def custom_bucket_sort(ages: List[int], buc... | from solution import custom_bucket_sort
def test_custom_bucket_sort_example():
assert custom_bucket_sort([23, 45, 22, 18, 35, 13, 67], 10) == [13, 18, 22, 23, 35, 45, 67]
def test_custom_bucket_sort_empty():
assert custom_bucket_sort([], 10) == []
def test_custom_bucket_sort_single_element():
assert cust... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def custom_bucket_sort(ages, buckets_range):",
"function_name": "custom_bucket_sort",
"parameter_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(bucket: List[int]) -> List[int]:\n \"\"\"\n Perform insertion sort on the given bucket.\n \"\"\"\n f... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019217",
"row_id": 19217,
"seed_ids": "[26]"
} | 0.548297 | Data_Structure_19217 | I | [
"insertion_sort",
"custom_bucket_sort"
] | 2 | [
[
"custom_bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 57a183e45615fd6524395266a3a1f0eb81963417 | 9e183f4289c76bdd70e30108235f2467f07780e8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19218_I | ### Scenario:
You have recently taken a class where various sorting algorithms were discussed. One of the algorithms discussed was Bogo Sort, a highly inefficient and academic sorting method. To illustrate its inefficiency, you are to implement this algorithm but also create a function to estimate the probability distr... | 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_simulation(arr, max_shuffles, simulation=False):
"""
Attempts to sort an array using t... | from solution import bogo_sort_simulation
def test_bogo_sort_empty_list():
assert bogo_sort_simulation([], 100) == ([], 0, True)
def test_bogo_sort_single_element():
assert bogo_sort_simulation([1], 100) == ([1], 0, True)
def test_bogo_sort_already_sorted():
assert bogo_sort_simulation([1, 2, 3], 100) ==... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Attempts to sort an array using the bogo sort algorithm.\n\nParameters:\narr (list): The list of number... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n for i in range(len(arr) - 1):\n if arr[i] > arr[i + 1]:\n return False\n return True\n\ndef bog... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019218",
"row_id": 19218,
"seed_ids": "[16]"
} | 0.607461 | Data_Structure_19218 | I | [
"is_sorted",
"bogo_sort_simulation"
] | 2 | [
[
"bogo_sort_simulation",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a36978965d6ac65656ee68d89460c68b4773302d | 56bd1d48b48225e5bf201d4d680baadeaca60baf | |||
v1.0 | instruct | Data_Structure | Data_Structure_19221_I | ### Question Statement
You are working on a large data processing application that needs to frequently sort datasets of varying sizes. To ensure robust and efficient sorting, you will implement a classic sorting algorithm known as Merge Sort.
### Task
Write a function `merge_sort(arr)` that takes a list of integers `... | def merge_sort(arr):
"""
Sorts the array using the merge sort algorithm.
Parameters:
arr (list): List of integers to be sorted.
Returns:
list: New list with elements sorted in non-decreasing order.
"""
# Base case: if the list is empty or has one element, return it
if len(a... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_list():
assert merg... | [
{
"docstring": "Sorts the array using the merge sort algorithm.\n\nParameters:\narr (list): List of integers to be sorted.\n\nReturns:\nlist: New list with elements sorted in non-decreasing order.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(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 merge_sort(arr):\n \"\"\"\n Performs the merge sort on the input list and returns a sorted list.\n \n :param arr: list of integers to be sorte... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019221",
"row_id": 19221,
"seed_ids": "[12]"
} | 0.664915 | Data_Structure_19221 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8f6a559c54cd54f5a06ef4b1c9813330742ae0b2 | d6ca270855fe0ccc129e7255ff580860ccf85724 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19298_I | ### Context
A company uses a road network to transport goods between warehouses and retail stores. The network is modeled as a directed graph where nodes represent warehouses and stores, while edges represent roads with specific capacities. Your task is to compute the maximum transportation capacity (maximum flow) from... | from collections import deque
def dinic_bfs(capacity, flow, level, source, sink):
vertices = len(capacity)
queue = deque([source])
level[source] = 0
while queue:
front = queue.popleft()
for nxt in range(vertices):
if level[nxt] == -1 and flow[front][nxt] < capacity[front][nx... | def test_simple_case():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert max_flow(capacity, source, sink) == 23
def test_no_flow():
... | [
{
"docstring": null,
"function_declaration": "def dinic_bfs(capacity, flow, level, source, sink):",
"function_name": "dinic_bfs",
"parameter_list": "(capacity, flow, level, source, sink)"
},
{
"docstring": null,
"function_declaration": "def dinic_dfs(capacity, flow, level, idx, sink, ptr... | [
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 queue import Queue\n\ndef dinic_bfs(capacity, flow, level, source, sink):\n vertices = len(capacity)\n queue = Queue()\n queue.put(source)\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019298",
"row_id": 19298,
"seed_ids": "[240]"
} | 0.607002 | Data_Structure_19298 | I | [
"dinic_bfs",
"dinic_dfs",
"max_flow"
] | 3 | [
[
"max_flow",
"dinic_bfs"
],
[
"max_flow",
"dinic_dfs"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 926fb5e75a56a7fc1800fefa83c0ad59dfc3779f | fabe7860e6370815db997dec587436dca16355f4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19355_I | ### GCD, LCM, and Trailing Zeros Analysis and Implementation
#### Scenario:
You are tasked with developing a basic math utility library for a software application. Your utility should be able to compute the Greatest Common Divisor (GCD), the Lowest Common Multiple (LCM) of two integers, and determine the number of tra... | def gcd(a: int, b: int) -> int:
"""
Compute the Greatest Common Divisor (GCD) of two numbers using Euclid's Algorithm.
"""
while b:
a, b = b, a % b
return a
def lcm(a: int, b: int) -> int:
"""
Compute the Lowest Common Multiple (LCM) of two numbers.
"""
if a == 0 or b == 0:
... | from solution import gcd, lcm, trailing_zero
# Tests for GCD function
def test_gcd_simple():
assert gcd(54, 24) == 6
assert gcd(48, 18) == 6
def test_gcd_edge_cases():
assert gcd(0, 5) == 5
assert gcd(5, 0) == 5
assert gcd(0, 0) == 0
assert gcd(7, 1) == 1
assert gcd(1, 7) == 1
def test_gc... | [
{
"docstring": "Compute the Greatest Common Divisor (GCD) of two numbers using Euclid's Algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Compute the Lowest Common Multiple (LCM) of two numbers.",
"function_declar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a: int, b: int) -> int:\n \"\"\"\n Computes the Greatest Common Divisor (GCD) of two integers using Euclid's Algorithm.\n \"\"\"\n while b... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019355",
"row_id": 19355,
"seed_ids": "[166]"
} | 0.603783 | Data_Structure_19355 | I | [
"gcd",
"lcm",
"trailing_zero"
] | 3 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e923cbac0a1d462d5fbb08dbcf7fcbc2eae0a6f5 | ee97c9f614a8de4bf52bd8b42740ba15a1793b4e | |||
v1.0 | instruct | Data_Structure | Data_Structure_19363_I | You are given a set of labeled vectors (training set) and an unknown vector for which you need to determine the label using the Nearest Neighbor Algorithm.
**Functional Requirements**:
- Implement a function `nearest_neighbor_classification(x, tSet)` where:
- `x`: A tuple of numerical values representing a vector.
... | import math
def euclidean_distance(v1, v2):
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def nearest_neighbor_classification(x, tSet):
"""
Returns the label of the nearest training vector to x using Euclidean distance.
Parameters:
x (tuple): A numeric tuple representing the vec... | from solution import nearest_neighbor_classification
def test_nearest_neighbor_classification_standard():
x = (1.0, 2.0)
tSet = {
(1.1, 2.1): 'A',
(1.2, 3.1): 'B',
(0.9, 1.9): 'C'
}
assert nearest_neighbor_classification(x, tSet) == 'C'
def test_nearest_neighbor_classification_... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(v1, v2):",
"function_name": "euclidean_distance",
"parameter_list": "(v1, v2)"
},
{
"docstring": "Returns the label of the nearest training vector to x using Euclidean distance.\n\nParameters:\nx (tuple): A numeric tuple re... | [
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 euclidean_distance(v1: Tuple[float, ...], v2: Tuple[float, ...]) -> float:\n return math.sqrt(sum((... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019363",
"row_id": 19363,
"seed_ids": "[260]"
} | 0.602002 | Data_Structure_19363 | I | [
"euclidean_distance",
"nearest_neighbor_classification"
] | 2 | [
[
"nearest_neighbor_classification",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2da7774ad45058b2fba00c5cdc2cb324f8703526 | 4e3f500077e7fa6f5700ca3cd84d2339892c021f | |||
v1.0 | instruct | Data_Structure | Data_Structure_19369_I | You are tasked with creating a function to rotate a 2D matrix 180 degrees utilizing two intermediate 90-degree rotations performed in succession.
### Function Signature
```python
def rotate_180(matrix: List[List[int]]) -> List[List[int]]:
pass
```
### Input
* **`matrix`**: A list of lists where each sublist rep... | from typing import List
def rotate_90(matrix: List[List[int]]) -> List[List[int]]:
"""Rotate the matrix 90 degrees clockwise"""
# Transpose the matrix and then reverse each row
return [list(reversed(col)) for col in zip(*matrix)]
def rotate_180(matrix: List[List[int]]) -> List[List[int]]:
"""Rotate th... | import pytest
from solution import rotate_180
def test_rotate_180_3x3():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
expected = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
assert rotate_180(matrix) == expected
def test_rotate_180_2x2():
matrix = [
... | [
{
"docstring": "Rotate the matrix 90 degrees clockwise",
"function_declaration": "def rotate_90(matrix):",
"function_name": "rotate_90",
"parameter_list": "(matrix)"
},
{
"docstring": "Rotate the matrix 180 degrees",
"function_declaration": "def rotate_180(matrix):",
"function_name":... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rotate_180(matrix: List[List[int]]) -> List[List[int]]:\n def rotate_90(matrix: List[List[int]]) -> List[List[int]]:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019369",
"row_id": 19369,
"seed_ids": "[337]"
} | 0.550592 | Data_Structure_19369 | I | [
"rotate_90",
"rotate_180"
] | 2 | [
[
"rotate_180",
"rotate_90"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dd40752dc94374aeebe03577041369e2eb85aa58 | 244156eb8f59e9e1ed7c6d83ae0667344c07b395 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19437_I | ### Heap Sort Toggle Implementation
**Objective**: Write a function `toggle_heap_sort` that can switch between using a max-heap and min-heap for sorting an array.
**Context**: You are given the tasks to sort an array using Heap Sort, and depending on user preference, you need to choose between Max-Heap and Min-Heap s... | def max_heapify(arr, n, i, 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], arr[i]
... | from solution import toggle_heap_sort
def test_toggle_heap_sort_max_heap():
assert toggle_heap_sort([4, 10, 3, 5, 1], use_max_heap=True) == [1, 3, 4, 5, 10]
def test_toggle_heap_sort_min_heap():
assert toggle_heap_sort([4, 10, 3, 5, 1], use_max_heap=False) == [1, 3, 4, 5, 10]
def test_toggle_heap_sort_single... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, simulation):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, simulation)"
},
{
"docstring": null,
"function_declaration": "def min_heapify(arr, n, i, simulation):",
"function_name": "min_heapify... | [
0,
0,
0,
0,
0,
1,
0,
1,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def heapify(arr, n, i, use_max_heap=True, simulation=False):\n if use_max_heap:\n largest = i # Initialize largest as root for max-heap\n lef... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00019437",
"row_id": 19437,
"seed_ids": "[8]"
} | 0.690232 | Data_Structure_19437 | I | [
"max_heapify",
"min_heapify",
"heap_sort",
"toggle_heap_sort"
] | 4 | [
[
"heap_sort",
"max_heapify"
],
[
"heap_sort",
"min_heapify"
],
[
"toggle_heap_sort",
"heap_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | c3490d225683cfeb0d024d636f1a1f5d14385236 | df810af9509126c0bd4e8ddb37e4c9aeb505f4a0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19443_I | Write a function, `optimized_comb_sort`, that sorts an array of integers using an optimized version of the Comb Sort algorithm. The optimization should involve using a different shrink factor and handling small arrays more efficiently.
### Input:
- An array of integers `arr` of length `n`.
### Output:
- The function ... | def insertion_sort(arr):
"""
A utility function to perform insertion sort on the input array.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def optimized_comb_sor... | from solution import optimized_comb_sort
def test_empty_array():
assert optimized_comb_sort([]) == []
def test_single_element_array():
assert optimized_comb_sort([1]) == [1]
def test_sorted_array():
assert optimized_comb_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_array():
assert optim... | [
{
"docstring": "A utility function to perform insertion sort on the input array.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts an array of integers using an optimized version of the Comb Sort algori... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insertion_sort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while j >= 0 and arr[j] > key:\n arr[j... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019443",
"row_id": 19443,
"seed_ids": "[21]"
} | 0.63295 | Data_Structure_19443 | I | [
"insertion_sort",
"optimized_comb_sort"
] | 2 | [
[
"optimized_comb_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5b0316c337c4d09fda5ba15d234d83baa528c57c | ff0865624ff11b4c86392d729914e9b602867c71 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19475_I | ### Radix Sort Implementation and Stress Test
#### Objective:
Write a function to implement radix sort and apply it to sort a list of non-negative integers. Additionally, enhance the algorithm to handle a large dataset efficiently and ensure it performs within acceptable limits.
#### Function Signature:
```python
def... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
for i... | from solution import radix_sort
def test_radix_sort_example_case():
arr = [170, 45, 75, 90, 802, 24, 2, 66]
sorted_arr = [2, 24, 45, 66, 75, 90, 170, 802]
assert radix_sort(arr) == sorted_arr
def test_radix_sort_with_duplicates():
arr = [3, 6, 3, 1, 9, 6, 3, 2]
sorted_arr = [1, 2, 3, 3, 3, 6, 6, 9... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort... | [
1,
0,
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 counting_sort(arr: List[int], exp: int, simulation: bool) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019475",
"row_id": 19475,
"seed_ids": "[15]"
} | 0.610393 | Data_Structure_19475 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4e19f60a39b21a67f8b0cbe4cb3cd448239ab317 | 29f0b0e7438bd8bc3dbce833f2b55f690fd7e080 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19480_I | ## Problem Statement
Implement an enhanced bucket sort that optimizes performance for various data distributions. Instead of using fixed bucket sizes, dynamically size each bucket to balance the load more effectively. Use merge sort within each bucket for improved efficiency.
### Function Signature
```python
def adva... | from typing import List
def merge_sort(arr: List[float]) -> List[float]:
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i]... | from solution import advanced_bucket_sort
def test_empty_list():
assert advanced_bucket_sort([]) == []
def test_single_element_list():
assert advanced_bucket_sort([0.42]) == [0.42]
def test_uniformly_distributed_list():
arr = [0.78, 0.32, 0.54, 0.01, 0.95, 0.12]
assert advanced_bucket_sort(arr) == [0... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def advanced_bucket_sort(arr):",
"function_name": "advanced_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\n\ndef merge_sort(arr: List[float]) -> List[float]:\n if len(arr) <= 1:\n return arr\n\n def merge(left: List[float], rig... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019480",
"row_id": 19480,
"seed_ids": "[26]"
} | 0.547357 | Data_Structure_19480 | I | [
"merge_sort",
"advanced_bucket_sort"
] | 2 | [
[
"advanced_bucket_sort",
"merge_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b414b5a35c8e0e48b3c424b1662e38125d6cb79c | 252d884f3a1bf92570fbc25812ae37c984f89248 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19512_I | ### Question: Implement Bucket Sort with Improved Secondary Sorting
#### Context
You are working as a software engineer at a company that deals with large datasets. The datasets contain numerical information which needs to be sorted efficiently. Bucket Sort is one of the algorithms you consider due to its efficiency w... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left: List[int], right: List[int]) -> List[int]:
result = []
i = j = ... | from solution import bucket_sort
def test_empty_array():
assert bucket_sort([]) == []
def test_single_element():
assert bucket_sort([5]) == [5]
def test_sorted_array():
assert bucket_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert bucket_sort([5, 4, 3, 2, 1]) == [1, ... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
},
{
"docst... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from 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 = ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019512",
"row_id": 19512,
"seed_ids": "[26]"
} | 0.531818 | Data_Structure_19512 | I | [
"merge_sort",
"merge",
"bucket_sort"
] | 3 | [
[
"bucket_sort",
"merge_sort"
],
[
"merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d8bd633a20ee1378aefe9d1898805bbb4787e184 | 206364b025d3722c8ab87cc0b0de653b42f1956d | |||
v1.0 | instruct | Data_Structure | Data_Structure_19525_I | ## Coding Task: Enhanced RSA Key Generation with Optimized Primality Test
### Objective
Implement an optimized RSA key generation function with improved primality testing using the Miller-Rabin algorithm.
### Scenario
The current `generate_key` function can be time-consuming due to inefficient primality testing. To e... | import random
def is_prime(n, k=40):
""" Return True if n is a probable prime using the Miller-Rabin test. """
if n in (2, 3):
return True
if n % 2 == 0 or n == 1:
return False
# Write (n - 1) as 2^r * d
r, d = 0, n - 1
while d % 2 == 0:
r += 1
d //= 2
... | from solution import generate_key, is_prime
def test_is_prime_small_primes():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(5) == True
assert is_prime(7) == True
def test_is_prime_small_non_primes():
assert is_prime(1) == False
assert is_prime(4) == False
assert is_... | [
{
"docstring": "Return True if n is a probable prime using the Miller-Rabin test. ",
"function_declaration": "def is_prime(n, k=40):",
"function_name": "is_prime",
"parameter_list": "(n, k=40)"
},
{
"docstring": "Generate an odd integer randomly ",
"function_declaration": "def generate_p... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef miller_rabin_primality_test(n, k=40):\n # Helper function to perform the Miller-Rabin primality test\n if n == 2 or n == 3:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019525",
"row_id": 19525,
"seed_ids": "[154]"
} | 0.593321 | Data_Structure_19525 | I | [
"is_prime",
"generate_prime_candidate",
"generate_prime_number",
"gcd",
"modinv",
"generate_key"
] | 6 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"generate_prime_number"
],
[
"generate_key",
"modinv"
],
[
"generate_prime_number",
"generate_prime_candidate"
],
[
"generate_prime_number",
"is_prime"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 7b9d5f5cb8f3026ce75037b59d81dd62eb866bb2 | 44c7a5fceb89605f4922ef195e8546733a76e5ad | |||
v1.0 | instruct | Data_Structure | Data_Structure_19609_I | ### RSA Encryption Challenge
You are required to implement an RSA encryption and decryption system. The task involves generating RSA keys, encrypting a message, and decrypting it back to the original message using the provided keys.
#### Function Signature
```python
def generate_key(k: int) -> Tuple[int, int, int]:
... | import random
from typing import Tuple
from sympy import isprime
from sympy.ntheory.generate import nextprime
def generate_key(k: int) -> Tuple[int, int, int]:
"""
Generate RSA keys of bit length k.
"""
assert k > 1, "Key length k should be greater than 1."
# Generate two large random prime nu... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert n > 0
assert e > 0
assert d > 0
def test_encrypt_decrypt():
n, e, d = generate_key(16)
data =... | [
{
"docstring": "Generate RSA keys of bit length k.",
"function_declaration": "def generate_key(k):",
"function_name": "generate_key",
"parameter_list": "(k)"
},
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\nfrom typing import Tuple\n\ndef generate_prime_candidate(length):\n \"\"\"\n Generate an odd inte... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019609",
"row_id": 19609,
"seed_ids": "[154]"
} | 0.658097 | Data_Structure_19609 | I | [
"generate_key",
"gcd",
"modinv",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"modinv"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | fa24b0ec673494720bf72bacb010fc17a136277c | e10360a9a73ecf113f588314390ba8adece8c6dc | |||
v1.0 | instruct | Data_Structure | Data_Structure_19626_I | ### Question: Implement and Extend a Markov Chain
Given the partial implementation of a Markov Chain, complete the following tasks:
1. **`simulate_chain` Function**:
Write a function `simulate_chain` that simulates the Markov Chain for a given number of steps and returns the sequence of states.
```python
de... | import random
def next_state(chain, current_state):
"""
Given a Markov-Chain, randomly chooses the next state given the current state.
Handles edge cases where the current state has no defined transitions.
Parameters:
chain (dict): The Markov Chain represented as a dictionary.
cur... | from solution import next_state, simulate_chain
def test_next_state_valid_transitions():
chain = {
'A': {'B': 0.5, 'C': 0.5},
'B': {'A': 1.0},
'C': {'C': 1.0}
}
assert next_state(chain, 'A') in ['B', 'C']
assert next_state(chain, 'B') == 'A'
assert next_state(chain, 'C') == ... | [
{
"docstring": "Given a Markov-Chain, randomly chooses the next state given the current state.\n\nHandles edge cases where the current state has no defined transitions.\n\nParameters:\n chain (dict): The Markov Chain represented as a dictionary.\n current_state (str): The current state.\n\nReturns:\n s... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef __choose_state(next_state_map):\n \"\"\"\n Chooses a state based on the transition probabilities.\n \n Parameters:\n n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019626",
"row_id": 19626,
"seed_ids": "[232]"
} | 0.508193 | Data_Structure_19626 | I | [
"next_state",
"__choose_state",
"simulate_chain"
] | 3 | [
[
"next_state",
"__choose_state"
],
[
"simulate_chain",
"next_state"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | dc6c6031ba9e66e7fb57ac05227784f2ff770e22 | 905d551e91df03cbe50af67f0ae892793ce728f5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19674_I | You have been provided with a function that approximates the square root of a positive integer \( N \) using the Babylonian method. Your task is to extend this function to handle a list of numbers and return their respective square root approximations, each with a maximum absolute error \( \epsilon \).
### Requirement... | def babylonian_sqrt(N, epsilon=0.001):
guess = N / 2.0
while True:
next_guess = (guess + N / guess) / 2.0
if abs(next_guess - guess) < epsilon:
return next_guess
guess = next_guess
def batch_square_root(numbers, epsilon=0.001):
return [babylonian_sqrt(num, epsilon) for n... | from solution import batch_square_root, babylonian_sqrt
def test_single_number():
result = batch_square_root([4])
assert len(result) == 1
assert abs(result[0] - 2.0) < 0.001
def test_multiple_numbers():
result = batch_square_root([4, 16, 25, 100])
expected_results = [2.0, 4.0, 5.0, 10.0]
for r... | [
{
"docstring": null,
"function_declaration": "def babylonian_sqrt(N, epsilon=0.001):",
"function_name": "babylonian_sqrt",
"parameter_list": "(N, epsilon=0.001)"
},
{
"docstring": null,
"function_declaration": "def batch_square_root(numbers, epsilon=0.001):",
"function_name": "batch_... | [
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 approximate_square_root(n: int, epsilon: float) -> float:\n \"\"\"\n Approximates the square root of a positive integer n using the Babylonian metho... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019674",
"row_id": 19674,
"seed_ids": "[138]"
} | 0.71984 | Data_Structure_19674 | I | [
"babylonian_sqrt",
"batch_square_root"
] | 2 | [
[
"batch_square_root",
"babylonian_sqrt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 72691b3a7e7fbbf0bea55481eb4f709b8863a9c8 | 37e2bb3e054fe46c6bcdad4892d07ac8428152cc | |||
v1.0 | instruct | Data_Structure | Data_Structure_19710_I | You are required to write a function that converts an integer to bytes representation in both big-endian and little-endian formats, and vice versa. Then you must verify that converting from integer to bytes and back to integers yields the original value in both endian formats.
**Objective**: Demonstrate an understandi... | from collections import deque
def int_to_bytes_big_endian(num: int) -> bytes:
"""
Converts an integer to its byte representation in big-endian format.
"""
if num == 0:
return b'\x00'
result = deque()
while num:
result.appendleft(num & 0xff)
num >>= 8
return bytes(res... | def test_int_to_bytes_big_endian():
assert int_to_bytes_big_endian(305419896) == b'\x12\x34\x56\x78'
assert int_to_bytes_big_endian(0) == b'\x00'
assert int_to_bytes_big_endian(255) == b'\xff'
assert int_to_bytes_big_endian(256) == b'\x01\x00'
def test_int_to_bytes_little_endian():
assert int_to_by... | [
{
"docstring": "Converts an integer to its byte representation in big-endian format.",
"function_declaration": "def int_to_bytes_big_endian(num):",
"function_name": "int_to_bytes_big_endian",
"parameter_list": "(num)"
},
{
"docstring": "Converts an integer to its byte representation in littl... | [
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 int_to_bytes_big_endian(num: int) -> bytes:\n \"\"\"\n Convert an integer to bytes using big-endian format.\n \"\"\"\n if num == 0:\n r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019710",
"row_id": 19710,
"seed_ids": "[216]"
} | 0.546503 | Data_Structure_19710 | I | [
"int_to_bytes_big_endian",
"int_to_bytes_little_endian",
"bytes_big_endian_to_int",
"bytes_little_endian_to_int",
"verify_conversion"
] | 5 | [
[
"verify_conversion",
"bytes_big_endian_to_int"
],
[
"verify_conversion",
"bytes_little_endian_to_int"
],
[
"verify_conversion",
"int_to_bytes_big_endian"
],
[
"verify_conversion",
"int_to_bytes_little_endian"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | d371dd0d07e62ddeb59d1d15943e354d7511a854 | 822055c49ab841824f3ebc9b019ef1d57092c9ee | |||
v1.0 | instruct | Data_Structure | Data_Structure_19862_I | ### Gnome Sorting Challenge
You have been hired as a software engineer to help improve and implement robust functionalities in sorting arrays. One of the tasks is to implement the Gnome Sort algorithm and then optimize it. Implement the Gnome Sort algorithm adhering to the typical operations as specified. Furthermore,... | from typing import List
def gnome_sort(arr: List[int]) -> List[int]:
n = len(arr)
pos = 0
while pos < n:
if pos == 0 or arr[pos] >= arr[pos - 1]:
pos += 1
else:
arr[pos], arr[pos - 1] = arr[pos - 1], arr[pos]
pos -= 1
return arr
def optimized_gnome_s... | from solution import optimized_gnome_sort
def test_optimized_gnome_sort_small_array():
assert optimized_gnome_sort([34, 2, 10, -9]) == [-9, 2, 10, 34]
assert optimized_gnome_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
assert optimized_gnome_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
assert optimized_gnome_s... | [
{
"docstring": null,
"function_declaration": "def gnome_sort(arr):",
"function_name": "gnome_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def optimized_gnome_sort(arr, threshold=20):",
"function_name": "optimized_gnome_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 gnome_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Gnome Sort algorithm implementation for small datasets.\n \"\"\"\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019862",
"row_id": 19862,
"seed_ids": "[13]"
} | 0.605141 | Data_Structure_19862 | I | [
"gnome_sort",
"optimized_gnome_sort"
] | 2 | [
[
"optimized_gnome_sort",
"gnome_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e23e6723e4b2938b885b0d2adc3f5957b88c9a23 | 2de931c1fb62bce6f622baeee1a5a4656d218820 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19870_I | **Question: Efficiently Sort and Remove Duplicates**
You work for a software firm where it's common to handle large lists of unsorted numbers. Often, you need to sort these lists and remove any duplicate entries. As the datasets can get quite large, a bubble sort is inefficient. Instead, you decide to use a comb sort ... | def comb_sort(arr):
"""
Function to perform comb sort on the provided array.
"""
gap = len(arr)
shrink = 1.3
sorted = False
while not sorted:
gap = int(gap / shrink)
if gap <= 1:
gap = 1
sorted = True
i = 0
while i + gap < len... | from solution import comb_sort, sort_and_remove_duplicates
def test_comb_sort_unsorted():
assert comb_sort([4, 6, 2, 4, 3, 2, 1]) == [1, 2, 2, 3, 4, 4, 6]
def test_comb_sort_sorted():
assert comb_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_comb_sort_reverse_sorted():
assert comb_sort([5, 4, 3, 2, 1... | [
{
"docstring": "Function to perform comb sort on the provided array.",
"function_declaration": "def comb_sort(arr):",
"function_name": "comb_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Function to sort the array in ascending order and remove duplicates.",
"function_declaration": ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sort_and_remove_duplicates(arr):\n \"\"\"\n Sorts the given list arr of integers in ascending order and removes any duplicates.\n \"\"\"\n def... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019870",
"row_id": 19870,
"seed_ids": "[21]"
} | 0.63118 | Data_Structure_19870 | I | [
"comb_sort",
"sort_and_remove_duplicates"
] | 2 | [
[
"sort_and_remove_duplicates",
"comb_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f399e0b0a1422b7f829bdf4f4232adbc2d479d1c | c20982c6effd28fc3be49dfc7f0e2370746386f9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19888_I | ### Hailstone Problem
Consider the following Hailstone sequence generation process:
1. Start with any positive integer `n`.
2. If `n` is 1, stop the process.
3. If `n` is even, the next number in the sequence is `n/2`.
4. If `n` is odd, the next number in the sequence is `3n + 1`.
5. Repeat the process until `n` becom... | def hailstone_sequence(n: int) -> list:
"""
Generates the Hailstone sequence starting from integer n.
"""
sequence = []
while n != 1:
sequence.append(n)
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
sequence.append(1)
return sequence
def longe... | from solution import hailstone_sequence, longest_hailstone_sequence
def test_hailstone_sequence():
assert hailstone_sequence(1) == [1]
assert hailstone_sequence(2) == [2, 1]
assert hailstone_sequence(3) == [3, 10, 5, 16, 8, 4, 2, 1]
assert hailstone_sequence(5) == [5, 16, 8, 4, 2, 1]
def test_longest_... | [
{
"docstring": "Generates the Hailstone sequence starting from integer n.",
"function_declaration": "def hailstone_sequence(n):",
"function_name": "hailstone_sequence",
"parameter_list": "(n)"
},
{
"docstring": "Finds the starting number (1 ≤ n ≤ m) which produces the longest Hailstone seque... | [
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 hailstone_sequence(n):\n \"\"\"\n Generates the Hailstone sequence for a given starting number n.\n \"\"\"\n sequence = []\n while n != 1:\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019888",
"row_id": 19888,
"seed_ids": "[167]"
} | 0.585128 | Data_Structure_19888 | I | [
"hailstone_sequence",
"longest_hailstone_sequence"
] | 2 | [
[
"longest_hailstone_sequence",
"hailstone_sequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aebbd2e203dfd48e170732b96f008a246ec5cbec | e4d824810dbf2d66753a94e7621ea317d805a851 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19891_I | ### Question: Implement and Enhance Radix Sort to Handle Negative Numbers
You are tasked with implementing an enhanced version of the Radix Sort algorithm provided. The provided Radix Sort implementation sorts lists of non-negative integers. Extend this functionality to handle lists that include both non-negative and ... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool):
n = len(arr)
output = [0] * n
count = [0] * 10
# Count occurrences of digits
for i in range(n):
index = arr[i] // exp
count[(index % 10)] += 1
# Update count to have position info
for i ... | from solution import enhanced_radix_sort
def test_empty_array():
assert enhanced_radix_sort([]) == []
def test_all_positives():
assert enhanced_radix_sort([3, 1, 4, 1, 5, 9]) == [1, 1, 3, 4, 5, 9]
def test_all_negatives():
assert enhanced_radix_sort([-3, -1, -4, -1, -5, -9]) == [-9, -5, -4, -3, -1, -1]
... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation):",
"function_name": "radix_sort",
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019891",
"row_id": 19891,
"seed_ids": "[15]"
} | 0.629034 | Data_Structure_19891 | I | [
"counting_sort",
"radix_sort",
"enhanced_radix_sort"
] | 3 | [
[
"enhanced_radix_sort",
"radix_sort"
],
[
"radix_sort",
"counting_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | baa7b2ead5cf98dd2f361c1f21b0cef27f964038 | 91460e9312cb51d98e4881d9f2c0845e98faf390 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19948_I | You are given a list of unique words, each of the same length, and your task is to form all possible word squares where each row and each column of the square reads the same word.
A word square is defined as a sequence of words of the same length that forms a valid word square such that the kth row and kth column read... | from typing import List, Dict
from collections import defaultdict
def build_prefix_hash(words: List[str]) -> Dict[str, List[str]]:
"""
Builds a prefix hash map for quick prefix-based lookups.
"""
prefix_dict = defaultdict(list)
for word in words:
for i in range(len(word)):
prefi... | from solution import findWordSquares
def test_example_case():
words = ["area", "lead", "wall", "lady", "ball"]
squares = findWordSquares(words)
expected_squares = [
["wall", "area", "lead", "lady"],
["ball", "area", "lead", "lady"]
]
assert sorted(squares) == sorted(expected_squares... | [
{
"docstring": "Builds a prefix hash map for quick prefix-based lookups.",
"function_declaration": "def build_prefix_hash(words):",
"function_name": "build_prefix_hash",
"parameter_list": "(words)"
},
{
"docstring": null,
"function_declaration": "def findWordSquares(words):",
"functi... | [
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, Dict\nfrom collections import defaultdict\n\ndef build_prefix_hash(words: List[str]) -> Dict[str, List[str]]:\n \"\"\"\n Builds... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019948",
"row_id": 19948,
"seed_ids": "[87]"
} | 0.576885 | Data_Structure_19948 | I | [
"build_prefix_hash",
"findWordSquares"
] | 2 | [
[
"findWordSquares",
"build_prefix_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 50d68ffd9da73bedca234c131970bc6455a04737 | f3299494080523e494587651b05c8c147ab93f41 | |||
v1.0 | instruct | Data_Structure | Data_Structure_19955_I | ### Integer Pair Analysis for GCD and LCM Computation
#### Objective:
Implement functions to analyze pairs of integers by computing the greatest common divisor (GCD) and least common multiple (LCM) both conventionally and using bitwise operations. Additionally, include a feature to count trailing zeros in the binary r... | def compute_gcd(a, b):
"""
Compute the greatest common divisor (GCD) using the Euclidean algorithm.
"""
while b:
a, b = b, a % b
return a
def compute_gcd_bitwise(a, b):
"""
Compute the GCD using bitwise operations.
"""
if a == 0: return b
if b == 0: return a
# Find ... | from solution import compute_gcd, compute_gcd_bitwise, compute_lcm, count_trailing_zeros
def test_compute_gcd():
assert compute_gcd(12, 18) == 6
assert compute_gcd(100, 25) == 25
assert compute_gcd(7, 1) == 1
assert compute_gcd(27, 18) == 9
def test_compute_gcd_bitwise():
assert compute_gcd_bitwis... | [
{
"docstring": "Compute the greatest common divisor (GCD) using the Euclidean algorithm.",
"function_declaration": "def compute_gcd(a, b):",
"function_name": "compute_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Compute the GCD using bitwise operations.",
"function_declaration": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def compute_gcd(a, b):\n \"\"\"\n Compute the greatest common divisor (GCD) using the Euclidean algorithm.\n \"\"\"\n while b:\n a, b = b, ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019955",
"row_id": 19955,
"seed_ids": "[166]"
} | 0.638059 | Data_Structure_19955 | I | [
"compute_gcd",
"compute_gcd_bitwise",
"compute_lcm",
"count_trailing_zeros"
] | 4 | [
[
"compute_lcm",
"compute_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 521a38098e184a229b18134b7aed93b77448dd74 | 67890481322b9fd5cf5eb6f762793dc7baf31626 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20027_I | ### RSA Key Generation and Encryption
**Objective:**
Implement the RSA encryption algorithm by generating the public and private keys, encrypting a given message with the public key, and then decrypting it with the private key.
**Task:**
1. **Key Generation:**
Implement an efficient prime number generation proce... | import random
def gcd(a, b):
while b:
a, b = b, a % b
return a
def multiplicative_inverse(e, phi):
def egcd(a, b):
if a == 0:
return (b, 0, 1)
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
g, x, y = egcd(e, phi)
if g != 1:
raise Except... | from solution import generate_key, encrypt, decrypt
def test_key_generation():
n, e, d = generate_key(16, seed=42)
assert n > 0
assert e > 0
assert d > 0
def test_encryption_decryption():
n, e, d = generate_key(16, seed=42)
data = 12345
encrypted = encrypt(data, e, n)
decrypted = decry... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def multiplicative_inverse(e, phi):",
"function_name": "multiplicative_inverse",
"parameter_list": "(e, phi)"
},
... | [
0,
0,
0,
1,
0,
0,
1,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime\n\ndef generate_key(k: int, seed: int = None) -> tuple:\n if seed is not None:\n random.seed(seed)\n \n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00020027",
"row_id": 20027,
"seed_ids": "[154]"
} | 0.581982 | Data_Structure_20027 | I | [
"gcd",
"multiplicative_inverse",
"is_prime",
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt"
] | 8 | [
[
"generate_key",
"gcd"
],
[
"generate_key",
"generate_prime_number"
],
[
"generate_key",
"multiplicative_inverse"
],
[
"generate_prime_number",
"generate_prime_candidate"
],
[
"generate_prime_number",
"is_prime"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | a33858327db8f6d8c6e1f5a1bdde03076c00c61e | f658d7b672f2ecd7a78845e140c337b96908e97d | |||
v1.0 | instruct | Data_Structure | Data_Structure_20134_I | ### Interpolation Search-Based Range Query
In many applications, such as database indexing, quick range queries over sorted data are often needed. Designing a solution to efficiently determine the range of indices where array elements fall within a specified range can significantly enhance performance.
#### Problem S... | from typing import List, Tuple
def interpolation_search(array: List[int], target: int) -> int:
low = 0
high = len(array) - 1
while low <= high and target >= array[low] and target <= array[high]:
if low == high:
if array[low] == target:
return low
return -1
... | from solution import range_query
def test_range_query_within_bounds():
assert range_query([1, 3, 5, 7, 9, 11, 13, 15], 5, 13) == (2, 6)
def test_range_query_straddle_bounds():
assert range_query([1, 3, 5, 7, 9, 11, 13, 15], 6, 12) == (3, 5)
def test_range_query_no_match():
assert range_query([1, 3, 5, 7,... | [
{
"docstring": null,
"function_declaration": "def interpolation_search(array, target):",
"function_name": "interpolation_search",
"parameter_list": "(array, target)"
},
{
"docstring": null,
"function_declaration": "def find_start_index(array, lower):",
"function_name": "find_start_in... | [
0,
0,
0,
0,
0,
0,
1,
1,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def interpolation_search(array, x):\n low = 0\n high = len(array) - 1\n\n while low <= high and x >= array[low] and x <= array[high]:\n if low... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00020134",
"row_id": 20134,
"seed_ids": "[192]"
} | 0.594119 | Data_Structure_20134 | I | [
"interpolation_search",
"find_start_index",
"find_end_index",
"range_query"
] | 4 | [
[
"find_end_index",
"interpolation_search"
],
[
"find_start_index",
"interpolation_search"
],
[
"range_query",
"find_end_index"
],
[
"range_query",
"find_start_index"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | cccf80aa641bc72e8b2badf34be5ab677d68b1b9 | 9ad123c25e07eebbcf1bc8aea86d7a979b3eb15a | |||
v1.0 | instruct | Data_Structure | Data_Structure_20164_I | Generate Reverse Hailstone Sequence
#### Context
You are given the task to generate a Hailstone sequence starting from a given number `n`, but as an additional challenge, you must generate and return the sequence in reverse order, starting from 1 and ending at `n`. This requires you to first compute the traditional Ha... | def hailstone(n: int) -> list:
sequence = []
while n != 1:
sequence.append(n)
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
sequence.append(1)
return sequence
def reverse_hailstone(n: int) -> list:
sequence = hailstone(n)
return sequence[::-1] | from solution import reverse_hailstone
def test_reverse_hailstone_base_case():
assert reverse_hailstone(1) == [1]
def test_reverse_hailstone_small_number():
assert reverse_hailstone(5) == [1, 2, 4, 8, 16, 5]
def test_reverse_hailstone_large_number():
# Expected sequence for 10: [10, 5, 16, 8, 4, 2, 1]
... | [
{
"docstring": null,
"function_declaration": "def hailstone(n):",
"function_name": "hailstone",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def reverse_hailstone(n):",
"function_name": "reverse_hailstone",
"parameter_list": "(n)"
}
] | [
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def reverse_hailstone(n: int) -> list:\n \"\"\"Generates the reverse Hailstone sequence starting from 1 up to n.\"\"\"\n def hailstone_sequence(n: int) ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00020164",
"row_id": 20164,
"seed_ids": "[167]"
} | 0.630498 | Data_Structure_20164 | I | [
"hailstone",
"reverse_hailstone"
] | 2 | [
[
"reverse_hailstone",
"hailstone"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6d094f3d5cef870aeef1dfb337b4f3e3e52ab101 | 625437fc59df854ebb845c733455553c7dbe7908 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20204_I | ### Question: Implement RSA Encryption and Decryption
You are tasked with implementing a simplified version of the RSA encryption algorithm. The goal is to practice the key aspects of RSA, including key generation, encryption, and decryption. You need to create functions for these tasks based on the detailed algorithm... | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(length):
""" Generate an odd integer randomly """
p = random.getrandbits(length)
# Ensure p is odd
if p % 2 == 0:
p += 1
return p
def generate_prime_number(length):
""" Generate a prime number of length `... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_encrypt_decrypt():
n, e, d = generate_key(16)
data = 42
encrypted = encrypt(data, e, n)
dec... | [
{
"docstring": "Generate an odd integer randomly ",
"function_declaration": "def generate_prime_candidate(length):",
"function_name": "generate_prime_candidate",
"parameter_list": "(length)"
},
{
"docstring": "Generate a prime number of length `length` ",
"function_declaration": "def gen... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime(bits: int, seed: int = None) -> int:\n if seed is not None:\n random.see... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020204",
"row_id": 20204,
"seed_ids": "[154]"
} | 0.555086 | Data_Structure_20204 | I | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 74454c55551121bd4eb87c24f6c6b2f5e4ac5dc8 | aaa0df84010fff2ee94ffa42cc8db7e377705cbc | |||
v1.0 | instruct | Data_Structure | Data_Structure_20316_I | ### Quick Sort Implementation with Median-of-Three Pivot Selection
**Scenario**:
The company you are working for has data analysis software that needs to efficiently sort large datasets. Your manager has noted that the conventional Quick Sort algorithm sometimes performs poorly on nearly sorted data and wants you to i... | def median_of_three(arr, low, high):
mid = (low + high) // 2
if arr[low] > arr[mid]:
arr[low], arr[mid] = arr[mid], arr[low]
if arr[low] > arr[high]:
arr[low], arr[high] = arr[high], arr[low]
if arr[mid] > arr[high]:
arr[mid], arr[high] = arr[high], arr[mid]
return mid
def p... | from solution import optimized_quick_sort
def test_sorted():
assert optimized_quick_sort([1, 2, 3, 4]) == [1, 2, 3, 4]
def test_reverse_sorted():
assert optimized_quick_sort([4, 3, 2, 1]) == [1, 2, 3, 4]
def test_unsorted():
assert optimized_quick_sort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10... | [
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter... | [
1,
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_quick_sort(arr):\n \"\"\"\n Sorts the array `arr` using an optimized quick sort algorithm with median-of-three pivot selection.\n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020316",
"row_id": 20316,
"seed_ids": "[25]"
} | 0.591193 | Data_Structure_20316 | I | [
"median_of_three",
"partition",
"quick_sort_recursive",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"quick_sort_recursive"
],
[
"partition",
"median_of_three"
],
[
"quick_sort_recursive",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 47c36793fe4724753834ca03542a62e9489ab7d5 | 38570231d901144725df20ae717ba617302cf242 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20414_I | #### Context:
You are tasked with implementing an enhanced Insertion Sort algorithm that uses binary search to locate the insertion point efficiently. This should help in reducing the number of comparisons required to find the correct position for each element in the partially sorted array.
#### Problem:
Write a funct... | def search_insert(array, val):
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low
def binary_insertion_sort(array):
for i in range(1, len(array)):
k... | from solution import binary_insertion_sort
def test_empty_array():
array = []
binary_insertion_sort(array)
assert array == []
def test_single_element_array():
array = [1]
binary_insertion_sort(array)
assert array == [1]
def test_sorted_array():
array = [1, 2, 3, 4, 5]
binary_insertion... | [
{
"docstring": null,
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": null,
"function_declaration": "def binary_insertion_sort(array):",
"function_name": "binary_insertion_sort",
"parame... | [
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 low = 0\n high = len(array) - 1\n while low <= high:\n mid = low + (high - low) // 2\n if val > array[... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020414",
"row_id": 20414,
"seed_ids": "[199]"
} | 0.560119 | Data_Structure_20414 | I | [
"search_insert",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 87a60a931fcd0307e54837238143cb9e0a35e300 | a10f3b18e97c8216a2c737b501384d85aebbc76d | |||
v1.0 | instruct | Data_Structure | Data_Structure_20415_I | ### Matrix Inversion Challenge
You are required to implement a function to invert a given square matrix. The function should handle matrices of size n x n and account for various edge cases such as non-invertible matrices.
#### Function Signature
```python
def invert_matrix(m: List[List[float]]) -> List[List[float]]:... | from typing import List
def determinant(matrix: List[List[float]]) -> float:
"""Calculate 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 ... | from solution import invert_matrix
def test_invert_simple_matrix():
assert invert_matrix([[1, 2], [3, 4]]) == [[-2.0, 1.0], [1.5, -0.5]]
def test_invert_singular_matrix():
assert invert_matrix([[0, 0], [0, 0]]) == [-2]
def test_invert_non_square_matrix():
assert invert_matrix([[1, 2, 3], [4, 5, 6]]) == [... | [
{
"docstring": "Calculate the determinant of a square matrix.",
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": "Return the Minor of the matrix excluding the i-th row and j-th column.",
"function_declarati... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef get_minor(matrix: List[List[float]], i: int, j: int) -> List[List[float]]:\n minor = [\n [matrix[x][y] for y in range... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020415",
"row_id": 20415,
"seed_ids": "[347]"
} | 0.606198 | Data_Structure_20415 | I | [
"determinant",
"minor",
"transpose",
"cofactor",
"invert_matrix"
] | 5 | [
[
"cofactor",
"determinant"
],
[
"cofactor",
"minor"
],
[
"determinant",
"minor"
],
[
"invert_matrix",
"cofactor"
],
[
"invert_matrix",
"determinant"
],
[
"invert_matrix",
"transpose"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | abd78d3bc05964fed82b85f2298c5672c293cae0 | 9f4b4fc88487c031081a76049adcd428435b1a19 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20423_I | ### RSA Key Generation, Encryption, and Decryption
As part of your assessments, you need to implement components of the RSA encryption algorithm to measure the understanding of your students. Your task is to complete the implementation of the RSA cryptographic algorithm for secure data transmission.
**Functions to Im... | import random
def find_mod_inverse(a, m):
"""
Find and return the modular inverse of a modulo m.
"""
def egcd(a, b):
if a == 0:
return b, 0, 1
else:
g, x, y = egcd(b % a, a)
return g, y - (b // a) * x, x
g, x, y = egcd(a, m)
if g != 1:
... | import pytest
from solution import find_mod_inverse, is_prime, generate_prime
def test_find_mod_inverse():
assert find_mod_inverse(3, 11) == 4
assert find_mod_inverse(10, 17) == 12
assert find_mod_inverse(2, 5) == 3
with pytest.raises(ValueError):
find_mod_inverse(3, 6) # 3 and 6 are not co-p... | [
{
"docstring": "Find and return the modular inverse of a modulo m.",
"function_declaration": "def find_mod_inverse(a, m):",
"function_name": "find_mod_inverse",
"parameter_list": "(a, m)"
},
{
"docstring": "Determine if the number num is prime.",
"function_declaration": "def is_prime(num... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef find_mod_inverse(a, m):\n \"\"\"\n Find and return the modular inverse of a modulo m.\n \"\"\"\n def egcd(a, b):\n if ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020423",
"row_id": 20423,
"seed_ids": "[154]"
} | 0.615244 | Data_Structure_20423 | I | [
"find_mod_inverse",
"is_prime",
"generate_prime"
] | 3 | [
[
"generate_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 808f736bec7ea3c395e03304285b5859537a3898 | 26acb6c443f7ffdf6e3c1291bb96cd3f53521649 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20459_I | Design a function `secure_key_exchange` that employs Diffie-Hellman key exchange protocol to generate a shared secret key between two parties, Alice and Bob. Your implementation should include all necessary steps from prime validation to the final key exchange.
### Input
- A large prime number `p` (1 < `p` < 10^9)
- ... | def prime_check(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 find_primitive_root(p):
if not prim... | from solution import secure_key_exchange
def test_valid_parameters():
p = 23
a = 5
assert secure_key_exchange(p, a) != "Error: Shared secret key mismatch"
def test_invalid_prime():
p = 22
a = 5
assert secure_key_exchange(p, a) == "Error: 22 is not a prime number"
def test_invalid_primitive_ro... | [
{
"docstring": null,
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def find_primitive_root(p):",
"function_name": "find_primitive_root",
"parameter_list": "(p)"
},
{
... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def prime_check(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020459",
"row_id": 20459,
"seed_ids": "[146]"
} | 0.47439 | Data_Structure_20459 | I | [
"prime_check",
"find_primitive_root",
"secure_key_exchange"
] | 3 | [
[
"find_primitive_root",
"prime_check"
],
[
"secure_key_exchange",
"find_primitive_root"
],
[
"secure_key_exchange",
"prime_check"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | a8dc13bc0c021fa68a0fefff09cde7edc5e488a3 | 11b975c9ccb495f356a6120e71903457f2863ec6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20473_I | ### Palindrome Verification Using Various Techniques
#### Context
You've been hired to develop a reliable system to validate whether given strings are palindromes. Considering potential variations in the input data, such as the presence of non-alphanumeric characters and different cases, the verification should be bot... | import re
from collections import deque
def clean_string(s):
"""
Remove non-alphanumeric characters and convert to lowercase.
"""
return re.sub(r'[^A-Za-z0-9]', '', s).lower()
def advanced_is_palindrome(s: str, method: str) -> bool:
"""
Check if the given string is a palindrome using the speci... | from solution import advanced_is_palindrome
def test_advanced_is_palindrome_reverse():
assert advanced_is_palindrome("A man, a plan, a canal: Panama", "reverse") == True
assert advanced_is_palindrome("race a car", "reverse") == False
assert advanced_is_palindrome(" ", "reverse") == True
assert advanced... | [
{
"docstring": "Remove non-alphanumeric characters and convert to lowercase.",
"function_declaration": "def clean_string(s):",
"function_name": "clean_string",
"parameter_list": "(s)"
},
{
"docstring": "Check if the given string is a palindrome using the specified method.",
"function_dec... | [
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 collections\nimport re\n\ndef advanced_is_palindrome(s: str, method: str) -> bool:\n \"\"\"\n :param s: The input string to check.\n :param me... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020473",
"row_id": 20473,
"seed_ids": "[70]"
} | 0.813333 | Data_Structure_20473 | I | [
"clean_string",
"advanced_is_palindrome"
] | 2 | [
[
"advanced_is_palindrome",
"clean_string"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 50181444534fbd1ad9b95f7198ff7794bb9010df | 87fe3d2468239fc055110647d0d24bfd5fac58a7 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20483_I | ### Nearest Neighbor Classification
In this assessment, you will implement and extend the Nearest Neighbor algorithm based on the provided code snippets. The goal is to classify a given test point by finding its nearest neighbor in a training set of labeled vectors.
### Problem Statement
You are given a training set... | import math
def euclidean_distance(v1, v2):
"""
Computes the Euclidean distance between two vectors
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def nearest_neighbor(x, tSet):
"""
Finds and returns the class label of the nearest neighbor of vector x in the training set tSet.... | from solution import nearest_neighbor
def test_nn_exact_match():
x = (1, 2)
tSet = {
(2, 3): "A",
(4, 5): "B",
(1, 2): "C"
}
assert nearest_neighbor(x, tSet) == "C"
def test_nn_closest_point():
x = (1, 2)
tSet = {
(2, 3): "A",
(4, 5): "B",
(1, 3)... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(x, y):\n \"\"\"\n Computes the Euclidean distance between two vectors x and y.\n \"\"\"\n return math.sqrt(s... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020483",
"row_id": 20483,
"seed_ids": "[260]"
} | 0.641737 | Data_Structure_20483 | I | [
"euclidean_distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c795edfbf99105f233e32ca098586906815983bc | 62908954fb563a9e32ae5ae27ef3f6453d9efc1e | |||
v1.0 | instruct | Data_Structure | Data_Structure_20489_I | You are given a function that implements Pancake Sort, an inefficient but interesting sorting algorithm. Pancake Sort works by flipping subarrays (like flipping segments of a stack of pancakes) to move the maximum unsorted element to its correct position iteratively.
#### Task
Write a function `pancake_sort(arr)` that... | def flip(arr, end):
"""
Helper function to flip the subarray from start to end (inclusive).
"""
start = 0
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
def pancake_sort(arr):
"""
Perform Pancake Sort on the input list `arr`.
"... | from solution import pancake_sort
def test_pancake_sort_basic():
assert pancake_sort([3, 6, 2, 7, 4]) == [2, 3, 4, 6, 7]
def test_pancake_sort_sorted_array():
assert pancake_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_pancake_sort_reverse_sorted_array():
assert pancake_sort([5, 4, 3, 2, 1]) == [1, ... | [
{
"docstring": "Helper function to flip the subarray from start to end (inclusive).",
"function_declaration": "def flip(arr, end):",
"function_name": "flip",
"parameter_list": "(arr, end)"
},
{
"docstring": "Perform Pancake Sort on the input list `arr`.",
"function_declaration": "def pan... | [
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 flip(arr, k):\n \"\"\"\n Helper function to reverse the order of the first k elements in the array.\n \"\"\"\n return arr[:k][::-1] + arr[k:]\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020489",
"row_id": 20489,
"seed_ids": "[9]"
} | 0.790667 | Data_Structure_20489 | I | [
"flip",
"pancake_sort"
] | 2 | [
[
"pancake_sort",
"flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ea4cf9d5907aaf7c3fd897d41039e98d8b591b7d | c8f1401ca7a29a2f3d6418ad6bf140a42681ff66 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20593_I | ### RSA Encryption/Decryption Implementations
#### Background
RSA is one of the first public-key cryptosystems and is widely used for secure data transmission. Unlike symmetric key cryptosystems, RSA relies on a pair of keys:
- A public key (n, e) for encryption.
- A private key (n, d) for decryption.
#### Task
Your ... | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(length):
"""
Generate an odd integer randomly
"""
p = random.getrandbits(length)
# apply a mask to set MSB and LSB to 1
p |= (1 << length - 1) | 1
return p
def generate_prime_number(length):
"""
Gener... | from solution import generate_key_pair, encrypt, decrypt
def test_generate_key_pair():
n, e, d = generate_key_pair(16)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_encrypt_decrypt():
n, e, d = generate_key_pair(32)
data = 42
encrypted = encrypt(dat... | [
{
"docstring": "Generate an odd integer randomly",
"function_declaration": "def generate_prime_candidate(length):",
"function_name": "generate_prime_candidate",
"parameter_list": "(length)"
},
{
"docstring": "Generate a prime",
"function_declaration": "def generate_prime_number(length):"... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\nimport math\n\ndef generate_prime_candidate(length):\n \"\"\" Generate an odd integer randomly \"\"\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020593",
"row_id": 20593,
"seed_ids": "[154]"
} | 0.597051 | Data_Structure_20593 | I | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key_pair",
"encrypt",
"decrypt"
] | 5 | [
[
"generate_key_pair",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 23ee6717a0c25fe23d92ac5c6134abca496cf0a4 | 9824531d4500c826c8886bdb6f19e6c9d402cf72 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20595_I | ### Question: Implement an enhanced Merge Sort
#### Objective
You are given an array of integers and need to sort it in ascending order using the merge sort algorithm. The implementation should consider typical edge cases and aim for minimal auxiliary space usage.
#### Function Signature
```python
def merge_sort(arr:... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts the input list `arr` in ascending order using merge sort algorithm.
"""
if len(arr) <= 1:
return arr
# Split the array into two halves
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half... | 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_two_elements_sorted():
assert merge_sort([1, 2]) == [1, 2]
def test_merge_sort_two_elements_unsorted():
assert merge_s... | [
{
"docstring": "Sorts the input list `arr` in ascending order using merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted sublists (`left` and `right`) into one sorted 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 merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Function to sort an array using the Merge Sort algorithm.\n \"\"\"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020595",
"row_id": 20595,
"seed_ids": "[12]"
} | 0.647595 | Data_Structure_20595 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d81063bf0e6956641df24b3135c7ebe121a4efd6 | d4b8200a221adb8d0e4b13e5f57a46fa1e13c820 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20596_I | Implement a function `improved_sort(arr)` that sorts an array of integers in ascending order. Your task is to enhance the given exchange sort algorithm based on its limitations and performance bottlenecks. You may consider some form of optimization or choose an entirely different sorting algorithm, provided it improves... | from typing import List
def improved_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers in ascending order using the Merge Sort algorithm.
Merge Sort is a divide-and-conquer algorithm that provides an average and worst-case time complexity of O(n log n).
"""
if len(arr) <= 1:
... | from solution import improved_sort
def test_improved_sort_example_1():
assert improved_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
def test_improved_sort_example_2():
assert improved_sort([10, -1, 3, 7, 8]) == [-1, 3, 7, 8, 10]
def test_improved_sort_empty_list():
assert ... | [
{
"docstring": "Sorts an array of integers in ascending order using the Merge Sort algorithm.\n\nMerge Sort is a divide-and-conquer algorithm that provides an average and worst-case time complexity of O(n log n).",
"function_declaration": "def improved_sort(arr):",
"function_name": "improved_sort",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef improved_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of integers in ascending order using the merge sort a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020596",
"row_id": 20596,
"seed_ids": "[28]"
} | 0.652314 | Data_Structure_20596 | I | [
"improved_sort",
"merge"
] | 2 | [
[
"improved_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2d48c5f1d8e8f3be06d114eb24304c0437eb5fbc | c39afa00f7e46d6111bc61090f1959e1123c82b8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20598_I | Pancake Sort Optimization and Enhancement
You are given an array of integers that you need to sort using the Pancake Sort algorithm. Write a function `enhanced_pancake_sort` that sorts the array in ascending order. Your task is to first improve the basic pancake sort by minimizing the number of flips and ensuring the ... | from typing import List
def flip(arr: List[int], k: int):
"""Helper function to reverse the array from start up to index k."""
arr[:k+1] = arr[:k+1][::-1]
def enhanced_pancake_sort(arr: List[int]) -> List[int]:
"""Sorts an array using the enhanced Pancake Sort algorithm."""
n = len(arr)
for size i... | from solution import enhanced_pancake_sort
def test_enhanced_pancake_sort_example_case():
assert enhanced_pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
def test_enhanced_pancake_sort_single_element():
assert enhanced_pancake_sort([1]) == [1]
def test_enhanced_pancake_sort_already_sorted():
assert enhanced_p... | [
{
"docstring": "Helper function to reverse the array from start up to index k.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Sorts an array using the enhanced Pancake Sort algorithm.",
"function_declaration": "def ... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef flip(arr: List[int], k: int) -> None:\n \"\"\"\n Flips the first k elements of the array arr in ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020598",
"row_id": 20598,
"seed_ids": "[9]"
} | 0.713703 | Data_Structure_20598 | I | [
"flip",
"enhanced_pancake_sort"
] | 2 | [
[
"enhanced_pancake_sort",
"flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 44c16496ccc2fda4c74290a20fb2e10740648628 | c298fa8caa9a6ca1258bbbff23f34c8241b0a88c | |||
v1.0 | instruct | Data_Structure | Data_Structure_20635_I | Find Primitive Roots
Given a positive integer n, your task is to write a function that finds all primitive roots of n. If no primitive roots exist, return an empty list.
### Function Signature
```python
def find_primitive_root(n: int) -> List[int]:
""" Returns a list of all primitive roots of n. """
```
### Inp... | from typing import List
import math
def gcd(a: int, b: int) -> int:
while b:
a, b = b, a % b
return a
def find_primitive_root(n: int) -> List[int]:
def is_primitive_root(root: int, n: int, totient: int) -> bool:
required = set(range(1, n))
seen = set()
current = root
... | from solution import find_primitive_root
def test_find_primitive_root_prime():
assert find_primitive_root(13) == [2, 6, 7, 11]
def test_find_primitive_root_non_prime():
assert find_primitive_root(10) == []
def test_find_primitive_root_minimal():
assert find_primitive_root(1) == [0]
def test_find_primiti... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def find_primitive_root(n):",
"function_name": "find_primitive_root",
"parameter_list": "(n)"
},
{
"docstring... | [
0,
0,
0,
1,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import gcd\nfrom typing import List\n\ndef compute_totient(n: int) -> int:\n result = n\n p = 2\n while p * p <= n:\n if n % p == 0:... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00020635",
"row_id": 20635,
"seed_ids": "[160]"
} | 0.494089 | Data_Structure_20635 | I | [
"gcd",
"find_primitive_root"
] | 2 | [
[
"find_primitive_root",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c1d8e39ebd2a6d226a951494125672123d4abe2d | 3b909a4df1faeb18b74d99be11c110020aa8fa5a | |||
v1.0 | instruct | Data_Structure | Data_Structure_20643_I | You are tasked with implementing an improved version of the Quick Sort algorithm to handle some of its common drawbacks. In particular, you need to implement the following enhancements:
1. Implement the Quick Sort algorithm using a randomized pivot to minimize the risk of hitting the worst-case time complexity.
2. Swi... | import random
def insertion_sort(arr, low, high):
for i in range(low + 1, high + 1):
key = arr[i]
j = i - 1
while j >= low and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def partition(arr, low, high):
pivot_index = random.randint(low, high... | from solution import quick_sort_optimized
def test_sorted_array():
assert quick_sort_optimized([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert quick_sort_optimized([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_random_array():
arr = [3, 6, 8, 10, 1, 2, 1]
assert quick_sort_o... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, low, high):",
"function_name": "insertion_sort",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter_l... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef quick_sort_optimized(arr):\n if len(arr) <= 1:\n return arr\n else:\n _quick_sort(arr, 0, len(arr) - 1)\n return a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020643",
"row_id": 20643,
"seed_ids": "[25]"
} | 0.573863 | Data_Structure_20643 | I | [
"insertion_sort",
"partition",
"quick_sort",
"quick_sort_optimized"
] | 4 | [
[
"quick_sort",
"insertion_sort"
],
[
"quick_sort",
"partition"
],
[
"quick_sort_optimized",
"quick_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | f20bd818c1b61bf881f73bcfe4479931cf50190b | f9eee0689eda2a89239c19e2ba0bdc10a3f505d9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20677_I | ### Sorting Algorithm Analysis and Enhancement
Bogo Sort, also whimsically known as "stupid sort," is a notoriously inefficient algorithm due to its reliance on random shuffling. Despite being impractical for real-world applications, it serves as an engaging example of algorithm complexity and inefficiency.
For this ... | import random
def insertion_sort(arr):
"""
Sorts an array in ascending order using the insertion sort algorithm.
Parameters:
arr (list): The list of elements to be sorted.
Returns:
list: The sorted list.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
... | from solution import insertion_sort, is_sorted, bogo_sort
def test_insertion_sort_empty():
assert insertion_sort([]) == []
def test_insertion_sort_single_element():
assert insertion_sort([1]) == [1]
def test_insertion_sort_sorted():
assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_inse... | [
{
"docstring": "Sorts an array in ascending order using the insertion sort algorithm.\n\nParameters:\narr (list): The list of elements to be sorted.\n\nReturns:\nlist: The sorted list.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef insertion_sort(arr):\n \"\"\"\n Sorts an array in ascending order using the insertion sort algorithm.\n \n Parameters:\n a... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020677",
"row_id": 20677,
"seed_ids": "[16]"
} | 0.541382 | Data_Structure_20677 | I | [
"insertion_sort",
"is_sorted",
"bogo_sort",
"compare_performance"
] | 4 | [
[
"bogo_sort",
"is_sorted"
],
[
"compare_performance",
"bogo_sort"
],
[
"compare_performance",
"insertion_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 0a1a8faa12a5220c7825e4a425b355def7646fa4 | 1baf8e13a164361bbeb5548b290ec0c96649c64a | |||
v1.0 | instruct | Data_Structure | Data_Structure_20743_I | ### Binary Search Enhancement
#### Problem Statement
You are given an array of integers sorted in ascending order and a target integer. Your task is to write a function that returns the index of the first occurrence of the target in the array using binary search. If the target is not found, return `-1`.
You must im... | from typing import List
def binary_search_iterative(array: List[int], target: int) -> int:
"""
Perform binary search to find the first occurrence of the target using iterative approach.
"""
left, right = 0, len(array) - 1
result = -1
while left <= right:
mid = (left + right) // 2
... | from solution import binary_search_iterative, binary_search_recursive
def test_binary_search_iterative():
array1 = [1, 2, 4, 4, 5, 6, 8]
target1 = 4
assert binary_search_iterative(array1, target1) == 2
array2 = [1, 3, 5, 7, 9]
target2 = 2
assert binary_search_iterative(array2, target2) == -1
... | [
{
"docstring": "Perform binary search to find the first occurrence of the target using iterative approach.",
"function_declaration": "def binary_search_iterative(array, target):",
"function_name": "binary_search_iterative",
"parameter_list": "(array, target)"
},
{
"docstring": "Helper functi... | [
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_iterative(array: List[int], target: int) -> int:\n left, right = 0, len(array) - 1\n result = -1\n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020743",
"row_id": 20743,
"seed_ids": "[200]"
} | 0.695742 | Data_Structure_20743 | I | [
"binary_search_iterative",
"binary_search_recursive_helper",
"binary_search_recursive"
] | 3 | [
[
"binary_search_recursive",
"binary_search_recursive_helper"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6c7b50e43155198a199a349fd7c677e519d27373 | e5d3bfa1cbeab6f48217d90625180e561e62d497 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20793_I | ### Problem: Compute Euler's Totient Function for an Array of Integers
Your task is to write a function that computes the totient function (ϕ(n)) for each integer in a list. You will be given an array of integers and must return an array of totient function results corresponding to each integer.
### Function Signatur... | from typing import List
def compute_totient(n: int) -> int:
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 compute_totients(ar... | from solution import compute_totients
def test_compute_totients_basic():
assert compute_totients([1, 2, 3, 4, 5]) == [1, 1, 2, 2, 4]
assert compute_totients([6, 25, 100]) == [2, 20, 40]
def test_compute_totients_single_element():
assert compute_totients([10]) == [4]
assert compute_totients([7]) == [6]... | [
{
"docstring": null,
"function_declaration": "def compute_totient(n):",
"function_name": "compute_totient",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def compute_totients(arr):",
"function_name": "compute_totients",
"parameter_list": "(arr)"
}
] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef compute_totients(arr: List[int]) -> List[int]:\n \"\"\"\n Computes Euler's Totient Function for each integer in the given... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020793",
"row_id": 20793,
"seed_ids": "[141]"
} | 0.576043 | Data_Structure_20793 | I | [
"compute_totient",
"compute_totients"
] | 2 | [
[
"compute_totients",
"compute_totient"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ba767d43d40e830d68e39241122c647c0b4a92a8 | e9299b5de0e83d89e7140415efbb8ba41bdb5a4f | |||
v1.0 | instruct | Data_Structure | Data_Structure_20877_I | **Problem Statement**:
You are given a large document (text) and a specific word (pattern) that you need to search within the text. Use the Knuth-Morris-Pratt (KMP) algorithm to efficiently find all the starting indices where the word appears as a substring in the document.
**Function Signature**:
```python
def find_... | from typing import List
def compute_lps(pattern: str) -> List[int]:
"""
Helper function to compute the Longest Prefix Suffix (LPS) array used in KMP algorithm.
"""
lps = [0] * len(pattern)
length = 0 # length of the previous longest prefix suffix
i = 1
while i < len(pattern):
... | from solution import find_pattern_occurrences
def test_find_pattern_occurrences_basic():
assert find_pattern_occurrences('hello there hero!', 'he') == [0, 7, 12]
def test_find_pattern_occurrences_multiple_matches():
assert find_pattern_occurrences('abcabcabc', 'abc') == [0, 3, 6]
def test_find_pattern_occurr... | [
{
"docstring": "Helper function to compute the Longest Prefix Suffix (LPS) array used in KMP algorithm.",
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": null,
"function_declaration": "def find_pattern_o... | [
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 compute_lps(pattern: str) -> List[int]:\n \"\"\"\n Helper function to compute the Longest Prefix Suffix (LPS) array used ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020877",
"row_id": 20877,
"seed_ids": "[93]"
} | 0.552888 | Data_Structure_20877 | I | [
"compute_lps",
"find_pattern_occurrences"
] | 2 | [
[
"find_pattern_occurrences",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | add13573e7d23d3489839d84dacc5ae06674ef81 | e290d4683e83d0b8558ea7d85e8e62999abfa4c1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20896_I | ### Stooge Sort Analysis and Enhancement
You are given a recursive sorting algorithm known as Stooge Sort. It is known for its inefficiency due to its high time complexity but serves as a good educational example for understanding recursive sorting mechanisms.
**Task**: Augment the Stooge Sort implementation to inclu... | def insertion_sort(arr, l, h):
for i in range(l + 1, h + 1):
key = arr[i]
j = i - 1
while j >= l and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def stoogesort(arr, l, h, k=10):
# Early termination check
already_sorted = True
for i i... | from solution import stoogesort
def test_stoogesort_sorted_input():
array = [1, 2, 3, 4, 5]
stoogesort(array, 0, len(array) - 1)
assert array == [1, 2, 3, 4, 5]
def test_stoogesort_reverse_sorted_input():
array = [5, 4, 3, 2, 1]
stoogesort(array, 0, len(array) - 1)
assert array == [1, 2, 3, 4,... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, l, h):",
"function_name": "insertion_sort",
"parameter_list": "(arr, l, h)"
},
{
"docstring": null,
"function_declaration": "def stoogesort(arr, l, h, k=10):",
"function_name": "stoogesort",
"parameter_list": "... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def stoogesort(arr, l, h, k=5):\n \"\"\"\n Performs Stooge Sort on the array with enhancements.\n \n Parameters:\n arr (list): The list to be s... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020896",
"row_id": 20896,
"seed_ids": "[10]"
} | 0.625549 | Data_Structure_20896 | I | [
"insertion_sort",
"stoogesort"
] | 2 | [
[
"stoogesort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 483b5837631ea974c639a3fff1eecb5303606aa9 | 0a66f295a29f23eab0b46c605ac2a72f64a594d2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20922_I | ### Cycle Detection in a Directed Graph
#### Objective:
Write Python functions to determine if a directed graph has a cycle. This is crucial in applications like detecting deadlocks in operating systems, where processes and resources can be modeled as a directed graph.
#### Details:
- You are provided with a function... | from enum import Enum
class TraversalState(Enum):
WHITE = 0
GRAY = 1
BLACK = 2
def is_in_cycle(graph, traversal_states, vertex):
"""
Determines if the given vertex is in a cycle.
:param graph: Dictionary representation of the graph.
:param traversal_states: Dictionary representing the stat... | def test_empty_graph():
graph = {}
assert contains_cycle(graph) == False
def test_single_vertex_no_edges():
graph = {'A': []}
assert contains_cycle(graph) == False
def test_single_cycle():
graph = {
'A': ['B'],
'B': ['C'],
'C': ['A']
}
assert contains_cycle(graph) =... | [] | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from enum import Enum\n\nclass TraversalState(Enum):\n WHITE = 0\n GRAY = 1\n BLACK = 2\n\ndef is_in_cycle(graph, traversal_states, vertex):\n \"\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020922",
"row_id": 20922,
"seed_ids": "[237]"
} | 0.628688 | Data_Structure_20922 | I | [
"is_in_cycle",
"contains_cycle"
] | 2 | [
[
"contains_cycle",
"is_in_cycle"
]
] | 1 | [] | false | [
"TraversalState"
] | true | pytest | false | [] | true | 495fc153579a4dcd0119decd2e53a587ec7ac1b9 | 3909b772608cb90c6372bd3e85213ed7a4ac024a | |||
v1.0 | instruct | Data_Structure | Data_Structure_20957_I | ---
### Problem: Sorting Checker
You have been provided with a highly inefficient sorting algorithm called Bogo Sort. Your task is to develop a more efficient checker function to verify if the list is sorted in ascending order. Alongside, implement a new function that uses this sorting checker to stop the Bogo Sort ea... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Checks if the given list is sorted in ascending order.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort_with_check(arr: List[int]) -> List[int]:
... | from solution import is_sorted, bogo_sort_with_check
def test_is_sorted_empty_list():
assert is_sorted([]) is True
def test_is_sorted_single_element():
assert is_sorted([1]) is True
def test_is_sorted_sorted_list():
assert is_sorted([1, 2, 3, 4, 5]) is True
def test_is_sorted_unsorted_list():
assert... | [
{
"docstring": "Checks if the given list is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the list using an improved Bogo Sort algorithm that stops early if the list becomes sorted.... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Check if the given list is sorted in ascending order.\n \... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020957",
"row_id": 20957,
"seed_ids": "[16]"
} | 0.574369 | Data_Structure_20957 | I | [
"is_sorted",
"bogo_sort_with_check"
] | 2 | [
[
"bogo_sort_with_check",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fe3f552f01dbde669942a92b0702b635ba49b509 | 9ab4cb7ba6b321df2924cdb84eb58d4889fd3fa4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_20985_I | ### Knuth-Morris-Pratt String Matching Enhancement
Given the implementation of the Knuth-Morris-Pratt (KMP) algorithm for string matching, enhance it to handle multiple patterns simultaneously. Specifically, you will implement a function `multi_pattern_kmp` which searches for multiple patterns in a given text and retu... | from typing import List, Dict
def compute_kmp_table(pattern: str) -> List[int]:
"""
Compute the KMP table (also known as the "partial match" table or "failure function")
for a given pattern.
"""
table = [0] * len(pattern)
j = 0 # length of the previous longest prefix suffix
i = 1
while... | def test_compute_kmp_table():
assert compute_kmp_table("ABCDABD") == [0, 0, 0, 0, 1, 2, 0]
assert compute_kmp_table("AAAA") == [0, 1, 2, 3]
assert compute_kmp_table("AABAACAABAA") == [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5]
def test_knuth_morris_pratt():
assert knuth_morris_pratt("ABABDABACDABABCABAB", "ABABC... | [
{
"docstring": "Compute the KMP table (also known as the \"partial match\" table or \"failure function\")\nfor a given pattern.",
"function_declaration": "def compute_kmp_table(pattern):",
"function_name": "compute_kmp_table",
"parameter_list": "(pattern)"
},
{
"docstring": "KMP algorithm 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": "from typing import List, Dict\n\ndef compute_lps(pattern: str) -> List[int]:\n lps = [0] * len(pattern)\n length = 0 # length of the previous longest p... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020985",
"row_id": 20985,
"seed_ids": "[93]"
} | 0.603286 | Data_Structure_20985 | I | [
"compute_kmp_table",
"knuth_morris_pratt",
"multi_pattern_kmp"
] | 3 | [
[
"knuth_morris_pratt",
"compute_kmp_table"
],
[
"multi_pattern_kmp",
"knuth_morris_pratt"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | b6ffaf093117601dca6bc54952ab531a9b9689b2 | 74846d9de80e33fb49563fd6100d259f099b47e7 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21006_I | ### Problem Description
You are asked to implement an optimized version of the Merge Sort algorithm for sorting a list of integers. Your implementation should focus on efficiency and correctness while demonstrating a sound understanding of the merge sort process. Instead of using subarrays, you should use indices to m... | from typing import List
def insertion_sort(arr: List[int], left: int, right: int):
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 merge(arr: List[int], left: int, ... | from solution import hybrid_merge_sort
def test_hybrid_merge_sort_empty():
assert hybrid_merge_sort([]) == []
def test_hybrid_merge_sort_single_element():
assert hybrid_merge_sort([1]) == [1]
def test_hybrid_merge_sort_two_elements():
assert hybrid_merge_sort([2, 1]) == [1, 2]
def test_hybrid_merge_sort... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def merge(arr, left, mid, right):",
"function_name": "merge",
"paramete... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[int], left: int, right: int) -> None:\n \"\"\"\n Sorts the subarray arr[left:right+1] using inse... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021006",
"row_id": 21006,
"seed_ids": "[12]"
} | 0.650502 | Data_Structure_21006 | I | [
"insertion_sort",
"merge",
"hybrid_merge_sort"
] | 3 | [
[
"hybrid_merge_sort",
"insertion_sort"
],
[
"hybrid_merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5d41bd8dfbfa1ef75b0b53c1cb40212db238cfbb | f9def354d42bc9fb0b68731470122e776b5d7733 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21022_I | ### Question
**String Reversal Algorithm Implementation**
You are tasked with implementing a function to reverse a given string using a specified method. The method should be chosen based on the application needs and constraints provided.
**Function Signature**:
```python
def reverse_string(s: str, method: str) -> s... | def reverse_string(s: str, method: str) -> str:
"""
Reverses a string based on the specified method.
Parameters:
s (str): The string to be reversed.
method (str): The method to use for reversal. One of 'recursive', 'iterative', 'pythonic', 'ultra_pythonic'.
Returns:
str: The revers... | from solution import reverse_string
def test_reverse_string_recursive():
assert reverse_string("hello", "recursive") == "olleh"
assert reverse_string("world", "recursive") == "dlrow"
assert reverse_string("a", "recursive") == "a"
assert reverse_string("", "recursive") == ""
def test_reverse_string... | [
{
"docstring": "Reverses a string based on the specified method.\n\nParameters:\ns (str): The string to be reversed.\nmethod (str): The method to use for reversal. One of 'recursive', 'iterative', 'pythonic', 'ultra_pythonic'.\n\nReturns:\nstr: The reversed string.",
"function_declaration": "def reverse_str... | [
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 reverse_string(s: str, method: str) -> str:\n \"\"\"\n Reverses the given string `s` using the specified method.\n \n :param s: The string to ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021022",
"row_id": 21022,
"seed_ids": "[61]"
} | 0.694572 | Data_Structure_21022 | I | [
"reverse_string",
"_reverse_recursive",
"_reverse_iterative",
"_reverse_pythonic",
"_reverse_ultra_pythonic"
] | 5 | [
[
"reverse_string",
"_reverse_iterative"
],
[
"reverse_string",
"_reverse_pythonic"
],
[
"reverse_string",
"_reverse_recursive"
],
[
"reverse_string",
"_reverse_ultra_pythonic"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | ab6bc46240de1e3d8a0be3d60910a2d0b7b20712 | a756c5a9127e6653efff8b46621147392c83c928 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21024_I | ### Fibonacci Focus
You are tasked with writing an optimized function to compute the nth Fibonacci number using matrix exponentiation. This method should maintain a polynomial time complexity.
The Fibonacci numbers are defined as:
- F0 = 0, F1 = 1
- Fn = Fn-1 + Fn-2 for n > 1
Matrix exponentiation allows us to compu... | def matrix_mult(A, B):
"""
Multiplies two 2x2 matrices.
"""
return [
[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]
]
def matrix_pow(M, power):
"""
Exponentiates m... | from solution import fib_matrix
def test_fib_matrix_base_cases():
assert fib_matrix(0) == 0
assert fib_matrix(1) == 1
def test_fib_matrix_small_cases():
assert fib_matrix(2) == 1
assert fib_matrix(3) == 2
assert fib_matrix(4) == 3
assert fib_matrix(5) == 5
def test_fib_matrix_larger_cases():
... | [
{
"docstring": "Multiplies two 2x2 matrices.",
"function_declaration": "def matrix_mult(A, B):",
"function_name": "matrix_mult",
"parameter_list": "(A, B)"
},
{
"docstring": "Exponentiates matrix M to the given power using exponentiation by squaring.",
"function_declaration": "def matrix... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fib_matrix(n: int) -> int:\n \"\"\"\n Compute the nth Fibonacci number using matrix exponentiation method.\n \"\"\"\n if n == 0:\n retu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021024",
"row_id": 21024,
"seed_ids": "[37]"
} | 0.745657 | Data_Structure_21024 | I | [
"matrix_mult",
"matrix_pow",
"fib_matrix"
] | 3 | [
[
"fib_matrix",
"matrix_pow"
],
[
"matrix_pow",
"matrix_mult"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 935aea28ec602c7d3ad82ddb0bc2827343e591a2 | c5befbfbc0776a44d792dc2f7ddd1a3f0aae8a71 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21030_I | ### Gnome Sort in Practice
#### Background
Gnome Sort is a simple, intuitive sorting algorithm that is not efficient for large datasets but can be useful for educational purposes or when sorting trivially small datasets. The algorithm employs a series of comparisons and swaps to ensure the array is ordered.
#### Task... | def gnome_sort(arr):
"""
Sorts a list of integers using the Gnome Sort algorithm.
"""
index = 0
while index < len(arr):
if index == 0 or arr[index] >= arr[index - 1]:
index += 1
else:
arr[index], arr[index - 1] = arr[index - 1], arr[index]
index -=... | from solution import gnome_sort, sorted_index_positions
def test_gnome_sort():
assert gnome_sort([34, 2, 78, 1, 58]) == [1, 2, 34, 58, 78]
assert gnome_sort([5, 3, 1, 4, 2]) == [1, 2, 3, 4, 5]
assert gnome_sort([]) == []
assert gnome_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
assert gnome_sort([3, 3,... | [
{
"docstring": "Sorts a list of integers using the Gnome Sort algorithm.",
"function_declaration": "def gnome_sort(arr):",
"function_name": "gnome_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Returns a list of indices showing the new positions of the elements in the sorted 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 gnome_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array of integers using the Gnome Sort algorithm.\n \"\"\... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00021030",
"row_id": 21030,
"seed_ids": "[13]"
} | 0.645429 | Data_Structure_21030 | I | [
"gnome_sort",
"sorted_index_positions"
] | 2 | [
[
"sorted_index_positions",
"gnome_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c57b423e55e0db4a7caded8d59d59afd9b800392 | 3d68d303db010d52747ead1131c06a69336b276d | |||
v1.0 | instruct | Data_Structure | Data_Structure_21051_I | RSA Public Key Cryptosystem
#### Context
The RSA public key cryptosystem heavily relies on number theory and concepts such as the Extended Euclidean Algorithm and Modular Inverse. Given two large prime numbers p and q, the RSA algorithm involves calculating the public and private keys for secure communication.
#### P... | def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def extended_gcd(a, b):
if a == 0:
return b, 0, 1
gcd, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y
def modular_inverse(a, m):
gcd, x, _ = extended_gcd(a, m)
if gcd != 1:
... | from solution import generate_rsa_keys
def test_generate_rsa_keys_small_primes():
p, q = 17, 23
public_key, private_key, n = generate_rsa_keys(p, q)
assert public_key == 65537
assert n == 391
assert (public_key * private_key) % ((p - 1) * (q - 1)) == 1
def test_generate_rsa_keys_larger_primes():
... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n while b != 0:\n a, b = b, a % b\n return a\n\ndef extended_gcd(a, b):\n if a == 0:\n return b, 0, 1\n gcd, x1, y1 =... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021051",
"row_id": 21051,
"seed_ids": "[161]"
} | 0.605098 | Data_Structure_21051 | I | [
"gcd",
"extended_gcd",
"modular_inverse",
"generate_rsa_keys"
] | 4 | [
[
"generate_rsa_keys",
"gcd"
],
[
"generate_rsa_keys",
"modular_inverse"
],
[
"modular_inverse",
"extended_gcd"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | a6d0e6a106e59ec1b7d02f88f0439662a969d945 | 1e3d24dbaac4bfbed6fa9e618e9b2dea4a5ef4b4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21098_I | **Extended Euclidean Algorithm & Modular Inverse Implementation**
You have been given the task of implementing two functions that utilize the Extended Euclidean Algorithm to compute:
1. The GCD of two integers, and their corresponding coefficients.
2. The modular inverse of an integer modulo \(m\).
### Full Descripti... | def extended_gcd(a, b):
"""
Implements the Extended Euclidean Algorithm.
Calculates integers x and y such that ax + by = gcd(a, b).
Args:
a (int): First number.
b (int): Second number.
Returns:
tuple: (x, y, gcd(a, b))
"""
if b == 0:
return (1, 0, a)
else:
... | from solution import extended_gcd, modular_inverse
def test_extended_gcd():
assert extended_gcd(30, 12) == (1, -2, 6)
assert extended_gcd(12, 30) == (-2, 1, 6) # Different sequence yields the same GCD
assert extended_gcd(101, 10) == (1, -10, 1)
assert extended_gcd(0, 5) == (0, 1, 5)
assert extende... | [
{
"docstring": "Implements the Extended Euclidean Algorithm.\nCalculates integers x and y such that ax + by = gcd(a, b).\n\nArgs:\na (int): First number.\nb (int): Second number.\n\nReturns:\ntuple: (x, y, gcd(a, b))",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
... | [
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 Computes the extended GCD of a and b.\n \n Args:\n a (int): first integer\n b (int): second integ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021098",
"row_id": 21098,
"seed_ids": "[161]"
} | 0.556982 | Data_Structure_21098 | I | [
"extended_gcd",
"modular_inverse"
] | 2 | [
[
"modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 672b8919e4cbead1dc3c2193cffa31e0f5f0687b | aba5e017c6ed73490008113ec8ef1e18457bae8e | |||
v1.0 | instruct | Data_Structure | Data_Structure_21101_I | Write a function called `next_prime` that takes an integer `n` and returns the smallest prime number larger than `n`. The function should efficiently utilize the given `prime_check` function as part of its solution.
### Input
* An integer `n` (−10^6 ≤ n ≤ 10^6)
### Output
* Returns an integer that is the smallest pr... | import math
def is_prime(num):
"""
Helper function to check if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
... | from solution import next_prime
def test_next_prime_positive():
assert next_prime(10) == 11
assert next_prime(17) == 19
assert next_prime(20) == 23
assert next_prime(1000) == 1009
def test_next_prime_negative_and_zero():
assert next_prime(-5) == 2
assert next_prime(0) == 2
assert next_prim... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the smallest prime number greater than n.",
"function_declaration": "def next_prime(n):",
"... | [
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\n\ndef is_prime(num):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021101",
"row_id": 21101,
"seed_ids": "[143]"
} | 0.623001 | Data_Structure_21101 | I | [
"is_prime",
"next_prime"
] | 2 | [
[
"next_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9f8f87af3d43a0ab02907730976698301abc3afb | d394b9f744cac8836e974b592fe63f7a1fcfaef8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21178_I | ## Question
### Problem Statement
You are required to implement an optimized version of the Quick Sort algorithm. Your function should sort an array of integers efficiently, optimizing for both average and worst-case scenarios. Specifically, you should:
1. Use a randomized pivot to avoid the worst-case performance o... | import random
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 _quick_sort(arr:... | from solution import optimized_quick_sort
def test_empty_array():
assert optimized_quick_sort([]) == []
def test_single_element():
assert optimized_quick_sort([1]) == [1]
def test_already_sorted():
assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted():
assert opti... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, low, high):",
"function_name": "insertion_sort",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def _quick_sort(arr, low, high):",
"function_name": "_quick_sort",
"paramet... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef insertion_sort(arr, low, high):\n for i in range(low + 1, high + 1):\n key = arr[i]\n j = i - 1... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021178",
"row_id": 21178,
"seed_ids": "[25]"
} | 0.600288 | Data_Structure_21178 | I | [
"insertion_sort",
"_quick_sort",
"optimized_quick_sort"
] | 3 | [
[
"_quick_sort",
"insertion_sort"
],
[
"optimized_quick_sort",
"_quick_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4ec7b0af330e3b951f96c769bfc016b50070f050 | 05e79a0aca52a0cfebe02bd85180e1c38a520e43 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21228_I | ### Radix Sort Application to Transaction IDs
Consider a scenario where you are working with a large dataset of transaction IDs represented as integers. These transaction IDs need to be sorted in ascending order for efficient lookup and subsequent processing. Implement the `radix_sort` function to sort these transacti... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool=False) -> None:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n ... | from solution import radix_sort
def test_empty_list():
assert radix_sort([]) == []
def test_single_element():
assert radix_sort([1]) == [1]
def test_sorted_list():
assert radix_sort([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def test_reverse_sorted_list():
assert radix_sort(... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation=False):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"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 typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool) -> None:\n n = len(arr)\n output = [0] * n\n count = [0] * 1... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021228",
"row_id": 21228,
"seed_ids": "[15]"
} | 0.55357 | Data_Structure_21228 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a838fabb3a26e34b2f2beb9b1d0f6bb34b8f070b | 4c063dff868135c6ab9b95e149b9303a3b9a7080 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21244_I | **Context**:
Bogo Sort is an intentionally inefficient algorithm used for academic purposes to demonstrate the pitfalls of relying on randomness for sorting. Despite its impracticality, understanding Bogo Sort provides a clear understanding of why efficient algorithms are necessary.
Write a function to sort an array ... | from itertools import permutations
def is_sorted(arr):
"""
Check if the given list is sorted in ascending order.
"""
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def permutation_bogo_sort(arr):
"""
Sort the given list of elements using a variation of Bogo Sort by generating
al... | from solution import permutation_bogo_sort
def test_permutation_bogo_sort_sorted_list():
assert permutation_bogo_sort([1, 2, 3]) == [1, 2, 3]
def test_permutation_bogo_sort_reversed_list():
assert permutation_bogo_sort([3, 2, 1]) == [1, 2, 3]
def test_permutation_bogo_sort_mixed_list():
assert permutatio... | [
{
"docstring": "Check if the given list is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sort the given list of elements using a variation of Bogo Sort by generating\nall possible permuta... | [
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 itertools import permutations\n\ndef permutation_bogo_sort(arr):\n \"\"\"\n Sort the given list of elements using a variation of Bogo Sort.\n\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021244",
"row_id": 21244,
"seed_ids": "[16]"
} | 0.57201 | Data_Structure_21244 | I | [
"is_sorted",
"permutation_bogo_sort"
] | 2 | [
[
"permutation_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e90ceec482f8e6a99620c5018c83e79590324cf5 | cbc64c5345ca0656cbe9d59493c0ba55d1b49cd4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21248_I | ### Binary Tree Construction from Traversal Data
You are given the pre-order and post-order traversal sequences of a full binary tree. A full binary tree is a binary tree in which every node has either 0 or 2 children. Your task is to reconstruct this full binary tree and return its in-order traversal sequence.
### I... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def construct_tree(pre, pre_start, pre_end, post, post_start, post_end):
if pre_start > pre_end or post_start > post_end:
return None
root = TreeNode(pre... | from solution import build_tree_inorder
def test_build_tree_inorder_simple():
pre = [1, 2, 4, 5, 3, 6, 7]
post = [4, 5, 2, 6, 7, 3, 1]
expected_inorder = [4, 2, 5, 1, 6, 3, 7]
assert build_tree_inorder(pre, post) == expected_inorder
def test_build_tree_inorder_single_node():
pre = [1]
post = [... | [] | [
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 build_tree_inorder(pre, post):\n # Helper function to construct tree and get inorder traversal\n def construct(pre_index, post_start, post_end):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021248",
"row_id": 21248,
"seed_ids": "[300]"
} | 0.575902 | Data_Structure_21248 | I | [
"construct_tree",
"inorder_traversal",
"build_tree_inorder"
] | 3 | [
[
"build_tree_inorder",
"construct_tree"
],
[
"build_tree_inorder",
"inorder_traversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 0969e07d6da586e427171a5b65928e5b3db80e60 | da403609cb4dfd177ef0cbf2f1cdde82a9ae7ae9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21251_I | Maximum Flow Network Analysis
#### Task
You are given a directed graph representing a flow network with `n` vertices and `m` edges. Each edge has a specific capacity representing the maximum possible flow that can pass through that edge. Your task is to implement the Ford-Fulkerson, Edmonds-Karp, and Dinic algorithms... | from typing import List, Tuple, Dict
from collections import deque, defaultdict
def bfs_level_graph(C, source, sink, levels, n):
queue = deque([source])
levels[source] = 0
while queue:
u = queue.popleft()
for v in range(n):
if levels[v] < 0 and C[u][v] > 0: # unused capacity
... | from solution import maximum_flow
def test_case_1():
n = 4
m = 5
edges = [(0, 1, 1000), (0, 2, 1000), (1, 2, 1), (1, 3, 1000), (2, 3, 1000)]
source = 0
sink = 3
result = maximum_flow(n, m, edges, source, sink)
assert result == {
"Ford-Fulkerson": 2000,
"Edmonds-Karp": 2000,
... | [
{
"docstring": null,
"function_declaration": "def bfs_level_graph(C, source, sink, levels, n):",
"function_name": "bfs_level_graph",
"parameter_list": "(C, source, sink, levels, n)"
},
{
"docstring": null,
"function_declaration": "def dfs_flow(C, levels, u, sink, flow):",
"function_n... | [
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, Tuple, Dict\nimport collections\n\ndef maximum_flow(n: int, m: int, edges: List[Tuple[int, int, int]], source: int, sink: int) -> Dic... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021251",
"row_id": 21251,
"seed_ids": "[240]"
} | 0.604749 | Data_Structure_21251 | I | [
"bfs_level_graph",
"dfs_flow",
"dinic_algorithm",
"bfs",
"ford_fulkerson",
"edmonds_karp",
"maximum_flow"
] | 7 | [
[
"dinic_algorithm",
"bfs_level_graph"
],
[
"dinic_algorithm",
"dfs_flow"
],
[
"edmonds_karp",
"ford_fulkerson"
],
[
"ford_fulkerson",
"bfs"
],
[
"maximum_flow",
"dinic_algorithm"
],
[
"maximum_flow",
"edmonds_karp"
],
[
"maximum_flow",
... | 7 | [] | false | [] | false | pytest | true | [] | true | 543d047fd8bde2d72d57558f927c3ebfca08e48e | 1b0c6a983300b888ba0305ea664097870c5d309c | |||
v1.0 | instruct | Data_Structure | Data_Structure_21313_I | ### Question: Efficient Quick Sort Implementation
**Scenario**:
You are tasked with sorting a large dataset of numbers using a highly efficient sorting algorithm due to memory constraints and the data's unsorted nature.
**Task**:
Implement an optimized version of Quick Sort, considering the partitioning and pivot sel... | from typing import List
import random
def median_of_three(arr, low, high):
mid = (low + high) // 2
a, b, c = arr[low], arr[mid], arr[high]
if a > b:
if a < c:
return low
elif b > c:
return mid
else:
return high
if b < c:
return mid
... | from solution import optimized_quick_sort
def test_sorted_array():
assert optimized_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert optimized_quick_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_unsorted_array():
assert optimized_quick_sort([3, 6, 8, 10, 1, 2, 1]... | [
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter... | [
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 optimized_quick_sort(arr, simulation=False):\n \"\"\"\n Sorts the array in place using the optimized quick sort algorithm with median-of-three pivot... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021313",
"row_id": 21313,
"seed_ids": "[25]"
} | 0.507838 | Data_Structure_21313 | I | [
"median_of_three",
"partition",
"quick_sort",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"quick_sort"
],
[
"partition",
"median_of_three"
],
[
"quick_sort",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 6f12e4ddcd45ef693913888710cfe82b496e82ad | 2bb21beffa0de406726ce0b2679e0ac097bc2e29 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21379_I | Develop a function `generalized_gcd(arr)` which computes the greatest common divisor (GCD) of a list of integers. Then, use this function to develop another function `generalized_lcm(arr)` to compute the least common multiple (LCM) for the same list of integers.
### Requirements
1. Implement the `generalized_gcd(arr)`... | import math
from functools import reduce
def gcd(a, b):
"""
Computes the greatest common divisor of a and b.
"""
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""
Computes the least common multiple of a and b.
"""
return abs(a*b) // gcd(a, b)
def generalized_gcd(arr):
... | import pytest
from solution import generalized_gcd, generalized_lcm
def test_generalized_gcd_positive_numbers():
assert generalized_gcd([2, 4, 6, 8]) == 2
assert generalized_gcd([10, 20, 40]) == 10
def test_generalized_gcd_mixed_numbers():
assert generalized_gcd([5, 7, 11]) == 1
assert generalized_gcd... | [
{
"docstring": "Computes the greatest common divisor of a and b.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the least common multiple of a and b.",
"function_declaration": "def lcm(a, b):",
"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": "import math\nfrom functools import reduce\n\ndef generalized_gcd(arr):\n \"\"\"\n Computes the GCD of a list of integers.\n\n Args:\n arr: List[in... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021379",
"row_id": 21379,
"seed_ids": "[166]"
} | 0.695018 | Data_Structure_21379 | I | [
"gcd",
"lcm",
"generalized_gcd",
"generalized_lcm"
] | 4 | [
[
"generalized_gcd",
"gcd"
],
[
"generalized_lcm",
"lcm"
],
[
"lcm",
"gcd"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 2555708988f671a83764c5dbe3dd846477267ddd | 5c3668e97ee76fbd3b307cfd10edfae6ff1e026f | |||
v1.0 | instruct | Data_Structure | Data_Structure_21395_I | ### Scenario
You are building a cryptographic system that relies heavily on modular arithmetic and primitive roots. One of the critical operations is identifying these roots for given integers, which is necessary for secure key generation.
### Task
Implement a function `is_primitive_root(a, n)` that checks if a given ... | from math import gcd
def euler_totient(n):
"""Calculate Euler's Totient function ϕ(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
... | from solution import is_primitive_root, euler_totient, find_order
def test_is_primitive_root_example_1():
assert is_primitive_root(2, 5) == True
def test_is_primitive_root_example_2():
assert is_primitive_root(4, 6) == False
def test_is_primitive_root_small_primes():
assert is_primitive_root(3, 7) == Tru... | [
{
"docstring": "Calculate Euler's Totient function ϕ(n)",
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": "Find the order of a modulo n",
"function_declaration": "def find_order(a, n):",
"function_name": "fi... | [
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 gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef euler_totient(n):\n result = n\n p = 2\n while p * p <= n:\n if n %... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021395",
"row_id": 21395,
"seed_ids": "[160]"
} | 0.542465 | Data_Structure_21395 | I | [
"euler_totient",
"find_order",
"is_primitive_root"
] | 3 | [
[
"is_primitive_root",
"euler_totient"
],
[
"is_primitive_root",
"find_order"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5e4b297a6b7b768c3f93f9e2bd960ce5fe6464c0 | 4a3776f237402c9d71c92d48ec6e00545a48a206 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21404_I | ### Rabin-Miller Primality Test Implementation
#### Problem
You are tasked with implementing the Rabin-Miller primality test. Your function should determine whether a given number is prime with high probability. The number tested might be very large, so efficiency is important.
#### Function Signature
```python
def i... | import random
def miller_rabin_pass(a, s, d, n):
"""
Helper function for performing a single Miller-Rabin test.
"""
a_to_power = pow(a, d, n)
if a_to_power == 1:
return True
for _ in range(s - 1):
if a_to_power == n - 1:
return True
a_to_power = pow(a_to_powe... | from solution import is_probably_prime
def test_prime_small_prime_numbers():
assert is_probably_prime(2, 5) == True
assert is_probably_prime(3, 5) == True
assert is_probably_prime(5, 5) == True
assert is_probably_prime(7, 5) == True
assert is_probably_prime(13, 5) == True
assert is_probably_pri... | [
{
"docstring": "Helper function for performing a single Miller-Rabin 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 determine whether n is ... | [
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_probably_prime(n: int, k: int) -> bool:\n \"\"\"\n Determines if a number n is probably prime using the Rabin-Miller primality t... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021404",
"row_id": 21404,
"seed_ids": "[136]"
} | 0.691045 | Data_Structure_21404 | I | [
"miller_rabin_pass",
"is_probably_prime"
] | 2 | [
[
"is_probably_prime",
"miller_rabin_pass"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8a2cc8daf0a86e9eaeb9d709569d91cf8aec51c7 | 5376d9682ce03f1e8152f849221f9631c1213d9a | |||
v1.0 | instruct | Data_Structure | Data_Structure_21420_I | ### Scenario
You work as a software engineer for a company that maintains a large database system. The database needs to efficiently remove specific entries while maintaining an ordered structure, which is implemented using a Binary Search Tree (BST). Your task is to implement a function that removes a node from the BS... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def delete_node_in_bst(root, key):
if not root:
return root
if key < root.val:
root.left = delete_node_in_bst(root.left, key)
elif key > root.val... | from solution import TreeNode, delete_node_in_bst
def tree_to_list(root):
""" Helper function to convert tree to list for easy comparison """
if not root:
return []
result = []
queue = [root]
while queue:
node = queue.pop(0)
if node:
result.append(node.val)
... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef de... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021420",
"row_id": 21420,
"seed_ids": "[331]"
} | 0.606201 | Data_Structure_21420 | I | [
"delete_node_in_bst",
"find_min"
] | 2 | [
[
"delete_node_in_bst",
"find_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | aebe9fcdb122daf2b8c4b92695dd1c700dad8f8c | 30c0ae689c61dceb4794efd5de7607115c95d636 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21437_I | ### Question: Iterative FFT Implementation
You are tasked with implementing the Cooley-Tukey FFT algorithm iteratively. This way you can avoid potential recursion depth issues faced with the recursive implementation. Write a function `iterative_fft` that computes the DFT of an array of complex numbers using an iterati... | from typing import List
import cmath
import math
def bit_reverse_copy(a):
n = len(a)
result = [0] * n
bits = int(math.log2(n))
for i in range(n):
reveresed_i = int(f'{i:0{bits}b}'[::-1], 2)
result[reveresed_i] = a[i]
return result
def iterative_fft(x: List[complex]) -> List[complex... | from solution import iterative_fft
def test_iterative_fft_simple():
input_signal = [2.0+2j, 1.0+3j, 3.0+1j, 2.0+2j]
expected_output = [8+8j, 2j, 2-2j, -2+0j]
result = iterative_fft(input_signal)
assert all(abs(r - e) < 1e-9 for r, e in zip(result, expected_output))
def test_iterative_fft_power_of_two(... | [
{
"docstring": null,
"function_declaration": "def bit_reverse_copy(a):",
"function_name": "bit_reverse_copy",
"parameter_list": "(a)"
},
{
"docstring": null,
"function_declaration": "def iterative_fft(x):",
"function_name": "iterative_fft",
"parameter_list": "(x)"
}
] | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport cmath\n\ndef iterative_fft(x: List[complex]) -> List[complex]:\n n = len(x)\n levels = n.bit_length() - 1\n y = [0] *... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00021437",
"row_id": 21437,
"seed_ids": "[165]"
} | 0.55627 | Data_Structure_21437 | I | [
"bit_reverse_copy",
"iterative_fft"
] | 2 | [
[
"iterative_fft",
"bit_reverse_copy"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 786545bec7448f39a8325c4ec3f5aa37030a71e7 | 4625b0a04c8f99302dfe6249645c46909786d002 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21490_I | ### Heap Sort with Variations in Performance Analytics.
**Objective**:
You need to assess the students' understanding of heap sort implementations using both max heap and min heap and additionally evaluate their ability to analyze the performance of sorting algorithms.
**Context**:
The provided heap sort algorithms u... | from typing import List, Dict, Any
def max_heapify(arr: List[int], n: int, i: int, count: int) -> int:
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[l] > arr[largest]:
largest = l
if r < n and arr[r] > arr[largest]:
largest = r
if largest != i:
arr[i], arr[... | from solution import compare_heap_sorts
def test_compare_heap_sorts_example():
input_arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
result = compare_heap_sorts(input_arr)
expected_sorted_arr = sorted(input_arr)
assert result['sorted_max_heap'] == expected_sorted_arr
assert result['sorted_min_heap'] =... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, count):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, count)"
},
{
"docstring": null,
"function_declaration": "def heap_sort_max(arr):",
"function_name": "heap_sort_max",
"parameter_list":... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict, Any\n\ndef heapify(arr: List[int], n: int, i: int, max_heap: bool, iterations: List[int]) -> None:\n \"\"\"\n To heapify ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021490",
"row_id": 21490,
"seed_ids": "[8]"
} | 0.619463 | Data_Structure_21490 | I | [
"max_heapify",
"heap_sort_max",
"min_heapify",
"heap_sort_min",
"compare_heap_sorts"
] | 5 | [
[
"compare_heap_sorts",
"heap_sort_max"
],
[
"compare_heap_sorts",
"heap_sort_min"
],
[
"heap_sort_max",
"max_heapify"
],
[
"heap_sort_min",
"min_heapify"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 5954e3cc143955f6174d0af4036b100842bee7d1 | 3d66d397409882b1ae0e855dfac0e688ce9b5226 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21529_I | You are to implement the function `intersection` which determines the intersection node of two singly linked lists. The intersection is determined by reference, not by value.
### Function Signature
```python
def intersection(head1: Node, head2: Node) -> Optional[Node]:
pass
```
### Input:
* `head1` and `head2`: ... | class Node:
def __init__(self, x):
self.val = x
self.next = None
def get_length(head):
length = 0
while head:
length += 1
head = head.next
return length
def intersection(head1: Node, head2: Node) -> Node:
if not head1 or not head2:
return None
len1 ... | from solution import Node, intersection
def test_intersection():
# Example 1
# List A: 1 -> 3 -> 5
# \
# 7 -> 9 -> 11
# /
# List B: 2 -> 4 -> 6
common = Node(7)
common.next = Node(9)
common.next.next = Node(11)
head1 = Node(1... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\ndef intersection(head1: Node, head2: Node) -> Optional[No... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021529",
"row_id": 21529,
"seed_ids": "[245]"
} | 0.591501 | Data_Structure_21529 | I | [
"get_length",
"intersection"
] | 2 | [
[
"intersection",
"get_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 1556ef2e11857fc9f9b2b3542b608f54843ffdf4 | b218566c49d7fe90d18e42313f9297eb0218e4ba | |||
v1.0 | instruct | Data_Structure | Data_Structure_21557_I | ### Question: Insertion Sort with Binary Search Optimization
You are tasked with implementing an insertion sort algorithm, but with a twist. You will use binary search to find the correct insertion position in the sorted portion of the array.
#### Instructions:
1. Implement the `binary_search_insert` function given ... | def binary_search_insert(array, val):
"""
Given a sorted array and a target value, return the index if the target is
found. If not, return the index where it would be if it were inserted in order.
"""
low, high = 0, len(array)
while low < high:
mid = (low + high) // 2
if array[mi... | from solution import binary_search_insert, binary_insertion_sort
# Tests for binary_search_insert
def test_binary_search_insert_found():
assert binary_search_insert([1, 3, 5, 6], 5) == 2
def test_binary_search_insert_not_found():
assert binary_search_insert([1, 3, 5, 6], 2) == 1
assert binary_search_inser... | [
{
"docstring": "Given a sorted array and a target value, return the index if the target is\nfound. If not, return the index where it would be if it were inserted in order.",
"function_declaration": "def binary_search_insert(array, val):",
"function_name": "binary_search_insert",
"parameter_list": "(... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binary_search_insert(array, val):\n \"\"\"\n Given a sorted array and a target value, return the index if the target is\n found. If not, return t... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021557",
"row_id": 21557,
"seed_ids": "[199]"
} | 0.55179 | Data_Structure_21557 | I | [
"binary_search_insert",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"binary_search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 35a421e120fed9eff182c569a077a1bf663da3c4 | 22d99becd35ce6848d47a14a8ccb3aae0257b4ca | |||
v1.0 | instruct | Data_Structure | Data_Structure_21607_I | ### Graph Path-Finding Challenge
#### Context
You are tasked with implementing graph traversal functions. Your goal is to write efficient code that finds paths between two nodes in a given directed graph. Your solution should incorporate advanced understanding of algorithm optimization and handle typical pitfalls foun... | def find_path(graph, start, end, path=None):
"""
Returns one path from start to end or None if no path exists.
"""
if path is None:
path = []
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if... | from solution import find_path, find_all_paths, find_shortest_path
def test_find_path():
graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']}
assert find_path(graph, 'A', 'D') in [['A', 'B', 'D'], ['A', 'C', 'D'], ['A', 'B', 'C', 'D']]
def test_find_path_no_path():
gr... | [
{
"docstring": "Returns one path from start to end or None if no path exists.",
"function_declaration": "def find_path(graph, start, end, path=None):",
"function_name": "find_path",
"parameter_list": "(graph, start, end, path=None)"
},
{
"docstring": "Returns all paths from start to end as a... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_path(graph, start, end, path=[]):\n \"\"\"\n Find one path from start node to end node\n \"\"\"\n path = path + [start]\n if start == ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021607",
"row_id": 21607,
"seed_ids": "[242]"
} | 0.656921 | Data_Structure_21607 | I | [
"find_path",
"find_all_paths",
"find_shortest_path"
] | 3 | [
[
"find_shortest_path",
"find_all_paths"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3d026b33b470677239faab83521abf99ffb629d3 | 49e275f2c92dbb35a94d06054a4681ea74f1e105 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21657_I | ### Matrix Operations and Optimization in Dynamic Systems
The following tasks involve matrix operations fundamental to many scientific and engineering applications. You will implement two main functionalities to work with square matrices: power calculation and matrix operations for dynamic systems modeling.
#### Back... | def matrix_mult(A, B):
n = len(A)
C = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
return C
def matrix_power(mat, power):
n = len(mat)
result = [[1 if i == j else 0 for j in range(n)] for i ... | from solution import matrix_power, state_transition
def test_matrix_power_identity():
mat = [[2, 0], [0, 2]]
power = 0
expected = [[1, 0], [0, 1]]
assert matrix_power(mat, power) == expected
def test_matrix_power_example():
mat = [[1, 1], [1, 0]]
power = 2
expected = [[2, 1], [1, 1]]
a... | [
{
"docstring": null,
"function_declaration": "def matrix_mult(A, B):",
"function_name": "matrix_mult",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def matrix_power(mat, power):",
"function_name": "matrix_power",
"parameter_list": "(mat, power)"
}... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_mult(A, B):\n n = len(A)\n C = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n for k in range(n)... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021657",
"row_id": 21657,
"seed_ids": "[340]"
} | 0.516414 | Data_Structure_21657 | I | [
"matrix_mult",
"matrix_power",
"state_transition"
] | 3 | [
[
"matrix_power",
"matrix_mult"
],
[
"state_transition",
"matrix_power"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 37c4434e3ac2a44d48f53c12d5fd5e1fa80ed081 | 6deee1bb8af1986d4f0da5ccc2975b37503c7567 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21665_I | ### Question
**Scenario**:
Imagine you are developing features for a mapping application where users can search for the k closest landmarks to their current location. Your task is to implement a function that finds the k closest points (landmarks) to a given origin point.
**Task**:
Write a function `k_closest(points,... | import heapq
from math import sqrt
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points in 2D space.
"""
return sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def k_closest(points, k, origin=(0, 0)):
"""
Find the k closest points to... | from solution import k_closest
def test_basic_case():
points = [(1, 5), (2, 3), (-2, 4), (3, -2), (0, 1)]
k = 3
origin = (0, 0)
expected = [(0, 1), (2, 3), (3, -2)]
assert set(k_closest(points, k, origin)) == set(expected)
def test_with_different_origin():
points = [(1, 2), (3, 4), (1, -1)]
... | [
{
"docstring": "Calculate the Euclidean distance between two points in 2D space.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Find the k closest points to the origin from a ... | [
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\n\ndef k_closest(points, k, origin=(0, 0)):\n \"\"\"\n Returns the k closest points to the origin.\n \n Parameters:\n - points: Lis... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021665",
"row_id": 21665,
"seed_ids": "[266]"
} | 0.727057 | Data_Structure_21665 | I | [
"euclidean_distance",
"k_closest"
] | 2 | [
[
"k_closest",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cebcb06a21db6ca5846534f92d99576d6cbb2045 | 14832547a7e316b41ed64239c9e3f6d927d531f3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21681_I | Invert a Matrix
Given an invertible \(n \times n\) matrix represented as a list of lists, implement a function `invert_matrix(m)` to compute the inverse of the matrix.
### Function Signature
```python
def invert_matrix(m: List[List[float]]) -> List[List[float]]:
pass
```
### Input
- `m`: a list of lists of float... | from typing import List
def invert_matrix(m: List[List[float]]) -> List[List[float]]:
# Helper function to compute the determinant of a matrix
def get_determinant(matrix: List[List[float]]) -> float:
size = len(matrix)
if size == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] ... | from solution import invert_matrix
def test_invert_2x2_matrix():
m = [
[4, 3],
[3, 2]
]
expected = [
[-2.0, 3.0],
[3.0, -4.0]
]
assert invert_matrix(m) == expected
def test_invert_3x3_matrix():
m = [
[1, 2, 3],
[0, 1, 4],
[5, 6, 0]
]
... | [
{
"docstring": null,
"function_declaration": "def invert_matrix(m):",
"function_name": "invert_matrix",
"parameter_list": "(m)"
},
{
"docstring": null,
"function_declaration": "def transpose(matrix):",
"function_name": "transpose",
"parameter_list": "(matrix)"
},
{
"docst... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef get_matrix_determinant(m: List[List[float]]) -> float:\n \"\"\"\n Helper function to calculate the determinant of a given... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021681",
"row_id": 21681,
"seed_ids": "[347]"
} | 0.553827 | Data_Structure_21681 | I | [
"invert_matrix",
"transpose"
] | 2 | [
[
"invert_matrix",
"transpose"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6fc4a31cd595ddf7a2ab5ac0998f7536d6ea0c81 | 126cdbf58af400dfffc55bdbf3640c83c15bee22 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21683_I | ### Insertion Sort Implementation
**Background**:
You are given a partially implemented helper function `search_insert` which determines the position where an element should be inserted in a sorted array. Using this helper function to assist, your task is to implement the Insertion Sort algorithm.
**Task**:
Write a P... | from typing import List
def search_insert(sorted_arr: List[int], value: int) -> int:
"""
Determines the position where an element should be inserted in a sorted array.
"""
for i, v in enumerate(sorted_arr):
if value < v:
return i
return len(sorted_arr)
def insertion_sort(arr: L... | from solution import insertion_sort
def test_insertion_sort_with_unsorted_list():
assert insertion_sort([4, 3, 1, 2]) == [1, 2, 3, 4]
assert insertion_sort([10, -1, 3, 5]) == [-1, 3, 5, 10]
def test_insertion_sort_with_sorted_list():
assert insertion_sort([1, 2, 3, 4]) == [1, 2, 3, 4]
assert insertion... | [
{
"docstring": "Determines the position where an element should be inserted in a sorted array.",
"function_declaration": "def search_insert(sorted_arr, value):",
"function_name": "search_insert",
"parameter_list": "(sorted_arr, value)"
},
{
"docstring": "Sorts a given list of integers using ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(arr, x):\n \"\"\"\n Helper function to find the index where x should be inserted\n in the sorted portion of arr.\n \"\"\"\n f... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021683",
"row_id": 21683,
"seed_ids": "[199]"
} | 0.652755 | Data_Structure_21683 | I | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8f28657ee8b387fd6d2a8a07f451b981e299fae7 | 37de0c80d3774fdae608e3ca608c4393d0ec2365 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21694_I | ### Nearest Neighbor Algorithm Implementation
You are tasked with implementing a function that uses the nearest neighbor algorithm to classify data points. Your function will take a query vector and a training set, compute the nearest neighbor, and return the associated label.
#### Function Signature
```python
def ne... | import math
def euclidean_distance(v1, v2):
"""
Compute the Euclidean distance between two vectors.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def nearest_neighbor_classifier(query, training_set):
"""
Classifies the given query vector by nearest neighbor algorithm.
Ar... | from solution import nearest_neighbor_classifier
def test_nearest_neighbor_classifier_basic():
query_vector = (4.0, 3.5, 2.2)
training_vectors = {
(4.1, 3.4, 2.2): 'apple',
(3.1, 2.9, 3.5): 'banana',
(4.0, 3.5, 2.1): 'cherry'
}
assert nearest_neighbor_classifier(query_vector, tr... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef nearest_neighbor_classifier(query, training_set):\n \"\"\"\n Classifies the given query vector by the nearest neighbor algorithm.\n\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021694",
"row_id": 21694,
"seed_ids": "[260]"
} | 0.644059 | Data_Structure_21694 | I | [
"euclidean_distance",
"nearest_neighbor_classifier"
] | 2 | [
[
"nearest_neighbor_classifier",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c1f1b3bbdb0bb4289dcba8ab45901c48eb47454c | 9c4a389d4226e7db21034ce2b73baa30e5c99c28 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21735_I | ### Stack-Based Infix to Postfix Conversion
#### Scenario
In a computer science class, you are asked to evaluate mathematical expressions written in infix notation. However, computers prefer postfix notation because it’s easier to parse and evaluate mechanically. To assist in converting infix expressions to postfix no... | def get_precedence(op):
"""
Returns the precedence of the given operator.
Higher number means higher precedence.
"""
if op in {'+', '-'}:
return 1
if op in {'*', '/'}:
return 2
return 0
def infix_to_postfix(expression: str) -> str:
"""
Converts the given infix expres... | from solution import infix_to_postfix
def test_simple_expression():
assert infix_to_postfix("3+(2*5)") == "325*+"
def test_expression_with_multiple_parentheses():
assert infix_to_postfix("((3+1)*4)") == "31+4*"
def test_expression_with_all_operators():
assert infix_to_postfix("5+2*6-3/7") == "526*+37/-"
... | [
{
"docstring": "Returns the precedence of the given operator.\nHigher number means higher precedence.",
"function_declaration": "def get_precedence(op):",
"function_name": "get_precedence",
"parameter_list": "(op)"
},
{
"docstring": "Converts the given infix expression to postfix notation.",... | [
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 infix_to_postfix(expression: str) -> str:\n precedence = {'+': 1, '-': 1, '*': 2, '/': 2}\n stack = []\n postfix = []\n \n for char in expr... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021735",
"row_id": 21735,
"seed_ids": "[173]"
} | 0.532889 | Data_Structure_21735 | I | [
"get_precedence",
"infix_to_postfix"
] | 2 | [
[
"infix_to_postfix",
"get_precedence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 84f0ca09909fd164703147107480e0163861b454 | b6c77a12bebb4fcce4c4a2482e10673acd34f1d6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21759_I | You are tasked with enhancing an efficient algorithm for checking prime numbers to evaluate a given list of integers. The goal is to write a function `filter_primes(numbers: List[int]) -> List[int]` that filters and returns only the prime numbers from a list of integers.
### Requirements
* Your function should leverag... | import math
from typing import List
def is_prime(n: int) -> bool:
"""
Check if the number n is a prime number.
"""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or ... | from solution import filter_primes, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(5) == True
assert is_prime(4) == False
assert is_prime(0) == False
assert is_prime(1) == False
assert is_prime(-1) == False
assert is_prime(13) == True... | [
{
"docstring": "Check if the number n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Filters and returns only the prime numbers from a list of integers.",
"function_declaration": "def filter_primes(... | [
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 math import isqrt\nfrom typing import List\n\ndef prime_check(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021759",
"row_id": 21759,
"seed_ids": "[143]"
} | 0.6544 | Data_Structure_21759 | I | [
"is_prime",
"filter_primes"
] | 2 | [
[
"filter_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a9602c18a8fa3ffcfa1b02f3bebf384ca377525f | 84527cee8c596f5551da418d5d1c73d492e093c6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_21788_I | You are given two problems to solve involving matrix operations. You need to implement functions to perform matrix multiplication and matrix exponentiation. These operations are fundamental in various computational applications, including graphics, dynamic programming, and scientific computations.
### Task 1: Matrix M... | from typing import List
def multiply_matrices(matA: List[List[int]], matB: List[List[int]]) -> List[List[int]]:
"""
Multiplies two square matrices of size n x n.
"""
size = len(matA)
result = [[0 for _ in range(size)] for _ in range(size)]
for i in range(size):
for j in range(size)... | from solution import multiply_matrices, matrix_pow
def test_multiply_matrices():
matA = [[1, 2], [3, 4]]
matB = [[5, 6], [7, 8]]
expected = [[19, 22], [43, 50]]
assert multiply_matrices(matA, matB) == expected
def test_matrix_pow_exponent_0():
mat = [[1, 2], [3, 4]]
power = 0
expected = [[... | [
{
"docstring": "Multiplies two square matrices of size n x n.",
"function_declaration": "def multiply_matrices(matA, matB):",
"function_name": "multiply_matrices",
"parameter_list": "(matA, matB)"
},
{
"docstring": "Raises a square matrix to a given power using exponentiation by squaring.",
... | [
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 multiply_matrices(matA: List[List[int]], matB: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Multiplies two square matr... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021788",
"row_id": 21788,
"seed_ids": "[340]"
} | 0.515579 | Data_Structure_21788 | I | [
"multiply_matrices",
"matrix_pow"
] | 2 | [
[
"matrix_pow",
"multiply_matrices"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a0afd2c2b49eb49838c00d81027523f182aa77a8 | 18d1b01b3af73ee442a6256b579b76f8292e6a6b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.