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_24875_I | **Question:**
You are given a directed graph represented as an adjacency list. Your task is to write a function that detects if there is a cycle in this graph using Depth-First Search (DFS) methodology.
### Function Signature
```python
def is_in_cycle(graph: Dict[str, List[str]], traversal_states: Dict[str, TraversalS... | from typing import Dict, List
from enum import Enum
class TraversalState(Enum):
UNVISITED = 1
VISITING = 2
VISITED = 3
def is_in_cycle(graph: Dict[str, List[str]], traversal_states: Dict[str, TraversalState], vertex: str) -> bool:
# If the current vertex is being visited, a cycle is detected
if tr... | import pytest
from solution import contains_cycle, is_in_cycle
def test_contains_cycle_with_cycle():
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['F'],
'D': ['E', 'F'],
'E': ['B'],
'F': []
}
assert contains_cycle(graph) == True
def test_contains_cycle_withou... | [] | [
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 Dict, List\nfrom enum import Enum\n\nclass TraversalState(Enum):\n UNVISITED = 1\n VISITING = 2\n VISITED = 3\n\ndef is_in_cycle(g... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00024875",
"row_id": 24875,
"seed_ids": "[237]"
} | 0.593501 | Data_Structure_24875 | I | [
"is_in_cycle",
"contains_cycle"
] | 2 | [
[
"contains_cycle",
"is_in_cycle"
]
] | 1 | [] | false | [
"TraversalState"
] | true | pytest | true | [] | true | a4ee0eb42d0936c924eb1c323e00212b6879bf74 | b83a64e043e91891a5caf58a7b988fc35d36c2ef | |||
v1.0 | instruct | Data_Structure | Data_Structure_24916_I | ### Problem: Efficient Matrix Exponentiation and Multiplication
You are tasked with implementing a solution for efficiently computing powers of a given square matrix. The solution should also handle basic matrix multiplication and generation of an identity matrix.
#### Function 1: `multiply(matA: list, matB: list) ->... | def multiply(matA, matB):
"""
Multiplies two square matrices matA and matB.
"""
n = len(matA)
# Initialize result matrix with zeros
result = [[0] * n for _ in range(n)]
# Perform multiplication
for i in range(n):
for j in range(n):
for k in range(n):
... | from solution import multiply, identity, matrix_exponentiation
def test_multiply_2x2_matrices():
matA = [
[1, 2],
[3, 4]
]
matB = [
[2, 0],
[1, 2]
]
expected = [
[4, 4],
[10, 8]
]
assert multiply(matA, matB) == expected
def test_identity_3x3(... | [
{
"docstring": "Multiplies two square matrices matA and matB.",
"function_declaration": "def multiply(matA, matB):",
"function_name": "multiply",
"parameter_list": "(matA, matB)"
},
{
"docstring": "Returns the identity matrix of size n x n.",
"function_declaration": "def identity(n):",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply(matA, matB):\n \"\"\"\n Multiplies two square matrices matA and matB.\n \"\"\"\n n = len(matA)\n result = [[0] * n for _ in range(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024916",
"row_id": 24916,
"seed_ids": "[340]"
} | 0.52842 | Data_Structure_24916 | I | [
"multiply",
"identity",
"matrix_exponentiation"
] | 3 | [
[
"matrix_exponentiation",
"identity"
],
[
"matrix_exponentiation",
"multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 695ac80244a7dec1a93e4139b2408fcb4859feaf | 58f498a13ca36f1ee374e8d8dbb9ccd2993f2669 | |||
v1.0 | instruct | Data_Structure | Data_Structure_24938_I | **Scenario**: You are developing an optimized insertion sort algorithm for use in your software that processes small-sized or nearly sorted datasets. To boost efficiency, particularly in finding the correct insertion points, you decide to integrate a binary search approach.
**Task**: Implement a function `optimized_in... | from typing import List
def search_insert(arr: List[int], val: int, start: int, end: int) -> int:
"""
Performs binary search to find the index at which val should be inserted
to keep the array sorted from start to end.
"""
if start == end:
if arr[start] > val:
return start
... | def test_optimized_insertion_sort_single_element():
assert optimized_insertion_sort([1]) == [1]
def test_optimized_insertion_sort_sorted():
assert optimized_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_optimized_insertion_sort_reverse_sorted():
assert optimized_insertion_sort([5, 4, 3, 2, 1... | [
{
"docstring": "Performs binary search to find the index at which val should be inserted \nto keep the array sorted from start to end.",
"function_declaration": "def search_insert(arr, val, start, end):",
"function_name": "search_insert",
"parameter_list": "(arr, val, start, end)"
},
{
"docs... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(arr: List[int], left: int, right: int, key: int) -> int:\n \"\"\"\n Binary search to find the index to inse... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024938",
"row_id": 24938,
"seed_ids": "[199]"
} | 0.515145 | Data_Structure_24938 | I | [
"search_insert",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 12655683f7b14ddb587e4c0b5398c47e17fc78d5 | 4eb5342a6b3d42e5b9308af9c909481c0322c038 | |||
v1.0 | instruct | Data_Structure | Data_Structure_24982_I | Implement and Extend Caesar Cipher
#### Context
You have learned about the Caesar cipher and how it encrypts text by shifting characters. Now, as an exercise, you will implement the Caesar cipher and extend it to handle decryption as well.
#### Objective
Write functions to encrypt and decrypt text using the Caesar c... | def caesar_cipher_encrypt(s, k):
"""
Encrypts the input text s using Caesar cipher with a shift of k.
"""
encrypted_text = []
for char in s:
if char.isalpha():
base = ord('A') if char.isupper() else ord('a')
encrypted_char = chr((ord(char) - base + k) % 26 + base)
... | from solution import caesar_cipher_encrypt, caesar_cipher_decrypt
def test_caesar_cipher_encrypt():
assert caesar_cipher_encrypt('hello, World!', 3) == 'khoor, Zruog!'
assert caesar_cipher_encrypt('Example', 0) == 'Example'
assert caesar_cipher_encrypt('abc', -3) == 'xyz'
assert caesar_cipher_encrypt(... | [
{
"docstring": "Encrypts the input text s using Caesar cipher with a shift of k.",
"function_declaration": "def caesar_cipher_encrypt(s, k):",
"function_name": "caesar_cipher_encrypt",
"parameter_list": "(s, k)"
},
{
"docstring": "Decrypts the input text s using Caesar cipher with a shift of... | [
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 caesar_cipher_encrypt(s, k):\n \"\"\"\n Encrypt the given text using Caesar cipher with a shift of k.\n \n Parameters:\n s (str): The input... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024982",
"row_id": 24982,
"seed_ids": "[78]"
} | 0.692972 | Data_Structure_24982 | I | [
"caesar_cipher_encrypt",
"caesar_cipher_decrypt"
] | 2 | [
[
"caesar_cipher_decrypt",
"caesar_cipher_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ea05cfb3b6e9f9d82521fd61dee0d366e5ab5770 | 2c5c07367267fc2078c0fe57c4764359ccf2c93a | |||
v1.0 | instruct | Data_Structure | Data_Structure_24984_I | ### Question: Improved Insertion Sort
You are provided with a simple implementation of the Insertion Sort algorithm. Your task is to optimize the Insertion Sort implementation to use Binary Search to find the correct position to insert each element. This should improve the time complexity of insertions from O(n) to O(... | from typing import List
def binary_search(arr, val, start, end):
"""
Helper function to perform binary search.
Find the index where 'val' should be inserted to keep 'arr' sorted.
"""
if start == end:
if arr[start] > val:
return start
else:
return start + 1
... | from solution import binary_insertion_sort
def test_binary_insertion_sort_unsorted():
assert binary_insertion_sort([12, 4, 3, 8, 4]) == [3, 4, 4, 8, 12]
def test_binary_insertion_sort_sorted():
assert binary_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_binary_insertion_sort_reversed():
ass... | [
{
"docstring": "Helper function to perform binary search.\nFind the index where 'val' should be inserted to keep 'arr' sorted.",
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef binary_search(arr, val, start, end):\n \"\"\"\n Helper function to perform binary search.\n Find the index where 'val'... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00024984",
"row_id": 24984,
"seed_ids": "[7]"
} | 0.563092 | Data_Structure_24984 | I | [
"binary_search",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bf412c170b6aeb526133a5dbc4bcbd0c4fec0833 | 786de808af248f838770de401cf569db2a264857 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25019_I | ### Diffie-Hellman Key Exchange Coding Challenge
**Objective**: Implement a secure Diffie-Hellman key exchange, and related supporting functions, to facilitate encrypted communication over a public channel. Your implementation should include steps to check primality, compute Euler's Totient function, determine the ord... | def prime_check(num: int) -> bool:
"""
Verify if a number is a prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return F... | from solution import prime_check, euler_totient, find_order, find_primitive_root, diffie_hellman_key_exchange
def test_prime_check():
assert prime_check(7) == True
assert prime_check(4) == False
assert prime_check(2) == True
assert prime_check(1) == False
assert prime_check(0) == False
assert p... | [
{
"docstring": "Verify if a number is a prime.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Compute the Euler's Totient function for a given integer.",
"function_declaration": "def euler_totient(n):",
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import List\n\ndef prime_check(num: int) -> bool:\n \"\"\"\n Verify if a number is a prime.\n \"\"\"\n if num <= 1:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025019",
"row_id": 25019,
"seed_ids": "[146]"
} | 0.518431 | Data_Structure_25019 | I | [
"prime_check",
"euler_totient",
"find_order",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 5 | [
[
"diffie_hellman_key_exchange",
"prime_check"
],
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"find_order"
],
[
"find_primitive_root",
"prime_check"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 0af4c2b779c176fff395f2d48af57cae231a2a77 | 724de04c476ab4ae472cae5e61dc56ed3a8afaf5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25028_I | ### Question
You are required to implement the Radix Sort algorithm and validate its correctness and efficiency through the following tasks.
#### Task
Given an unsorted list of non-negative integers, implement the `radix_sort` function to sort the list in ascending order. Additionally, ensure your implementation hand... | def counting_sort(arr, exp, simulation):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[(index % 10)] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] // exp
... | from solution import radix_sort
def test_radix_sort_simple():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_empty():
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort([5]) == [5]
def test_radix_sort_all_sam... | [
{
"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": "def counting_sort(arr, exp, simulation):\n n = len(arr)\n output = [0] * n \n count = [0] * 10 \n\n for i in range(n):\n index = arr[i] // ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00025028",
"row_id": 25028,
"seed_ids": "[15]"
} | 0.623986 | Data_Structure_25028 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 67f605209f45392fcc1a99ba20e3522b53f2ce2f | de0609efd0ea990898176e856d2d6f9c8005ee23 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25041_I | ### Merge Sort Algorithm Implementation
Your task is to implement the Merge Sort algorithm to sort an array of integers. You need to write a function that divides the array into halves, recursively sorts each half, and then merges them back together in sorted order.
### Function Specification
#### Input
- `arr`: A li... | def merge_sort(arr):
""" Merge Sort implementation that sorts a list of integers.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
""" Helper function to me... | from solution import merge_sort
def test_merge_sort_example_1():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merge_sort_repeating_el... | [
{
"docstring": "Merge Sort implementation that sorts a list of integers.\n ",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Helper function to merge two sorted lists.\n ",
"function_declaration": "def mer... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\" Merge Sort implementation that sorts a list of integers.\n \"\"\"\n if len(arr) <= 1:\n return arr\n \n mi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025041",
"row_id": 25041,
"seed_ids": "[12]"
} | 0.633776 | Data_Structure_25041 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 83cda082718fc9c3c219957a6260771326fe543a | 50d174cdc5d757ac6c6e35a2a3ebe2520bbab7d8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25047_I | **RSA Encryption Algorithm Implementation and Validation**
### Objective
As a data security consultant, you are tasked with implementing the RSA encryption and decryption processes, along with a custom primality test and modular inverse function. You need to handle edge cases and ensure efficient computation for secu... | import random
from typing import Tuple
def is_prime(num: int) -> bool:
"""
Check whether the given number is a prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while (i * i) <= num:
if num %... | from solution import is_prime, modinv, generate_key, encrypt, decrypt, validate_rsa
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
def test_modinv():
... | [
{
"docstring": "Check whether the given number is a prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Calculate the modular multiplicative inverse of a modulo m using the extended Euclidean algorithm.",
"funct... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import Tuple\n\ndef is_prime(num: int) -> bool:\n \"\"\"\n Check whether the given number is a prime.\n \"\"\"\n if num... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00025047",
"row_id": 25047,
"seed_ids": "[154]"
} | 0.645737 | Data_Structure_25047 | I | [
"is_prime",
"modinv",
"generate_key",
"encrypt",
"decrypt",
"validate_rsa"
] | 6 | [
[
"generate_key",
"is_prime"
],
[
"generate_key",
"modinv"
],
[
"validate_rsa",
"decrypt"
],
[
"validate_rsa",
"encrypt"
],
[
"validate_rsa",
"generate_key"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 0dca7b049538be61c9c87f1b16721774b2d7bac5 | 44beab60a534dfb7816fc7b2ee1162d4377fb1d1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25082_I | Solve Congruences with Chinese Remainder Theorem
You are provided with `n` modular equations in the form:
\[ x \% nums[i] = rems[i] \]
where `i` ranges from `0` to `n-1`, and the integers in `nums` list are pairwise coprime. Your task is to implement a function that finds the smallest positive integer `x` that satis... | from typing import List
from functools import reduce
def solve_chinese_remainder(nums: List[int], rems: List[int]) -> int:
"""
Solves the system of congruences using the Chinese Remainder Theorem.
:param nums: List of pairwise coprime integers.
:param rems: List of remainders.
:return: Smalles... | from solution import solve_chinese_remainder
def test_solve_chinese_remainder_example():
nums = [3, 4, 5]
rems = [2, 3, 1]
assert solve_chinese_remainder(nums, rems) == 11
def test_solve_chinese_remainder_single_equation():
nums = [7]
rems = [3]
assert solve_chinese_remainder(nums, rems) == 3
... | [
{
"docstring": "Solves the system of congruences using the Chinese Remainder Theorem.\n\n:param nums: List of pairwise coprime integers.\n:param rems: List of remainders.\n:return: Smallest positive integer x that satisfies all given congruences.",
"function_declaration": "def solve_chinese_remainder(nums, ... | [
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 extended_gcd(a: int, b: int):\n \"\"\"\n Extended Euclidean Algorithm that returns gcd of a and b, and the coefficients o... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00025082",
"row_id": 25082,
"seed_ids": "[158]"
} | 0.609196 | Data_Structure_25082 | I | [
"solve_chinese_remainder",
"gcd"
] | 2 | [
[
"solve_chinese_remainder",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 962a14b9790c28ea12e058d9421eaceb8c7ab023 | 88f125bb2df8d5129b16c80b2680c6dad2ff04bb | |||
v1.0 | instruct | Data_Structure | Data_Structure_25095_I | ### Context
Imagine you are a software engineer working on optimizing a large-scale data processing system that leverages parallel computing. Your task is to implement and extend a sorting algorithm that is efficient in parallel environments.
### Problem Statement
You need to implement a bitonic sort algorithm that s... | import sys
from typing import List
def bitonic_merge(arr, low, cnt, reverse):
if cnt > 1:
k = cnt // 2
for i in range(low, low + k):
if reverse == (arr[i] > arr[i + k]):
arr[i], arr[i + k] = arr[i + k], arr[i]
bitonic_merge(arr, low, k, reverse)
bitonic_m... | from solution import extended_bitonic_sort
def test_bitonic_sort_empty():
assert extended_bitonic_sort([]) == []
def test_bitonic_sort_single_element():
assert extended_bitonic_sort([42]) == [42]
def test_bitonic_sort_power_of_two_increasing():
assert extended_bitonic_sort([12, 4, 78, 22]) == [4, 12, 22,... | [
{
"docstring": null,
"function_declaration": "def bitonic_merge(arr, low, cnt, reverse):",
"function_name": "bitonic_merge",
"parameter_list": "(arr, low, cnt, reverse)"
},
{
"docstring": null,
"function_declaration": "def bitonic_sort_recursive(arr, low, cnt, reverse):",
"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": "from typing import List\nimport sys\n\ndef bitonic_sort_up(arr: List[int]) -> None:\n \"\"\"Helper function to perform a bitonic sort in ascending order.\"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025095",
"row_id": 25095,
"seed_ids": "[17]"
} | 0.582695 | Data_Structure_25095 | I | [
"bitonic_merge",
"bitonic_sort_recursive",
"nearest_power_of_two",
"extended_bitonic_sort"
] | 4 | [
[
"bitonic_sort_recursive",
"bitonic_merge"
],
[
"extended_bitonic_sort",
"bitonic_sort_recursive"
],
[
"extended_bitonic_sort",
"nearest_power_of_two"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 88c72fbf90222c828294861e9c6519d1a67b75ee | 97947766b3bce10bdef627d110532dd299ad317c | |||
v1.0 | instruct | Data_Structure | Data_Structure_25134_I | ### Question: Calculate Cosine Similarity Between Multiple Pairs of Vectors
You are tasked with writing a function to compute the cosine similarity between multiple pairs of vectors efficiently. Specifically, you need to implement a function that computes cosine similarity for each pair of vectors provided in two list... | import math
def cosine_similarity(vecA, vecB):
"""
Calculate the cosine similarity between two vectors.
"""
dot_product = sum(a * b for a, b in zip(vecA, vecB))
normA = math.sqrt(sum(a * a for a in vecA))
normB = math.sqrt(sum(b * b for b in vecB))
if normA == 0 or normB == 0:
retur... | def test_batch_cosine_similarity():
vectorsA = [[1, 1, 1], [1, 2, 3]]
vectorsB = [[1, 2, -1], [-1, -2, -3]]
result = batch_cosine_similarity(vectorsA, vectorsB)
assert result == [0.47140452079103173, -1.0], f"Expected [0.47140452079103173, -1.0] but got {result}"
def test_zero_vector():
vectorsA = ... | [
{
"docstring": "Calculate the cosine similarity between two vectors.",
"function_declaration": "def cosine_similarity(vecA, vecB):",
"function_name": "cosine_similarity",
"parameter_list": "(vecA, vecB)"
},
{
"docstring": "Calculate cosine similarity for each pair of vectors from vectorsA an... | [
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 math\n\ndef batch_cosine_similarity(vectorsA: List[List[float]], vectorsB: List[List[float]]) -> List[float]:\n def cosine_... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00025134",
"row_id": 25134,
"seed_ids": "[149]"
} | 0.557037 | Data_Structure_25134 | I | [
"cosine_similarity",
"batch_cosine_similarity"
] | 2 | [
[
"batch_cosine_similarity",
"cosine_similarity"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 06edfbbbea5546ffe806dc8e3b96ef3a570f859a | 6cc294ab1ddce921106b42c78582244ac887bc22 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25166_I | ### Question: Enhanced Text Pattern Matching with Additional Conditions
You are asked to implement an enhanced version of the Knuth-Morris-Pratt algorithm. Besides finding all occurrences of a pattern in a given text, our enhanced function should also return an indication if the pattern is overlapped at any position.
... | from typing import List, Tuple
def compute_lps(pattern: str) -> List[int]:
""" Helper function to compute the longest prefix suffix (LPS) array """
length = 0
lps = [0] * len(pattern)
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
lps[i]... | from solution import enhanced_knuth_morris_pratt
def test_pattern_at_multiple_positions():
assert enhanced_knuth_morris_pratt('ababcababc', 'ababc') == ([0, 5], False)
def test_overlapping_patterns():
assert enhanced_knuth_morris_pratt('aaaaaa', 'aaa') == ([0, 1, 2, 3], True)
def test_no_occurrences():
a... | [
{
"docstring": "Helper function to compute the longest prefix suffix (LPS) array ",
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": null,
"function_declaration": "def enhanced_knuth_morris_pratt(text, pa... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_knuth_morris_pratt(text, pattern):\n \"\"\"\n Enhanced KMP algorithm that finds all occurrences of a pattern in a text and also detects ove... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025166",
"row_id": 25166,
"seed_ids": "[93]"
} | 0.608904 | Data_Structure_25166 | I | [
"compute_lps",
"enhanced_knuth_morris_pratt"
] | 2 | [
[
"enhanced_knuth_morris_pratt",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bd6c3c3f1b03f0b1e451f95eb7d5e9ed29440ee3 | 1a5b15207ad38fae756087bb2cb165d98ce109cb | |||
v1.0 | instruct | Data_Structure | Data_Structure_25195_I | ### Word Squares Generation
Given a list of words (without duplicates), you need to find all the possible word squares that can be formed. A valid word square is a sequence of words where the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).
### Definitions:
- A word square is an ... | from collections import defaultdict
def build_prefix_dict(words):
prefix_dict = defaultdict(list)
for word in words:
for i in range(len(word)):
prefix_dict[word[:i+1]].append(word)
return prefix_dict
def backtrack(step, word_len, solution, results, prefix_dict):
if step == word_len... | from solution import find_word_squares
def test_example():
words = ["area", "lead", "wall", "lady", "ball"]
expected_output = [
["wall", "area", "lead", "lady"],
["ball", "area", "lead", "lady"]
]
result = find_word_squares(words)
assert sorted(result) == sorted(expected_output)
de... | [
{
"docstring": null,
"function_declaration": "def build_prefix_dict(words):",
"function_name": "build_prefix_dict",
"parameter_list": "(words)"
},
{
"docstring": null,
"function_declaration": "def backtrack(step, word_len, solution, results, prefix_dict):",
"function_name": "backtrac... | [
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.words = []\n\nclass Trie:\n def __init__(self):\n self.root = Tri... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00025195",
"row_id": 25195,
"seed_ids": "[87]"
} | 0.590625 | Data_Structure_25195 | I | [
"build_prefix_dict",
"backtrack",
"find_word_squares"
] | 3 | [
[
"find_word_squares",
"backtrack"
],
[
"find_word_squares",
"build_prefix_dict"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 690c1f980b2476781c3ec6ae1502cf348f63b2b6 | ba2d0314af60abde0adadb2598a14e8013545adc | |||
v1.0 | instruct | Data_Structure | Data_Structure_25211_I | **Bucket Sort Implementation**
### Task
Implement the `enhanced_bucket_sort(arr, num_buckets)` function that performs the bucket sort using a more efficient sorting algorithm (e.g., mergesort) for sorting within each bucket.
### Input
- `arr`: a list of non-negative integers to be sorted.
- `num_buckets`: an integer ... | def enhanced_bucket_sort(arr, num_buckets=10):
"""
Perform bucket sort using optimized sorting within each bucket.
:param arr: List of non-negative integers to be sorted.
:param num_buckets: Number of buckets to be used for sorting.
:return: Sorted list of integers.
"""
if len(arr) <= 1... | from solution import enhanced_bucket_sort
def test_enhanced_bucket_sort_empty_list():
assert enhanced_bucket_sort([]) == []
def test_enhanced_bucket_sort_single_element():
assert enhanced_bucket_sort([5]) == [5]
def test_enhanced_bucket_sort_sorted_list():
assert enhanced_bucket_sort([1, 2, 3, 4, 5]) == ... | [
{
"docstring": "Perform bucket sort using optimized sorting within each bucket.\n\n:param arr: List of non-negative integers to be sorted.\n:param num_buckets: Number of buckets to be used for sorting.\n:return: Sorted list of integers.",
"function_declaration": "def enhanced_bucket_sort(arr, num_buckets=10... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_bucket_sort(arr, num_buckets=10):\n \"\"\"\n Perform bucket sort using optimized sorting within each bucket.\n \n :param arr: List of... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00025211",
"row_id": 25211,
"seed_ids": "[26]"
} | 0.538311 | Data_Structure_25211 | I | [
"enhanced_bucket_sort",
"merge_sort",
"merge"
] | 3 | [
[
"enhanced_bucket_sort",
"merge_sort"
],
[
"merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5a2b5e3549360c35c14dbc2b9afd770008eb4538 | 0c435ef8ba118b50a0f7d7afa033b4f574df7f75 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25212_I | ### RSA Key Generation and Encryption/Decryption
You are tasked with building an encryption and decryption system based on the RSA algorithm. The provided implementation details for the RSA key generation algorithm, encryption, and decryption have been shared. Your task is to implement these following the guidelines b... | import random
from sympy import isprime, mod_inverse
def generate_prime_candidate(bits):
""" Generate an odd integer randomly """
p = random.getrandbits(bits)
while p % 2 == 0:
p = random.getrandbits(bits)
return p
def generate_prime_number(bits):
""" Generate a prime number of bit length ... | from solution import rsa_key_gen_and_crypto
def test_valid_key_and_data():
k = 16
data = 20
result = rsa_key_gen_and_crypto(k, data, seed=42)
n, e, d, encrypted_data, decrypted_data = result
assert decrypted_data == data
def test_minimum_bit_length():
k = 16
data = 15
result = rsa_key_... | [
{
"docstring": "Generate an odd integer randomly ",
"function_declaration": "def generate_prime_candidate(bits):",
"function_name": "generate_prime_candidate",
"parameter_list": "(bits)"
},
{
"docstring": "Generate a prime number of bit length bits ",
"function_declaration": "def generat... | [
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 gcd(a, b):\n while b != 0:\n a, b = b, a % b\n return a\n\ndef modinv(a, m):\n m0, x0, x1 = m, 0, 1\n if m == 1:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025212",
"row_id": 25212,
"seed_ids": "[154]"
} | 0.722305 | Data_Structure_25212 | I | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key",
"encrypt",
"decrypt",
"rsa_key_gen_and_crypto"
] | 6 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
],
[
"rsa_key_gen_and_crypto",
"decrypt"
],
[
"rsa_key_gen_and_crypto",
"encrypt"
],
[
"rsa_key_gen_and_crypto",
"generate_key"
]
] | 5 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | d4abbfc63aa5bbf183f5a5cc6144c23f3f1058d3 | 4e4bbbbce44262b7e49302c21f2509ca4d616a76 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25217_I | Your task is to implement a sorting algorithm based on the concept of **bucket sort**. You will need to distribute the elements of an array into separate "buckets", sort each bucket, and then concatenate these buckets to produce the final sorted array. For the purpose of sorting the individual buckets, you will use the... | from typing import List
def insertion_sort(arr: List[float]) -> List[float]:
"""
A simple implementation of insertion sort.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1... | from solution import bucket_sort
def test_bucket_sort_example_cases():
assert bucket_sort([0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]) == [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
assert bucket_sort([0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51]) == [0.23, 0.25, 0.32, 0.42, 0.47... | [
{
"docstring": "A simple implementation of insertion sort.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts a list of float numbers in the range [0, 1) using bucket sort.",
"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": "from typing import List\n\ndef insertion_sort(arr: List[float]) -> List[float]:\n \"\"\"\n Helper function to perform insertion sort on a list.\n \"\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025217",
"row_id": 25217,
"seed_ids": "[26]"
} | 0.59622 | Data_Structure_25217 | I | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d487a62c1d8e20a764f24b1a10eac26f9e888c76 | deaeb5cdb9837baeafad38a854db0c4afc0d6a6f | |||
v1.0 | instruct | Data_Structure | Data_Structure_25234_I | ### Bogo Sorting Challenge
**Context**: You have been assigned to demonstrate the inefficiencies of certain theoretical sorting algorithms. One such example is Bogo Sort, a highly inefficient and impractical sorting algorithm.
### Problem Statement
Implement the function `bogo_sort` that sorts an array of integers us... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr: List[int], simulation: bool = False) -> List[i... | from solution import is_sorted, bogo_sort
def test_is_sorted():
assert is_sorted([1, 2, 3, 4, 5]) == True
assert is_sorted([5, 1, 2, 3, 4]) == False
assert is_sorted([]) == True
assert is_sorted([1]) == True
assert is_sorted([2, 2, 2]) == True
def test_bogo_sort_empty_array():
assert bogo_sort... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts an array of integers using the highly inefficient Bogo Sort algorithm.\nIf 'simulation' is True, ... | [
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 bogo_sort(arr: List[int], simulation: bool = False) -> List[int]:\n def is_sorted(arr: List[int]) -> bool:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025234",
"row_id": 25234,
"seed_ids": "[16]"
} | 0.562646 | Data_Structure_25234 | I | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ad6509f40210b3755e2b3105c6efd5c9e35a9fe | a5b66fa40ea56f4dc26e2b249968518694c15bed | |||
v1.0 | instruct | Data_Structure | Data_Structure_25247_I | You have been given the task to implement a function that sorts an array of non-negative integers using a non-comparative radix sorting algorithm.
### Function Signature
```python
def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
```
### Input
* `arr`: A list of non-negative integers.
* `simulati... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool) -> None:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
... | from solution import radix_sort
def test_radix_sort():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
assert radix_sort([1, 10, 1000, 100, 10000]) == [1, 10, 100, 1000, 10000]
assert radix_sort([5, 3, 7, 8, 2, 1, 4, 6]) == [1, 2, 3, 4, 5, 6, 7, 8]
assert radix... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool) -> None:\n n = len(arr)\n output = [0] * n \n count = [0] * ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00025247",
"row_id": 25247,
"seed_ids": "[15]"
} | 0.669168 | Data_Structure_25247 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 890ce35b057ee3edaef4f06889e4f2dac612d2ec | 76854977427810a1cfceddfcf566ead85bd51d7b | |||
v1.0 | instruct | Data_Structure | Data_Structure_25249_I | ### Question
You are given two binary trees `s` and `t`. Implement a function `is_subtree(s, t)` to check if `t` is a subtree of `s`. A subtree of a tree `t` is a tree consisting of a node in `t` and all of its descendants in `t`.
### Function Signature
```python
def is_subtree(big, small):
pass
```
### Expected... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big, small):
if not small:
return True
if not big:
return False
if are_identical(big, small):
return True
return is_sub... | from solution import TreeNode, is_subtree
def test_is_subtree_example_1():
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.left.right = TreeNode(2)
t = TreeNode(4)
t.left = TreeNode(1)
t.right = TreeNode(2)
assert is_subtree(s, t) == True... | [] | [
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": "class TreeNode:\n \"\"\"\n Definition for a binary tree node.\n \"\"\"\n def __init__(self, val=0, left=None, right=None):\n self.val = val... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025249",
"row_id": 25249,
"seed_ids": "[288]"
} | 0.539169 | Data_Structure_25249 | I | [
"is_subtree",
"are_identical"
] | 2 | [
[
"is_subtree",
"are_identical"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | e2b09830989df268a8219025992a4a1b7a89a7bc | 10f4e5c4f20c5c446fb9341bf38e6b222b476be0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25291_I | #### Context
You are tasked with designing a more efficient insertion sort algorithm by utilizing binary search to find the insertion point quickly. This improvement helps reduce the time complexity of finding the insertion point from O(n) to O(log n) for each insertion, achieving overall better performance.
#### Prob... | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Find the index where `val` should be inserted to maintain sorted order.
Uses binary search to determine the insertion point.
"""
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low... | from solution import optimized_insertion_sort
def test_optimized_insertion_sort():
assert optimized_insertion_sort([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12]
assert optimized_insertion_sort([1, 3, 5, 7, 9, 2, 4, 6, 8]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
assert optimized_insertion_sort([]) == []
... | [
{
"docstring": "Find the index where `val` should be inserted to maintain sorted order.\nUses binary search to determine the insertion point.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "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 search_insert(array: List[int], val: int) -> int:\n low, high = 0, len(array) - 1\n while low <= high:\n mid = low... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025291",
"row_id": 25291,
"seed_ids": "[199]"
} | 0.562802 | Data_Structure_25291 | I | [
"search_insert",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f56aef6de57863f19d349b954943e3164bfa77be | 3618b9bdad775dba80ba58c532ac5b050cc8a183 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25295_I | **Context**:
You have been hired to help develop a simple recommendation system for a small online retailer. This retailer assigns a feature vector to each product based on user reviews and other metrics. Each feature vector is stored in a dictionary where the key is the tuple representing the feature vector and the va... | import math
def distance(x, y):
assert len(x) == len(y), "The vectors must have the same length"
sum = 0
for i in range(len(x)):
sum += (x[i] - y[i]) ** 2
return math.sqrt(sum)
def recommend_product(x: tuple, feature_vectors: dict) -> str:
min_distance = float('inf')
recommended_produc... | from solution import recommend_product, distance
def test_distance():
assert distance((1.0, 2.0), (1.0, 2.0)) == 0.0
assert distance((1.0, 2.0), (2.0, 3.0)) == math.sqrt(2)
assert distance((3.0, 4.0), (0.0, 0.0)) == 5.0
def test_recommend_product():
feature_vectors = {
(1.0, 2.0): "Product1",
... | [
{
"docstring": null,
"function_declaration": "def distance(x, y):",
"function_name": "distance",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def recommend_product(x, feature_vectors):",
"function_name": "recommend_product",
"parameter_list": "(x, f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(x, y):\n assert len(x) == len(y), \"The vectors must have the same length\"\n sum = 0\n for i in range(len(x)):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025295",
"row_id": 25295,
"seed_ids": "[260]"
} | 0.575558 | Data_Structure_25295 | I | [
"distance",
"recommend_product"
] | 2 | [
[
"recommend_product",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cb5873a2570115f52d711ef5c62b8073d1f4fba8 | f8ec0f130941fa20ac8853dbac5a711d0a02d731 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25330_I | ### Question:
#### Problem Statement
You are tasked with implementing a function named `solve_diophantine(a, b, c)` that takes three integers `a`, `b`, and `c` as inputs, and returns a tuple `(x, y, gcd)` such that `a * x + b * y = gcd` where `gcd` is the greatest common divisor of `a` and `b`. Additionally, ensure th... | def extended_gcd(a, b):
"""
Apply the extended Euclidean algorithm to find x, y such that:
a * x + b * y = gcd(a, b)
Returns a tuple (gcd, x, y) where gcd is the greatest common divisor of a and b,
and x, y are the coefficients such that a * x + b * y = gcd.
"""
if b == 0:
return a, ... | from solution import solve_diophantine
def test_solve_diophantine_positive():
x, y, g = solve_diophantine(30, 20, 10)
assert 30 * x + 20 * y == 10
assert g == 10
def test_solve_diophantine_another_positive():
x, y, g = solve_diophantine(35, 15, 5)
assert 35 * x + 15 * y == 5
assert g == 5
def... | [
{
"docstring": "Apply the extended Euclidean algorithm to find x, y such that:\na * x + b * y = gcd(a, b)\nReturns a tuple (gcd, x, y) where gcd is the greatest common divisor of a and b,\nand x, y are the coefficients such that a * x + b * y = gcd.",
"function_declaration": "def extended_gcd(a, b):",
"... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def extended_gcd(a, b):\n \"\"\"\n Apply the extended Euclidean algorithm to find x, y such that:\n a * x + b * y = gcd(a, b)\n Returns a tuple (g... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00025330",
"row_id": 25330,
"seed_ids": "[161]"
} | 0.589328 | Data_Structure_25330 | I | [
"extended_gcd",
"solve_diophantine"
] | 2 | [
[
"solve_diophantine",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8bbf703f80580d5c029d0bfa60b4d5627164cc95 | f31938f5ff9c8c9321c44ccd61e2b2c8cf0b540a | |||
v1.0 | instruct | Data_Structure | Data_Structure_25416_I | ### Question: Optimal Network Wiring with Minimum Spanning Tree
You are tasked with designing the most cost-effective way to lay down electrical wires to connect a set of buildings. The connections between buildings are represented as a weighted, undirected graph where nodes represent buildings and edges represent pos... | from typing import List, Tuple
def find(parent, i):
if parent[i] == i:
return i
else:
return find(parent, parent[i])
def union(parent, rank, x, y):
rootX = find(parent, x)
rootY = find(parent, y)
if rootX != rootY:
if rank[rootX] > rank[rootY]:
parent[rootY] = r... | from solution import minimum_spanning_tree
def test_example_case():
edges = [(0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4)]
assert minimum_spanning_tree(4, edges) == 19
def test_disconnected_graph():
edges = [(0, 1, 1), (2, 3, 2)]
assert minimum_spanning_tree(4, edges) == -1
def test_single... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
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, Tuple\n\nclass DisjointSet:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [0] * n\n \n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025416",
"row_id": 25416,
"seed_ids": "[230]"
} | 0.793999 | Data_Structure_25416 | I | [
"find",
"union",
"minimum_spanning_tree"
] | 3 | [
[
"minimum_spanning_tree",
"find"
],
[
"minimum_spanning_tree",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 74883571e74b3be31a17bbd6b670a00e51deffbb | 522acfa94c541e4789a4cd62d24c1dfc8a611aa3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25430_I | ### Bogo Sort Implementation and Analysis
#### Problem Statement
You are tasked to implement the Bogo Sort algorithm as described in the analysis above. The Bogo Sort algorithm checks if the given array is sorted, and if not, it shuffles the array randomly until it is sorted.
Your implementation must use the followin... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr, simulation=False):
"""
Function to sort the array using Bogo Sort.
"""
it... | from solution import bogo_sort
import pytest
def test_bogo_sort_sorted_array():
assert bogo_sort([1, 2, 3]) == [1, 2, 3]
def test_bogo_sort_unsorted_array():
assert bogo_sort([3, 1, 2]) == [1, 2, 3]
def test_bogo_sort_single_element():
assert bogo_sort([1]) == [1]
def test_bogo_sort_empty_array():
a... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Function to sort the array using Bogo Sort.",
"function_declaration": "def bogo_sort(arr, simulatio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if an array is sorted.\n \"\"\"\n for i in range(len(arr) - 1):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025430",
"row_id": 25430,
"seed_ids": "[16]"
} | 0.559757 | Data_Structure_25430 | I | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 285e631516dca576b0091a99c0513d8550b57274 | 559fd1d5da122579743429c1886a444c99e982fd | |||
v1.0 | instruct | Data_Structure | Data_Structure_25441_I | ## Coding Assessment Question
### Scenario
You are tasked with designing software for a company's file version control system. The system saves snapshots of different versions of the entire file directory tree structure. You need to implement a function that efficiently determines whether a saved snapshot (subtree) is... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
if not s:
return False
if is_same_tree(s, t):
return True
return is_subtree(s.left, t) or is_sub... | import pytest
from solution import TreeNode, is_subtree, is_same_tree
def test_is_subtree_true_case():
# Tree s: 3
# / \
# 4 5
# / \
# 1 2
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.le... | [] | [
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": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025441",
"row_id": 25441,
"seed_ids": "[288]"
} | 0.586384 | Data_Structure_25441 | I | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 9e546f60640cda05a299bedd5d85cba716bcc51e | acccb16902bd8097caa48def2dd1f03a34486f1d | |||
v1.0 | instruct | Data_Structure | Data_Structure_25447_I | ### Question: Implement and Test Radix Sort Algorithm
#### Scenario
You are given a list of non-negative integers that need to be sorted efficiently. Your task is to write a function `radix_sort` that sorts this list using the Radix Sort algorithm. The function should also have a simulation mode to output the intermed... | def counting_sort(arr, exp, simulation, iteration):
n = len(arr)
output = [0] * n # output array
count = [0] * 10 # count array for digits 0-9
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
... | from solution import radix_sort
def test_radix_sort_example():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66], simulation=False) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_empty():
assert radix_sort([], simulation=False) == []
def test_radix_sort_single_element():
assert radix_sort([1]... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation, iteration):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation, iteration)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"funct... | [
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 counting_sort_for_radix(arr, exp, simulation, iteration):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # Store count of occurrence... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025447",
"row_id": 25447,
"seed_ids": "[15]"
} | 0.571924 | Data_Structure_25447 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 30088214a33c0c5c5c35007249ec86d0950adcc4 | 7e62ed81075b8292dfb62b58bc9a71a3b168257a | |||
v1.0 | instruct | Data_Structure | Data_Structure_25488_I | ### Question: Advanced Greatest Common Divisor Calculation
#### Context
In number theory and various applications of computing, finding the greatest common divisor (GCD) and least common multiple (LCM) of two integer numbers is a frequent operation. These operations are fundamental in simplifying fractions, solving Di... | def gcd_bitwise(a, b):
"""
Compute the greatest common divisor (GCD) using bitwise operations.
Args:
a (int): First non-negative integer.
b (int): Second non-negative integer.
Returns:
int: The GCD of a and b.
Raises:
ValueError: If both a and b are zer... | from solution import gcd_bitwise, lcm, optimized_trailing_zero
import pytest
def test_gcd_bitwise():
# Test cases from examples
assert gcd_bitwise(48, 18) == 6
assert gcd_bitwise(0, 6) == 6
# Additional test cases
assert gcd_bitwise(17, 0) == 17
assert gcd_bitwise(101, 103) == 1
assert gcd_... | [
{
"docstring": "Compute the greatest common divisor (GCD) using bitwise operations.\n\nArgs:\n a (int): First non-negative integer.\n b (int): Second non-negative integer.\n\nReturns:\n int: The GCD of a and b.\n\nRaises:\n ValueError: If both a and b are zero.",
"function_declaration": "def gcd... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd_bitwise(a, b):\n \"\"\"\n Computes the greatest common divisor using bitwise operations.\n \"\"\"\n if a == 0 and b == 0:\n raise V... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025488",
"row_id": 25488,
"seed_ids": "[166]"
} | 0.672909 | Data_Structure_25488 | I | [
"gcd_bitwise",
"lcm",
"optimized_trailing_zero"
] | 3 | [
[
"lcm",
"gcd_bitwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7bbb59dafead8bfad33d90fb5e0e5d748f2297ce | 93f4229537e071bd279898bd678aa33fd8d8c10d | |||
v1.0 | instruct | Data_Structure | Data_Structure_25500_I | ### Coding Challenge
You are provided with a binary tree node class `TreeNode` and two functions `serialize` and `deserialize`.
1. **TreeNode class**:
```python
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
```
2. **serialize function**:
... | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def serialize(root):
def build_string(node):
if node:
vals.append(str(node.val))
build_string(node.left)
build_string(node.right)
else:
... | from solution import TreeNode, serialize, deserialize, is_serialization_correct
def test_is_serialization_correct_single_node():
root = TreeNode(1)
assert is_serialization_correct(root) == True
def test_is_serialization_correct_full_tree():
# Tree:
# 1
# / \
# 2 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": "class TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\ndef serialize(root):\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00025500",
"row_id": 25500,
"seed_ids": "[330]"
} | 0.562214 | Data_Structure_25500 | I | [
"serialize",
"deserialize",
"is_serialization_correct"
] | 3 | [
[
"is_serialization_correct",
"deserialize"
],
[
"is_serialization_correct",
"serialize"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | b8ef56c2d6d3a7d80a633ab989b1f56a09b704e8 | 9064ba19c063f5ffe2ef4695768ce6f65970886e | |||
v1.0 | instruct | Data_Structure | Data_Structure_25573_I | ## Maximum Flow Problem: Augmenting Path Algorithm Using BFS
### Background:
You are given a network of pipelines that transport water between interconnected reservoirs. Each connection can be represented as an edge with a specific capacity. You need to determine the maximum amount of water that can flow from the init... | from collections import deque
def bfs_find_augmenting_path(residual_graph, source, sink, parent):
visited = [False] * len(residual_graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(residual_graph[u]):
... | from solution import maximum_flow_bfs
def test_simple_case():
graph = [
[0, 1],
[0, 0]
]
assert maximum_flow_bfs(graph) == 1
def test_medium_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
... | [
{
"docstring": null,
"function_declaration": "def bfs_find_augmenting_path(residual_graph, source, sink, parent):",
"function_name": "bfs_find_augmenting_path",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow_bf... | [
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 bfs(residual_graph, source, sink, parent):\n visited = set()\n queue = [source]\n\n while queue:\n u = queue.pop(0)\n if u == sink:... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025573",
"row_id": 25573,
"seed_ids": "[229]"
} | 0.60968 | Data_Structure_25573 | I | [
"bfs_find_augmenting_path",
"maximum_flow_bfs"
] | 2 | [
[
"maximum_flow_bfs",
"bfs_find_augmenting_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c6b4d77022be5c00efd21030829d7610406006d3 | a34637e2a8efcba4cdf60b21f233e6a082563fa7 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25584_I | ### Question
**Merge Sort with In-Place Merge**
You are required to implement the Merge Sort algorithm but with an in-place merge operation to reduce auxiliary space usage.
#### Requirements:
- Implement the `inplace_merge_sort` function, which sorts an array in ascending order.
- The sorting function should leverag... | def inplace_merge(arr, start, mid, end):
"""
Merges two sorted subarrays of arr in place.
"""
start2 = mid + 1
# If the direct merge is already sorted
if arr[mid] <= arr[start2]:
return
while start <= mid and start2 <= end:
if arr[start] <= arr[start2]:
star... | from solution import inplace_merge_sort
def test_empty_array():
assert inplace_merge_sort([]) == []
def test_single_element_array():
assert inplace_merge_sort([1]) == [1]
def test_sorted_array():
assert inplace_merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert in... | [
{
"docstring": "Merges two sorted subarrays of arr in place.",
"function_declaration": "def inplace_merge(arr, start, mid, end):",
"function_name": "inplace_merge",
"parameter_list": "(arr, start, mid, end)"
},
{
"docstring": null,
"function_declaration": "def inplace_merge_sort_helper(a... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def inplace_merge(arr, start, mid, end):\n \"\"\"\n Helper function to merge two sorted halves of an array `arr` in-place.\n \n Parameters:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025584",
"row_id": 25584,
"seed_ids": "[12]"
} | 0.615201 | Data_Structure_25584 | I | [
"inplace_merge",
"inplace_merge_sort_helper",
"inplace_merge_sort"
] | 3 | [
[
"inplace_merge_sort",
"inplace_merge_sort_helper"
],
[
"inplace_merge_sort_helper",
"inplace_merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6143f129b64ddeae38633d4442dac731d8d37622 | 65bfaa5e338e0a3e7f7bf4de2b145954abd5bc59 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25588_I | ### Nearest Neighbor Classification
You are working on a pattern recognition system that uses the nearest neighbor algorithm to classify points in a two-dimensional space. You need to implement the `nearest_neighbor` function that will classify the new point based on the closest point in the training set.
#### Input:... | import math
def distance(x, y):
"""
Computes the Euclidean distance between two points x and y.
"""
return math.sqrt(sum((xi - yi) ** 2 for xi, yi in zip(x, y)))
def nearest_neighbor(x, tSet):
"""
Finds the label of the nearest neighbor for a given point x in the training set tSet.
"""
... | from solution import distance, nearest_neighbor
def test_distance_same_point():
assert distance((0, 0), (0, 0)) == 0
def test_distance_different_points():
assert distance((0, 0), (3, 4)) == 5
assert distance((1, 1), (4, 5)) == 5
assert distance((2, 3), (5, 7)) == 5
def test_nearest_neighbor_single_po... | [
{
"docstring": "Computes the Euclidean distance between two points x and y.",
"function_declaration": "def distance(x, y):",
"function_name": "distance",
"parameter_list": "(x, y)"
},
{
"docstring": "Finds the label of the nearest neighbor for a given point x in the training set tSet.",
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(x, y):\n \"\"\"\n Calculate the Euclidean distance between two points x and y.\n \"\"\"\n return math.sqrt(sum((xi - y... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025588",
"row_id": 25588,
"seed_ids": "[260]"
} | 0.681826 | Data_Structure_25588 | I | [
"distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1ca5e9c7af114a88d501d775e1fef0b8f5a15ae1 | ca0741f1c20c5c625ddbdf4ef57fe2b0a376f342 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25593_I | You are tasked with implementing a function to calculate the factorial of a non-negative integer using an optimized approach that avoids large intermediate values directly during computation, particularly under modulus. Your function should be optimized for handling inputs where `n` and `mod` are significantly large.
... | def optimized_factorial(n, mod):
"""
Returns n! % mod using an optimized approach.
"""
result = 1
for i in range(2, n + 1):
result = (result * i) % mod
return result
def factorial_traditional(n):
"""
Returns n! using the traditional recursive approach.
"""
if n == 0 or n... | from solution import optimized_factorial, compare_factorials, factorial_traditional
def test_optimized_factorial_small():
assert optimized_factorial(5, 13) == 3 # 5! % 13 == 120 % 13 == 3
def test_optimized_factorial_large():
assert optimized_factorial(100, 1000000007) == 437918130 # Known result
def test_... | [
{
"docstring": "Returns n! % mod using an optimized approach.",
"function_declaration": "def optimized_factorial(n, mod):",
"function_name": "optimized_factorial",
"parameter_list": "(n, mod)"
},
{
"docstring": "Returns n! using the traditional recursive approach.",
"function_declaration... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_factorial(n, mod):\n \"\"\"\n Calculate n! % mod using an optimized approach.\n \"\"\"\n if n == 0 or n == 1:\n return 1\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025593",
"row_id": 25593,
"seed_ids": "[139]"
} | 0.600908 | Data_Structure_25593 | I | [
"optimized_factorial",
"factorial_traditional",
"compare_factorials"
] | 3 | [
[
"compare_factorials",
"factorial_traditional"
],
[
"compare_factorials",
"optimized_factorial"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9d728b3e507dd1eeabc4f7b010e3fa3c434b7f09 | 1ab119e1669bdcb7e7331ed397867f2bd377d5a1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25615_I | ### Coding Problem: Implement a Bottom-Up Merge Sort
#### Problem Description
You have been tasked with implementing a bottom-up (iterative) version of the Merge Sort algorithm. Bottom-up merge sort does not use recursion; instead, it iteratively handles subarrays of increasing size to sort the entire array.
#### Cor... | def bottom_up_merge_sort(arr):
"""
Sorts the array using the bottom-up merge sort algorithm.
"""
if not arr or len(arr) == 1:
return arr
n = len(arr)
# Temporary array for merging
temp_arr = [0]*n
# Size represents the size of the subarrays to be merged
size = 1
while s... | from solution import bottom_up_merge_sort
def test_bottom_up_merge_sort_empty():
assert bottom_up_merge_sort([]) == []
def test_bottom_up_merge_sort_single_element():
assert bottom_up_merge_sort([1]) == [1]
def test_bottom_up_merge_sort_sorted():
assert bottom_up_merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, ... | [
{
"docstring": "Sorts the array using the bottom-up merge sort algorithm.",
"function_declaration": "def bottom_up_merge_sort(arr):",
"function_name": "bottom_up_merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted halves of the array.",
"function_declaration": "de... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bottom_up_merge_sort(arr):\n \"\"\"\n Performs a bottom-up merge sort on the input array arr.\n \n :param arr: List of integers to be sorted\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025615",
"row_id": 25615,
"seed_ids": "[12]"
} | 0.612894 | Data_Structure_25615 | I | [
"bottom_up_merge_sort",
"merge"
] | 2 | [
[
"bottom_up_merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e3451277d7fdf186f82bb311a478fdf50f1d3bb9 | c74bafc4f23c73a787ff1a066ba426bf36353764 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25639_I | ### Secure Key Exchange with Diffie-Hellman Algorithm
In this task, you are required to implement a simplified version of the Diffie-Hellman Key Exchange algorithm to securely exchange a secret key between two parties. Your task involves checking the necessary conditions and performing the key exchange steps involving... | import random
def is_prime(n):
"""
Basic check to verify 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... | from solution import perform_diffie_hellman
def test_valid_diffie_hellman():
# Testing with known primitive root and prime
a = 2
p = 11
shared_key = perform_diffie_hellman(a, p)
assert shared_key != -1
def test_invalid_prime():
# Testing with a non-prime number
a = 3
p = 12 # Not a pr... | [
{
"docstring": "Basic check to verify if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find a primitive root modulo p, if it exists.",
"function_declaration": "def find_primitive_root(p):",
"fu... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025639",
"row_id": 25639,
"seed_ids": "[146]"
} | 0.559234 | Data_Structure_25639 | I | [
"is_prime",
"find_primitive_root",
"prime_factors",
"perform_diffie_hellman"
] | 4 | [
[
"find_primitive_root",
"prime_factors"
],
[
"perform_diffie_hellman",
"find_primitive_root"
],
[
"perform_diffie_hellman",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 9e4acac40a68f195c5ab70e3b2ffbe64aee9c288 | 50e371306b7bce7e97def289a57523cc36135445 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25650_I | ### Problem: Efficient Sorting with Constraints
You have been given the task to sort a list of integers using the merge sort algorithm. Since this list can be very large, you need to ensure that your implementation is as efficient as possible in terms of space and time.
**Function Signature**
```python
def efficien... | from typing import List
def efficient_merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = efficient_merge_sort(arr[:mid])
right_half = efficient_merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left: List[int], ... | from solution import efficient_merge_sort
def test_empty_list():
assert efficient_merge_sort([]) == []
def test_single_element():
assert efficient_merge_sort([5]) == [5]
def test_even_number_of_elements():
assert efficient_merge_sort([3, 1, 2, 4]) == [1, 2, 3, 4]
def test_odd_number_of_elements():
a... | [
{
"docstring": null,
"function_declaration": "def efficient_merge_sort(arr):",
"function_name": "efficient_merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"... | [
0,
0,
0,
1,
1,
1,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef efficient_merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of integers using the merge sort algorithm.\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00025650",
"row_id": 25650,
"seed_ids": "[12]"
} | 0.559427 | Data_Structure_25650 | I | [
"efficient_merge_sort",
"merge"
] | 2 | [
[
"efficient_merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6f4e11849655aae63f3283f0fd504803b974fa01 | 8103777042ad5db30d9394d217e70717b69d4752 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25670_I | ### Maximum Flow Problem
**Context**: You are working for a logistics company. They need to determine the maximum possible flow through their delivery network to optimize the routes taken by their trucks. The network is represented as a graph where each node is a distribution center, and each edge has a capacity indic... | def bfs(residual_graph, source, sink, parent):
"""
A utility function to perform BFS on the residual graph.
Returns True if there is a path from source to sink in the residual graph.
Additionally, fills parent to store the path.
"""
visited = [False] * len(residual_graph)
queue = []
... | from solution import max_flow
def test_max_flow_simple():
graph = [[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]]
assert max_flow(graph) == 23
def test_max_flow_singl... | [
{
"docstring": "A utility function to perform BFS on the residual graph.\nReturns True if there is a path from source to sink in the residual graph.\nAdditionally, fills parent to store the path.",
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"par... | [
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 max_flow(adjacency_matrix):\n \"\"\"\n Calculates the maximum flow from the source node (first node) to the sink node (last node)\n in a directed... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025670",
"row_id": 25670,
"seed_ids": "[241]"
} | 0.652086 | Data_Structure_25670 | I | [
"bfs",
"max_flow"
] | 2 | [
[
"max_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 17fe9ed80070f8c0645b25f7be022ad5fa8318cc | 9ce726886b7cc4ae405018aefa0248fa8cd0901c | |||
v1.0 | instruct | Data_Structure | Data_Structure_25671_I | ### Bogo Sort Simulation and Optimization
You are given a theoretical and inefficient sorting algorithm named **Bogo Sort**. This algorithm randomly shuffles the elements of the array until it happens to be sorted. While this algorithm is impractical for general use, it provides an interesting case to study randomness... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""Helper function to check if the array is sorted"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def shuffle_array(arr: List[int]) -> None:
"""Helper function to randomly shuffle the array in place"""
rando... | from solution import optimized_bogo_sort
def test_sorted_array():
assert optimized_bogo_sort([1, 2, 3], 1000) == [1, 2, 3]
def test_reverse_sorted_array():
assert optimized_bogo_sort([3, 2, 1], 1000) == [1, 2, 3]
def test_random_unsorted_array():
assert optimized_bogo_sort([3, 1, 2], 1000) == [1, 2, 3]
... | [
{
"docstring": "Helper function to check if the array is sorted",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Helper function to randomly shuffle the array in place",
"function_declaration": "def shuffle_array(... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Check if the array is sorted.\n \"\"\"\n for i in rang... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025671",
"row_id": 25671,
"seed_ids": "[16]"
} | 0.562599 | Data_Structure_25671 | I | [
"is_sorted",
"shuffle_array",
"optimized_bogo_sort"
] | 3 | [
[
"optimized_bogo_sort",
"is_sorted"
],
[
"optimized_bogo_sort",
"shuffle_array"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a328f02b9b5da7602d89253c7dd9b8e75fbc8f41 | 25441446cb97f5af8eee17a90d3f3b6088d757a0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25710_I | ### Radix Sort Implementation and Edge Case Handling
You are tasked with implementing a radix sort algorithm in Python to sort an array of non-negative integers. Your function should handle the following edge cases and constraints:
1. Arrays of varying lengths, including empty arrays.
2. Large numbers up to 1,000,000... | from typing import List
def counting_sort(arr: List[int], exp: int) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
# Store count of occurrences in count[]
for i in range(n):
index = arr[i] // exp
count[(index % 10)] += 1
# Change count[i] so it contains the actua... | from solution import radix_sort
def test_radix_sort():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
assert radix_sort([]) == []
assert radix_sort([5]) == [5]
assert radix_sort([1, 1, 1, 1]) == [1, 1, 1, 1]
assert radix_sort([3, 1, 2, 5, 4]) == [1, 2, 3, ... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025710",
"row_id": 25710,
"seed_ids": "[15]"
} | 0.654887 | Data_Structure_25710 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1ade968f5bb8a316ce1633589e9f233b5634e234 | bc07b0c22acb48d3f8bad4bc500f1678ae5a3fa3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25824_I | ### Caesar Cipher with Enhanced Features
You are tasked with implementing an enhanced version of Caesar Cipher that includes additional functionalities such as decrypting the encrypted text and handling customized shift values securely. Your solution should maintain efficiency and readability.
#### Function 1: Encryp... | def caesar_encrypt(s: str, k: int) -> str:
"""
Encrypts the input string s by shifting each letter by k positions.
Non-alphabetic characters remain unchanged.
"""
def shift_char(c, k):
if c.islower():
return chr(((ord(c) - ord('a') + k) % 26) + ord('a'))
elif c.isupper():... | from solution import caesar_encrypt, caesar_decrypt
def test_caesar_encrypt():
assert caesar_encrypt("Hello, World!", 3) == "Khoor, Zruog!"
assert caesar_encrypt("abc xyz", 2) == "cde zab"
assert caesar_encrypt("HELLO", 3) == "KHOOR"
assert caesar_encrypt("Python3.6", 5) == "Udymts3.6"
assert caesa... | [
{
"docstring": "Encrypts the input string s by shifting each letter by k positions.\nNon-alphabetic characters remain unchanged.",
"function_declaration": "def caesar_encrypt(s, k):",
"function_name": "caesar_encrypt",
"parameter_list": "(s, k)"
},
{
"docstring": "Decrypts the previously enc... | [
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 caesar_encrypt(s: str, k: int) -> str:\n \"\"\"\n Encrypts the input string s by shifting each alphabetic character by k positions.\n Non-alphabe... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025824",
"row_id": 25824,
"seed_ids": "[78]"
} | 0.655751 | Data_Structure_25824 | I | [
"caesar_encrypt",
"caesar_decrypt"
] | 2 | [
[
"caesar_decrypt",
"caesar_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ba3f7979a2d08d34024a02b68b3e9e3bd234719a | dc5da9c548d4b312c71af47601b386702d1a1798 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25833_I | ### Question
#### Problem Statement:
Write a Python function to solve the Matrix Chain Multiplication problem using dynamic programming. Your function should take an array of integers representing the dimensions of matrices and return an integer denoting the minimum number of multiplications needed to multiply the gi... | def min_matrix_multiplications(dims):
n = len(dims) - 1
m = [[0 for x in range(n)] for y in range(n)]
s = [[0 for x in range(n)] for y in range(n)]
for L in range(2, n+1):
for i in range(n-L+1):
j = i + L - 1
m[i][j] = float('inf')
for k in range(i, j):
... | from solution import min_matrix_multiplications
def test_matrix_chain_simple():
dims = [40, 20, 30, 10, 30]
assert min_matrix_multiplications(dims) == 26000
def test_matrix_chain_two_matrices():
dims = [10, 20, 30]
assert min_matrix_multiplications(dims) == 6000
def test_matrix_chain_three_matrices()... | [
{
"docstring": null,
"function_declaration": "def min_matrix_multiplications(dims):",
"function_name": "min_matrix_multiplications",
"parameter_list": "(dims)"
},
{
"docstring": null,
"function_declaration": "def print_optimal_schedule(s, i, j):",
"function_name": "print_optimal_sche... | [
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 min_matrix_multiplications(dims):\n n = len(dims) - 1\n m = [[0 for _ in range(n)] for _ in range(n)]\n s = [[0 for _ in range(n)] for _ in range... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00025833",
"row_id": 25833,
"seed_ids": "[45]"
} | 0.503318 | Data_Structure_25833 | I | [
"min_matrix_multiplications",
"print_optimal_schedule"
] | 2 | [
[
"min_matrix_multiplications",
"print_optimal_schedule"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 777dd98ee90d18b009322cf861165024236a35dd | 80c6fd50d3fe2f48da2fb1c7d5b55edd6c30e0f5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25862_I | ### Scenario:
You have been hired by a logistics company to optimize the transport routes within a new city-wide delivery network. The network is represented as a directed graph where nodes are intersections and edges are roads with certain capacities (the maximum number of delivery vans that can pass per time unit).
... | from collections import deque
def bfs(capacity, source, sink, parent):
visited = [False] * len(capacity)
queue = deque([source])
visited[source] = True
while queue:
node = queue.popleft()
for i, cap in enumerate(capacity[node]):
if not visited[i] and cap > 0:
... | def test_optimal_delivery_flow_example():
route_matrix = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert optimal_delivery_flow(route_matrix) == 23
def test_optimal_deliver... | [
{
"docstring": null,
"function_declaration": "def bfs(capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def optimal_delivery_flow(route_matrix):",
"function_name": "optimal_... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(rGraph, s, t, parent):\n \"\"\"\n A BFS based function to check if there is a path from source 's' to \n sin... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025862",
"row_id": 25862,
"seed_ids": "[229]"
} | 0.609387 | Data_Structure_25862 | I | [
"bfs",
"optimal_delivery_flow"
] | 2 | [
[
"optimal_delivery_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 6204f02c55f50845e55c5e1ec730ffb115e09d92 | 56a0d1f5f75a1e8b0a376c578099cb45aaa11687 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25889_I | ### RSA Encryption and Decryption Implementation
You are required to implement a secure communication system based on the RSA encryption algorithm. RSA is a widely-used public-key cryptosystem that facilitates the encryption and decryption of data. You need to generate a public-private keypair, encrypt a message with ... | import random
from sympy import isprime, mod_inverse, nextprime
def generate_prime(bits, seed=None):
if seed is not None:
random.seed(seed)
prime_candidate = random.getrandbits(bits)
while not isprime(prime_candidate):
prime_candidate = nextprime(prime_candidate)
return prime_candidate
... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16, seed=0)
assert isinstance(n, int) and isinstance(e, int) and isinstance(d, int)
assert n > 0 and e > 0 and d > 0
def test_encrypt_decrypt():
n, e, d = generate_key(16, seed=0)
message = 42
e... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bits, seed=None):",
"function_name": "generate_prime",
"parameter_list": "(bits, seed=None)"
},
{
"docstring": "Generates RSA keypair of size `bits`.",
"function_declaration": "def generate_key(bits, seed=None):",
"func... | [
0,
0,
1,
0,
1,
1,
1,
0,
1
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime(bits, seed=None):\n if seed:\n random.seed(seed... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00025889",
"row_id": 25889,
"seed_ids": "[154]"
} | 0.5973 | Data_Structure_25889 | I | [
"generate_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 03ce9ca42cf2e5b66ac952fdeda1e70528d763e2 | 484416b1dc73e514fc4297afce765ed163fb805a | |||
v1.0 | instruct | Data_Structure | Data_Structure_25909_I | ### Question: Find the Intersection Node of Two Singly Linked Lists
#### Objective
Implement a function to find the intersection node between two singly linked lists. The intersection is defined by reference, not by value.
#### Problem Statement
Two linked lists intersect if they share some nodes. The intersection no... | class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def get_length(head: Node) -> int:
length = 0
current = head
while current:
length += 1
current = current.next
return length
def intersection(h1: Node, h2: Node) -> Node:
if not h1... | from solution import Node, intersection
def test_intersection_common_case():
a1 = Node(1)
b1 = Node(3)
c1 = Node(5)
d = Node(7)
e = Node(9)
f = Node(11)
a2 = Node(2)
b2 = Node(4)
c2 = Node(6)
a1.next = b1
b1.next = c1
c1.next = d
d.next = e
e.next = f
a2.n... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, value=0, next=None):\n self.value = value\n self.next = next\n\ndef intersection(h1: Node, h2: Node) -> Node... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025909",
"row_id": 25909,
"seed_ids": "[245]"
} | 0.571243 | Data_Structure_25909 | I | [
"get_length",
"intersection"
] | 2 | [
[
"intersection",
"get_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 0aafefac15cfdee7a410ada5d763dbf4d887146e | 4aacda8f9c3db4e8696c2080b36f851e95c2f03b | |||
v1.0 | instruct | Data_Structure | Data_Structure_25928_I | ### Bogo Sort Analysis and Enhancement
#### Scenario
You have come across an inefficient sorting algorithm called Bogo Sort which randomly shuffles the array until it becomes sorted. Your task is to understand its inefficiencies and then write a more practical approach.
#### Task
1. **Analysis**:
- Explain why Bo... | import random
import time
import copy
def bogo_sort(arr):
def is_sorted(arr):
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
attempts = 0
while not is_sorted(arr) and attempts < 10000:
random.shuffle(arr)
attempts += 1
return arr
def merge_sort(arr):
if ... | from solution import compare_sorts, merge_sort
def test_compare_sorts_sorted_array():
arr = [1, 2, 3, 4, 5]
bogo_sorted_arr, merge_sorted_arr, bogo_time, efficient_time = compare_sorts(arr)
assert bogo_sorted_arr == merge_sorted_arr == sorted(arr)
def test_compare_sorts_reverse_sorted_array():
arr = [... | [
{
"docstring": null,
"function_declaration": "def bogo_sort(arr):",
"function_name": "bogo_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": n... | [
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 time\nimport random\n\ndef bogo_sort(arr):\n \"\"\"\n Bogo Sort: Randomly shuffles the array until it becomes sorted\n \"\"\"\n def is_sort... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025928",
"row_id": 25928,
"seed_ids": "[16]"
} | 0.491189 | Data_Structure_25928 | I | [
"bogo_sort",
"merge_sort",
"compare_sorts"
] | 3 | [
[
"compare_sorts",
"bogo_sort"
],
[
"compare_sorts",
"merge_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0580206c454db0593506b2906587160c0472a459 | 14fc59fc0e731741e41d6607b9dba28f8b4b7f98 | |||
v1.0 | instruct | Data_Structure | Data_Structure_25993_I | You are tasked to implement a function that runs a nearest neighbor search algorithm. This function takes a high-dimensional query point and a training set, then returns the label of the nearest neighbor. The training set will be provided as a dictionary where the keys are high-dimensional points (tuples) and the value... | import math
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two high-dimensional points.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(point1, point2)))
def find_nearest_neighbor(query_point, training_set):
"""
Find the nearest neighbor for the give... | from solution import find_nearest_neighbor
def test_single_point_training_set():
query_point = (1, 2)
training_set = {(1, 2): 'Label'}
assert find_nearest_neighbor(query_point, training_set) == 'Label'
def test_multiple_points_training_set():
query_point = (1, 2)
training_set = {
(2, 3): '... | [
{
"docstring": "Calculate the Euclidean distance between two high-dimensional points.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Find the nearest neighbor for the given qu... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate Euclidean distance between two high-dimensional points.\n \"\"\"\n ret... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025993",
"row_id": 25993,
"seed_ids": "[260]"
} | 0.709288 | Data_Structure_25993 | I | [
"euclidean_distance",
"find_nearest_neighbor"
] | 2 | [
[
"find_nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 682c33df1993824c15643bea56fff454722c52f5 | 41211feb23bb23f5691f15757fa7fddfa07c9aa8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26026_I | ## Problem Statement
You are provided with a probabilistic algorithm, the Rabin-Miller Primality Test, which helps determine if a number is probably prime. Your task is to implement a function that leverages this algorithm to generate prime numbers of a specified bit length.
### Function Signature
```python
def gener... | import random
def is_probably_prime(n, k):
"""Rabin-Miller primality test."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
# Write (n - 1) as 2^r * d
r, d = 0, n - 1
while d % 2 == 0:
r += 1
d //= 2
def ... | from solution import generate_prime, is_probably_prime
def test_generate_prime_bit_length():
prime = generate_prime(16, k=40)
assert prime.bit_length() == 16, f"Expected bit length of 16, but got {prime.bit_length()}"
def test_prime_is_probable():
prime = generate_prime(16, k=40)
assert is_probably_pr... | [
{
"docstring": "Rabin-Miller primality test.",
"function_declaration": "def is_probably_prime(n, k):",
"function_name": "is_probably_prime",
"parameter_list": "(n, k)"
},
{
"docstring": "Generates a prime number of the given bit length.",
"function_declaration": "def generate_prime(bit_l... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef miller_rabin_test(n: int, k: int) -> bool:\n \"\"\" Perform the Miller-Rabin Primality Test to check if n is a probable prime. \"\"\"\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026026",
"row_id": 26026,
"seed_ids": "[136]"
} | 0.579379 | Data_Structure_26026 | I | [
"is_probably_prime",
"generate_prime"
] | 2 | [
[
"generate_prime",
"is_probably_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 590c3eef21b9a716d04145929c96166eed605518 | 572f5321200f73decdc2e2d8ba8f1f623b7f20f9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26040_I | ### Coding Challenge: Implement Huffman Encoding and Decoding
#### Scenario
Imagine you are working on a software project that requires efficient storage and transfer of data files. To achieve this, you decide to implement Huffman Coding, a popular compression algorithm. Your task is to develop functions that can enco... | import heapq
import os
from collections import defaultdict
class HuffmanNode:
def __init__(self, symbol=None, freq=0, left=None, right=None):
self.symbol = symbol
self.freq = freq
self.left = left
self.right = right
def __lt__(self, other):
return self.freq < other.... | import os
import pytest
from solution import huffman_encode, huffman_decode
def test_huffman_empty_file(tmp_path):
input_file = tmp_path / "input.txt"
encoded_file = tmp_path / "encoded.bin"
decoded_file = tmp_path / "decoded.txt"
input_file.write_bytes(b"")
huffman_encode(input_file, encoded... | [] | [
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 heapq\nimport os\nfrom collections import defaultdict\n\nclass HuffmanNode:\n def __init__(self, symbol=None, freq=0, left=None, right=None):\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00026040",
"row_id": 26040,
"seed_ids": "[335]"
} | 0.506427 | Data_Structure_26040 | I | [
"build_frequency_table",
"build_huffman_tree",
"build_codes_table",
"huffman_encode",
"decode_huffman_codes",
"huffman_decode"
] | 6 | [
[
"huffman_decode",
"decode_huffman_codes"
],
[
"huffman_encode",
"build_codes_table"
],
[
"huffman_encode",
"build_frequency_table"
],
[
"huffman_encode",
"build_huffman_tree"
]
] | 4 | [] | false | [
"HuffmanNode"
] | true | pytest | true | [] | true | 1401d79c534637319e8940fa77d0d57f037c0e66 | 598963c1e6d12311d1b045e8cff1aebe23d04acc | |||
v1.0 | instruct | Data_Structure | Data_Structure_26048_I | ### Problem Description
Write a function `multiply_bitwise_operator` that multiplies two non-negative integers using bitwise operations. This function should not use the `*` operator. Instead, leverage the properties of bitwise operations. Below is the expected behavior of your function:
**Input**:
- `a` (non-negativ... | def multiply_bitwise_operator(a: int, b: int) -> int:
"""
Multiply two non-negative integers using bitwise operations.
"""
result = 0
while b > 0:
# If the least significant bit of b is set, add `a` to the result
if (b & 1) != 0:
result = add_bitwise(result, a)
... | from solution import multiply_bitwise_operator
def test_multiply_positive_numbers():
assert multiply_bitwise_operator(3, 4) == 12
assert multiply_bitwise_operator(7, 6) == 42
assert multiply_bitwise_operator(15, 15) == 225
def test_multiply_with_zero():
assert multiply_bitwise_operator(0, 10) == 0
... | [
{
"docstring": "Multiply two non-negative integers using bitwise operations.",
"function_declaration": "def multiply_bitwise_operator(a, b):",
"function_name": "multiply_bitwise_operator",
"parameter_list": "(a, b)"
},
{
"docstring": "Add two non-negative integers using bitwise operations.",... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply_bitwise_operator(a: int, b: int) -> int:\n \"\"\"\n Multiplies two non-negative integers using bitwise operations.\n \"\"\"\n result ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026048",
"row_id": 26048,
"seed_ids": "[209]"
} | 0.730035 | Data_Structure_26048 | I | [
"multiply_bitwise_operator",
"add_bitwise"
] | 2 | [
[
"multiply_bitwise_operator",
"add_bitwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c288d9ed67ab320f37af14962080da8137b315ac | d497e091cefb2c541e1d48880eb7c5d2b6272431 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26052_I | You are working on a text processing application, and one of the core features is the ability to find all instances of a specific search term (pattern) within a large document. You decide to use the Knuth-Morris-Pratt (KMP) algorithm for its efficiency. The function `knuth_morris_pratt` has already been provided. Your ... | from typing import List, Sequence
def build_lps(pattern: Sequence[str]) -> List[int]:
""" Function to build the longest proper prefix which is also suffix (lps) array """
lps = [0] * len(pattern)
length = 0 # length of the previous longest prefix suffix
i = 1
while i < len(pattern):
if pat... | from solution import optimize_knuth_morris_pratt
def test_kmp_found_single_occurrence():
assert optimize_knuth_morris_pratt('hello there hero!', 'hero') == [12]
def test_kmp_found_multiple_occurrences():
assert optimize_knuth_morris_pratt('hello there hero here', 'he') == [0, 7, 12, 17]
def test_kmp_not_foun... | [
{
"docstring": "Function to build the longest proper prefix which is also suffix (lps) array ",
"function_declaration": "def build_lps(pattern):",
"function_name": "build_lps",
"parameter_list": "(pattern)"
},
{
"docstring": "Function that uses the Knuth-Morris-Pratt algorithm to find all oc... | [
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, Sequence\n\ndef optimize_knuth_morris_pratt(text: Sequence[str], pattern: Sequence[str]) -> List[int]:\n \"\"\"\n Returns a lis... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026052",
"row_id": 26052,
"seed_ids": "[93]"
} | 0.511706 | Data_Structure_26052 | I | [
"build_lps",
"optimize_knuth_morris_pratt"
] | 2 | [
[
"optimize_knuth_morris_pratt",
"build_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fc9d145db1a80365d223fca7d871ec86fb5cd73c | 34b44961faa7cace566a34496fd973d124e5f9e4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26200_I | #### Scenario:
You have been hired as a network engineer for a telecommunications company. Your task is to analyze the current network to determine how efficiently data flows from the data center (source) to the main server hub (sink) using the given graph.
#### Problem Statement:
Write a function `maximum_flow` to c... | from typing import List
from collections import deque
def bfs(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:
"""
BFS to find a path from source to sink in the residual graph. Updates parent[] to store the path.
Returns True if there is a path from source to sink, False... | from solution import maximum_flow
def test_example_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
assert maximum_flow(graph) == 23
def test_small_graph():
g... | [
{
"docstring": "BFS to find a path from source to sink in the residual graph. Updates parent[] to store the path.\nReturns True if there is a path from source to sink, False otherwise.",
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n \"... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00026200",
"row_id": 26200,
"seed_ids": "[229]"
} | 0.653678 | Data_Structure_26200 | I | [
"bfs",
"maximum_flow"
] | 2 | [
[
"maximum_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1f425e5bd9313a32843fd3d94ea3fe3f7459680c | a1353bc19ca5b29d896ff00410bd76a72206eef5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26201_I | ### Scenario
Alice and Bob wish to establish a secure communication channel using the Diffie-Hellman key exchange. You will write Python functions to automate this process.
### Objective
Implement the complete Diffie-Hellman key exchange algorithm, ensuring all aspects such as primality checks and primitive root veri... | from math import gcd
def is_prime(n):
"""
Check if a 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
... | from solution import is_prime, find_primitive_root, diffie_hellman_key_exchange
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
def test_find_primitive_ro... | [
{
"docstring": "Check if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find all primitive roots of a prime p.",
"function_declaration": "def find_primitive_root(p):",
"function_name": "find_p... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Determines if a number is a prime number.\n \n Args:\n n: int - the number to check\n \n Returns:\n bool -... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026201",
"row_id": 26201,
"seed_ids": "[146]"
} | 0.483355 | Data_Structure_26201 | I | [
"is_prime",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 3 | [
[
"diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"diffie_hellman_key_exchange",
"is_prime"
],
[
"find_primitive_root",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ff8ed6298d381cf1910b7f94fd019d62be1d830a | 4b7fc7ab6084f4eeabf0de79355e5af7039d6663 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26281_I | ### Radix Sort Implementation Challenge
You are tasked with implementing a radix sort algorithm that efficiently sorts non-negative integers. Your goal is to ensure the function sorts the input array correctly and demonstrates an understanding of the radix sort's steps and mechanisms.
Implement a function `enhanced_r... | def enhanced_radix_sort(arr, simulation=False):
if not arr:
return arr
# Get maximum number to figure out the number of digits
max_num = max(arr)
exp = 1
iteration = 0
while max_num // exp > 0:
counting_sort(arr, exp)
if simulation:
print(f"iteration {it... | from solution import enhanced_radix_sort
def test_enhanced_radix_sort_basic():
assert enhanced_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_enhanced_radix_sort_empty():
assert enhanced_radix_sort([]) == []
def test_enhanced_radix_sort_single_element():
asser... | [
{
"docstring": null,
"function_declaration": "def enhanced_radix_sort(arr, simulation=False):",
"function_name": "enhanced_radix_sort",
"parameter_list": "(arr, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counti... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_radix_sort(arr, simulation=False):\n \"\"\"\n Sorts a list of non-negative integers using radix sort.\n Optionally prints the array afte... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026281",
"row_id": 26281,
"seed_ids": "[15]"
} | 0.677631 | Data_Structure_26281 | I | [
"enhanced_radix_sort",
"counting_sort"
] | 2 | [
[
"enhanced_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 933b50e1b2e3c01b5eecbd9be562ef4bd9defd2e | 54ad0bdd7fda4c9318c0cac5b80795e60b9653c1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26380_I | ### Stooge Sort Enhancement Task
You are tasked with enhancing the Stooge Sort algorithm. Given the highly inefficient nature of Stooge Sort, you need to modify the original algorithm to improve its performance where possible.
### Objective
Create a modified version of Stooge Sort that includes a threshold parameter ... | def insertion_sort(arr, l, h):
"""
Helper function to perform Insertion Sort on the subarray from indices l to 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
de... | from solution import enhanced_stoogesort
def test_small_threshold():
arr = [5, 2, 9, 1, 5, 6]
enhanced_stoogesort(arr, 0, len(arr) - 1, 3)
assert arr == [1, 2, 5, 5, 6, 9]
def test_large_threshold():
arr = [3, 0, 2, 5, -1, 4, 1]
enhanced_stoogesort(arr, 0, len(arr) - 1, 6)
assert arr == [-1, 0... | [
{
"docstring": "Helper function to perform Insertion Sort on the subarray from indices l to h",
"function_declaration": "def insertion_sort(arr, l, h):",
"function_name": "insertion_sort",
"parameter_list": "(arr, l, h)"
},
{
"docstring": "Enhanced Stooge Sort algorithm with a threshold para... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insertion_sort(arr, l, h):\n \"\"\"\n Helper function to perform Insertion Sort on the subarray from indices l to h\n \"\"\"\n for i in range(... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00026380",
"row_id": 26380,
"seed_ids": "[10]"
} | 0.593472 | Data_Structure_26380 | I | [
"insertion_sort",
"enhanced_stoogesort"
] | 2 | [
[
"enhanced_stoogesort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9ea3068ce499c2c952e5ceec99977bf660eeb555 | 4ad9dbd9417bca2a0c08986a341dbed235325695 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26429_I | **Context**:
You have been hired to enhance the performance of a company's data handling processes. A key area identified is the sorting of records based on various criteria. One specific challenge is ensuring efficient sorting of large datasets while maintaining optimal performance across a variety of input scenarios,... | 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
else:
if a > c:
return low
elif b < c:
... | 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",
"param... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def _median_of_three(arr, low, high):\n mid = (low + high) // 2\n a, b, c = arr[low], arr[mid], arr[high]\n if a > b:\n if a < c:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00026429",
"row_id": 26429,
"seed_ids": "[25]"
} | 0.537887 | Data_Structure_26429 | I | [
"_median_of_three",
"_partition",
"_quick_sort_helper",
"optimized_quick_sort"
] | 4 | [
[
"_partition",
"_median_of_three"
],
[
"_quick_sort_helper",
"_partition"
],
[
"optimized_quick_sort",
"_quick_sort_helper"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 2ab18e8e19c711f360e4828e1ca0416bbff699c7 | 417938417be4352f4fe5a8ab9143a4f6315dde5e | |||
v1.0 | instruct | Data_Structure | Data_Structure_26462_I | Given the functions to convert integers to byte sequences (both big-endian and little-endian) and vice versa, write a new function that verifies if the conversions are performed correctly. The function `verify_conversion` should take an integer `num` and check that converting it to bytes and back to an integer yields t... | def int_to_bytes_big_endian(num: int) -> bytes:
return num.to_bytes((num.bit_length() + 7) // 8, byteorder='big')
def int_to_bytes_little_endian(num: int) -> bytes:
return num.to_bytes((num.bit_length() + 7) // 8, byteorder='little')
def bytes_to_int_big_endian(b: bytes) -> int:
return int.from_bytes(b, b... | def test_int_to_bytes_big_endian():
assert int_to_bytes_big_endian(1) == b'\x01'
assert int_to_bytes_big_endian(256) == b'\x01\x00'
assert int_to_bytes_big_endian(65536) == b'\x01\x00\x00'
assert int_to_bytes_big_endian(0) == b''
def test_int_to_bytes_little_endian():
assert int_to_bytes_little_end... | [
{
"docstring": null,
"function_declaration": "def int_to_bytes_big_endian(num):",
"function_name": "int_to_bytes_big_endian",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def int_to_bytes_little_endian(num):",
"function_name": "int_to_bytes_little_endian... | [
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 a byte sequence in big-endian format.\n \"\"\"\n return num.to_by... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026462",
"row_id": 26462,
"seed_ids": "[216]"
} | 0.57021 | Data_Structure_26462 | I | [
"int_to_bytes_big_endian",
"int_to_bytes_little_endian",
"bytes_to_int_big_endian",
"bytes_to_int_little_endian",
"verify_conversion"
] | 5 | [
[
"verify_conversion",
"bytes_to_int_big_endian"
],
[
"verify_conversion",
"bytes_to_int_little_endian"
],
[
"verify_conversion",
"int_to_bytes_big_endian"
],
[
"verify_conversion",
"int_to_bytes_little_endian"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | ea7aaf5eebf1b7d0a266a94f55d2e43d6151e094 | bec62c95d8db4617b58fb0aae7f5c3a88fb60683 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26513_I | ### Coding Challenge: Implement a Robust Diffie-Hellman Key Exchange in Python
#### Objective
Your task is to implement a secure Diffie-Hellman key exchange algorithm that ensures both participants (Alice and Bob) can securely generate and share a secret key over an insecure communication channel.
#### Requirements
1... | import random
import math
def is_prime(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def primitive_root(p):
if not is_prime(p):
raise ValueError(f"{p} is not a prime number.")
def is_pri... | import pytest
from solution import is_prime, primitive_root, diffie_hellman_key_exchange
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
assert is_prim... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def primitive_root(p):",
"function_name": "primitive_root",
"parameter_list": "(p)"
},
{
"docstring":... | [
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 is_prime(num):\n \"\"\"\n Checks if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026513",
"row_id": 26513,
"seed_ids": "[146]"
} | 0.501321 | Data_Structure_26513 | I | [
"is_prime",
"primitive_root",
"diffie_hellman_key_exchange",
"is_primitive_root"
] | 4 | [
[
"diffie_hellman_key_exchange",
"is_prime"
],
[
"diffie_hellman_key_exchange",
"is_primitive_root"
],
[
"primitive_root",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 62d6723310412cc37348875a922cfee749371af4 | a593cd7490594dc51486d96c0db32f4e55339e02 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26625_I | Implement an RSA Key Generation Function
#### Context:
You are tasked with designing a simplified RSA public and private key generation script. RSA relies on the Extended Euclidean Algorithm for modular inverse calculations.
#### Objective:
Write a Python function `generate_rsa_keys(p: int, q: int) -> Tuple[Tuple[int... | import random
from typing import Tuple
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
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(e: int, phi: int) -> int:
gcd, x, y = extended_gcd(e, phi)
... | from solution import generate_rsa_keys
def test_rsa_key_generation():
public_key, private_key = generate_rsa_keys(61, 53)
n, e = public_key
n_, d = private_key
assert n == n_
assert (e * d) % ((61 - 1) * (53 - 1)) == 1
def test_rsa_key_generation_different_primes():
public_key, private_ke... | [
{
"docstring": null,
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def modular_inverse(e, phi):",
"function_name": "modular_inverse",
"parameter_list": "(e, phi)"
}... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import Tuple\n\ndef extended_gcd(a: int, b: int) -> Tuple[int, int, int]:\n if a == 0:\n return b, 0, 1\n gcd, x1, y1 ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026625",
"row_id": 26625,
"seed_ids": "[161]"
} | 0.560061 | Data_Structure_26625 | I | [
"extended_gcd",
"modular_inverse",
"generate_rsa_keys"
] | 3 | [
[
"generate_rsa_keys",
"extended_gcd"
],
[
"generate_rsa_keys",
"modular_inverse"
],
[
"modular_inverse",
"extended_gcd"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 7ed37e20ec987400e43017e9b2cc4e318ba540e0 | e1233d1a6779421ca753d3ddae0f7d520214702d | |||
v1.0 | instruct | Data_Structure | Data_Structure_26627_I | ### Bogo Sort Extension
#### Context:
Bogo Sort is a highly inefficient algorithm due to its randomized approach to sorting. While Bogo Sort is not practical for real-world sorting tasks, it can be modified to create a new hypothetical sorting algorithm for educational purposes. Your task is to implement a modified ve... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def modified_bogo_sort(arr: List[int], simulation: bool = False) ... | from solution import modified_bogo_sort
def test_modified_bogo_sort_small_list():
arr = [3, 1, 4, 2]
sorted_arr = modified_bogo_sort(arr.copy())
assert sorted_arr == sorted(arr)
def test_modified_bogo_sort_empty_list():
arr = []
sorted_arr = modified_bogo_sort(arr.copy())
assert sorted_arr == ... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Implements the Modified Bogo Sort algorithm.",
"function_declaration": "def modified_bogo_sort(arr,... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Returns True if the array is sorted in non-decreasing order,... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026627",
"row_id": 26627,
"seed_ids": "[16]"
} | 0.595398 | Data_Structure_26627 | I | [
"is_sorted",
"modified_bogo_sort"
] | 2 | [
[
"modified_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d54504b34b900791db5e131580087b0666cc8544 | 97d6981e0514ad872135169510e9c6769ac2de47 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26703_I | ### Shared Secret Agreement Using Diffie-Hellman Key Exchange
Alice and Bob want to securely share a secret key using the Diffie-Hellman key exchange method. The Diffie-Hellman algorithm involves the following steps:
1. Choose a large prime number `p` and a primitive root `a` of `p`.
2. Alice picks a private key `a_p... | import random
def alice_private_key(p):
"""
Returns a random private key for Alice.
"""
return random.randint(1, p-1)
def alice_public_key(a_pr_k, a, p):
"""
Computes and returns Alice's public key.
"""
return pow(a, a_pr_k, p)
def bob_private_key(p):
"""
Returns a random priv... | from solution import (
alice_private_key, alice_public_key, bob_private_key, bob_public_key,
alice_shared_key, bob_shared_key, diffie_hellman_key_exchange
)
def test_diffie_hellman_key_exchange():
p = 23 # A small prime for simplicity
a = 5 # A primitive root of 23
a_pr_k = alice_private_key(p)... | [
{
"docstring": "Returns a random private key for Alice.",
"function_declaration": "def alice_private_key(p):",
"function_name": "alice_private_key",
"parameter_list": "(p)"
},
{
"docstring": "Computes and returns Alice's public key.",
"function_declaration": "def alice_public_key(a_pr_k,... | [
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 is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026703",
"row_id": 26703,
"seed_ids": "[146]"
} | 0.419889 | Data_Structure_26703 | I | [
"alice_private_key",
"alice_public_key",
"bob_private_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"diffie_hellman_key_exchange"
] | 7 | [
[
"diffie_hellman_key_exchange",
"alice_private_key"
],
[
"diffie_hellman_key_exchange",
"alice_public_key"
],
[
"diffie_hellman_key_exchange",
"alice_shared_key"
],
[
"diffie_hellman_key_exchange",
"bob_private_key"
],
[
"diffie_hellman_key_exchange",
"bob_pu... | 6 | [] | false | [] | false | pytest | true | [] | true | b7dca1f337fa999f7e7d515f34ea977d6b229343 | 91ba2a5d3340a3dba92da605f513347e6a96e573 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26708_I | ### Question: Advanced GCD and LCM Implementations
You are to implement a function that computes the greatest common divisor (GCD) and the least common multiple (LCM) of two integers with the following improvements over given reference methods:
1. Implement Euclid's algorithm for GCD using both modulus and bitwise ope... | def gcd_mod(a, b):
"""
Compute the GCD of a and b using Euclid's algorithm with modulus operation.
"""
while b != 0:
a, b = b, a % b
return a
def gcd_bitwise(a, b):
"""
Compute the GCD of a and b using the binary GCD algorithm.
"""
if a == 0:
return b
if b == 0:
... | from solution import gcd_mod, gcd_bitwise, lcm, gcd_lcm
def test_gcd_mod():
assert gcd_mod(24, 36) == 12
assert gcd_mod(48, 18) == 6
assert gcd_mod(101, 10) == 1
assert gcd_mod(0, 5) == 5
assert gcd_mod(17, 0) == 17
def test_gcd_bitwise():
assert gcd_bitwise(24, 36) == 12
assert gcd_bitwis... | [
{
"docstring": "Compute the GCD of a and b using Euclid's algorithm with modulus operation.",
"function_declaration": "def gcd_mod(a, b):",
"function_name": "gcd_mod",
"parameter_list": "(a, b)"
},
{
"docstring": "Compute the GCD of a and b using the binary GCD algorithm.",
"function_dec... | [
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_mod(a: int, b: int) -> int:\n \"\"\"\n Calculate GCD using Euclid's modulus algorithm.\n \"\"\"\n while b:\n a, b = b, a % b\n r... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026708",
"row_id": 26708,
"seed_ids": "[166]"
} | 0.699207 | Data_Structure_26708 | I | [
"gcd_mod",
"gcd_bitwise",
"lcm",
"gcd_lcm"
] | 4 | [
[
"gcd_lcm",
"gcd_mod"
],
[
"lcm",
"gcd_mod"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ef40b2500093ba479a3cd6d7b2e9566fb200651e | 7bad2f87255a981f1a52745c72daf6f9c4fba3fc | |||
v1.0 | instruct | Data_Structure | Data_Structure_26835_I | ### Question
You are provided with two functions for converting integers between different bases:
1. `int_to_base(num, base)`: Converts an integer `num` to a string representation of that number in the provided `base`.
2. `base_to_int(str_to_convert, base)`: Converts a string representation of a number in the given `... | def int_to_base(num, base):
""" Convert an integer to a string representation in a given base """
if num == 0:
return "0"
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sign = ""
if num < 0:
sign = "-"
num = -num
result = ""
while num > 0:
remainder = num %... | def test_convert_and_revert_positive():
assert convert_and_revert(15, 16) == 15
def test_convert_and_revert_negative():
assert convert_and_revert(-8, 2) == -8
def test_convert_and_revert_zero():
assert convert_and_revert(0, 10) == 0
def test_convert_and_revert_large_positive():
assert convert_and_rev... | [
{
"docstring": "Convert an integer to a string representation in a given base ",
"function_declaration": "def int_to_base(num, base):",
"function_name": "int_to_base",
"parameter_list": "(num, base)"
},
{
"docstring": "Convert a string representation of a number in a given base back to an in... | [
0,
0,
0,
0,
1,
1,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def int_to_base(num, base):\n \"\"\"\n Converts an integer num to its base-n string representation.\n \"\"\"\n if num == 0:\n return \"0\"\... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00026835",
"row_id": 26835,
"seed_ids": "[164]"
} | 0.707288 | Data_Structure_26835 | I | [
"int_to_base",
"base_to_int",
"convert_and_revert"
] | 3 | [
[
"convert_and_revert",
"base_to_int"
],
[
"convert_and_revert",
"int_to_base"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | ff8c7ce5d6a0051c73c7169f30c4fa2ba89f88c9 | 6d5032fa2074ce9d58eaed8e6ba94aa2d69fa03d | |||
v1.0 | instruct | Data_Structure | Data_Structure_26874_I | ### Context
You have been tasked with implementing the Bitonic Sort algorithm, which will be used in a high-performance computing environment. The Bitonic Sort must be capable of sorting arrays both in ascending and descending order, and the input size must be a power of two.
### Task
Implement the `bitonic_sort` func... | def bitonic_sort(arr, reverse=False):
"""
Sorts an array using the bitonic sort algorithm.
Parameters:
arr (List[int]): The array to sort.
reverse (bool): Whether to sort in descending order. Default is False.
Returns:
List[int]: Sorted array.
Raises:
ValueError: if th... | from solution import bitonic_sort, batch_bitonic_sort
import pytest
def test_bitonic_sort_ascending():
arr = [3, 7, 4, 8, 6, 2, 1, 5]
expected = [1, 2, 3, 4, 5, 6, 7, 8]
assert bitonic_sort(arr) == expected
def test_bitonic_sort_descending():
arr = [3, 7, 4, 8, 6, 2, 1, 5]
expected = [8, 7, 6, 5, ... | [
{
"docstring": "Sorts an array using the bitonic sort algorithm.\n\nParameters:\narr (List[int]): The array to sort.\nreverse (bool): Whether to sort in descending order. Default is False.\n\nReturns:\nList[int]: Sorted array.\n\nRaises:\nValueError: if the size of the input array is not a power of two",
"f... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_power_of_two(n):\n return (n & (n - 1) == 0) and n != 0\n\ndef bitonic_sort(arr, reverse=False):\n \"\"\"\n Sorts an array using bitonic sort ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026874",
"row_id": 26874,
"seed_ids": "[17]"
} | 0.620756 | Data_Structure_26874 | I | [
"bitonic_sort",
"batch_bitonic_sort"
] | 2 | [
[
"batch_bitonic_sort",
"bitonic_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ea4db0dc321f81e2b3d6ebfc1c81019a257ae5a7 | ac6c753d512e8ae3db1f6fce28bf9bfedb10e94a | |||
v1.0 | instruct | Data_Structure | Data_Structure_26905_I | ### Merge Sort Implementation with In-Place Merge
#### Scenario:
You are tasked with optimizing a merge sort algorithm for an embedded system with limited memory. To achieve this, you need to implement an in-place merge sort, minimizing additional memory usage while maintaining the core characteristics and performance... | def in_place_merge_sort(arr):
"""
Perform in-place merge sort on the input list.
Parameters:
arr (List[int]): The list of integers to sort.
Returns:
List[int]: Sorted list using in-place merge sort.
"""
if arr is None or len(arr) <= 1:
return arr
def so... | from solution import in_place_merge_sort, in_place_merge
def test_in_place_merge_sort_empty():
assert in_place_merge_sort([]) == []
def test_in_place_merge_sort_single_element():
assert in_place_merge_sort([1]) == [1]
def test_in_place_merge_sort_sorted():
assert in_place_merge_sort([1, 2, 3, 4, 5]) == [... | [
{
"docstring": "Perform in-place merge sort on the input list.\n\nParameters:\n arr (List[int]): The list of integers to sort.\n \nReturns:\n List[int]: Sorted list using in-place merge sort.",
"function_declaration": "def in_place_merge_sort(arr):",
"function_name": "in_place_merge_sort",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def in_place_merge_sort(arr):\n \"\"\"\n Perform in-place merge sort on the input list.\n \n Parameters:\n arr (List[int]): The list of int... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026905",
"row_id": 26905,
"seed_ids": "[12]"
} | 0.589145 | Data_Structure_26905 | I | [
"in_place_merge_sort",
"in_place_merge"
] | 2 | [
[
"in_place_merge_sort",
"in_place_merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ba0364639591cdb5a460f1dcecd27cd51126f090 | 68f9e36e8ebd18dfff29fd68355d4dc8ca36e5fa | |||
v1.0 | instruct | Data_Structure | Data_Structure_26918_I | ### Question: Optimal Facility Placement on a Grid
You are tasked with building a new distribution center in a city represented by an `m x n` grid. The city's map is provided as a 2D grid where:
- `1` represents a building.
- `0` represents an empty land that can be chosen for the new distribution center.
- `2` repres... | from typing import List, Tuple
from collections import deque
def bfs(grid: List[List[int]], m: int, n: int, start_x: int, start_y: int) -> List[List[int]]:
distances = [[-1] * n for _ in range(m)]
queue = deque([(start_x, start_y, 0)])
while queue:
x, y, dist = queue.popleft()
for dx, dy in... | from solution import find_optimal_location
def test_case_1():
grid = [
[1, 0, 2, 0, 1],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0]
]
assert find_optimal_location(grid) == 7
def test_case_2():
grid = [
[1, 0],
[0, 0]
]
assert find_optimal_location(grid) == 1
def t... | [
{
"docstring": null,
"function_declaration": "def bfs(grid, m, n, start_x, start_y):",
"function_name": "bfs",
"parameter_list": "(grid, m, n, start_x, start_y)"
},
{
"docstring": null,
"function_declaration": "def find_optimal_location(grid):",
"function_name": "find_optimal_locatio... | [
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": "from typing import List\nfrom collections import deque\n\ndef find_optimal_location(grid: List[List[int]]) -> int:\n def bfs(start_row, start_col, dist, re... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00026918",
"row_id": 26918,
"seed_ids": "[185]"
} | 0.591959 | Data_Structure_26918 | I | [
"bfs",
"find_optimal_location"
] | 2 | [
[
"find_optimal_location",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e195524be6df5b9497256f04f146cff09fe271fc | 6502d34e6fd4e4177b34dda712923ab705e3604f | |||
v1.0 | instruct | Data_Structure | Data_Structure_26930_I | You are given two functions, `max_heap_sort` and `min_heap_sort`, which sort an array in ascending order using heap sort with max-heap and min-heap respectively. However, it is observed that `min_heap_sort` does not sort the array correctly. Investigate the `min_heap_sort` function to identify and correct the issue.
*... | def min_heapify(arr, n, i):
"""
Helper function to maintain the min-heap property
"""
smallest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] < arr[smallest]:
smallest = left
if right < n and arr[right] < arr[smallest]:
smallest = right
if smalles... | from solution import min_heap_sort, is_sorted
def test_min_heap_sort_simple():
arr = [3, 2, 1, 4, 5]
sorted_arr = min_heap_sort(arr)
assert is_sorted(sorted_arr) == True
assert sorted_arr == sorted(arr)
def test_min_heap_sort_with_negatives():
arr = [3, -2, 1, -4, 5]
sorted_arr = min_heap_sort... | [
{
"docstring": "Helper function to maintain the min-heap property",
"function_declaration": "def min_heapify(arr, n, i):",
"function_name": "min_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Sorts an array in ascending order using min-heap",
"function_declaration": "def mi... | [
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 min_heap_sort(arr):\n def heapify(arr, n, i):\n smallest = i\n l = 2 * i + 1\n r = 2 * i + 2\n \n if l < n and arr[l... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026930",
"row_id": 26930,
"seed_ids": "[8]"
} | 0.690401 | Data_Structure_26930 | I | [
"min_heapify",
"min_heap_sort",
"is_sorted"
] | 3 | [
[
"min_heap_sort",
"min_heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a0b8e7fa99e7610ca42533d138a47af68c213ebb | f1c5b29a0f22ec6371c0079623f9d72255f4385e | |||
v1.0 | instruct | Data_Structure | Data_Structure_26950_I | ### Question: Nearest Neighbor Classifier with Euclidean Distance
You need to implement the nearest neighbor algorithm to classify data points. You are provided with a function called `distance` that calculates the Euclidean distance between two vectors, and a partially implemented function `nearest_neighbor` that you... | from math import sqrt
from typing import Tuple, Dict
def distance(vec1: Tuple[float, ...], vec2: Tuple[float, ...]) -> float:
"""
Calculate the Euclidean distance between two vectors.
"""
return sqrt(sum((v1 - v2) ** 2 for v1, v2 in zip(vec1, vec2)))
def nearest_neighbor(x: Tuple[float, ...], tSet: Di... | from solution import nearest_neighbor
def test_basic_case():
tSet = {
(1.0, 2.0): 'A',
(2.0, 3.0): 'B',
(3.0, 4.0): 'C'
}
x = (2.5, 3.5)
assert nearest_neighbor(x, tSet) == 'B'
def test_exact_match():
tSet = {
(1.0, 2.0): 'A',
(2.5, 3.5): 'B',
(3.0, ... | [
{
"docstring": "Calculate the Euclidean distance between two vectors.",
"function_declaration": "def distance(vec1, vec2):",
"function_name": "distance",
"parameter_list": "(vec1, vec2)"
},
{
"docstring": "Find the label of the nearest neighbor to the vector `x` from the training set `tSet`.... | [
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 Tuple, Dict\n\ndef distance(a: Tuple[float, ...], b: Tuple[float, ...]) -> float:\n \"\"\"\n Returns the Euclidean distance between t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026950",
"row_id": 26950,
"seed_ids": "[260]"
} | 0.704364 | Data_Structure_26950 | I | [
"distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 866076eab8fd22b626edfb136430ed215ff0498b | eaaae09f40ad9585366bad68c786680a9ce0d204 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26967_I | ### RSA Encryption Algorithm Implementation and Analysis
#### Context
The RSA algorithm is crucial for secure communication in modern applications, from web browsing to secure email and digital signatures. As a cryptographer in training, you need to solidify your understanding of RSA by implementing an extended versio... | import random
from sympy import gcd, mod_inverse, isprime
def efficient_gen_prime(k, seed=None):
"""
Generates a prime number with k bits using a probabilistic approach.
Args:
k (int): Number of bits.
seed (int): Optional seed for deterministic randomness.
Returns:
int: A prime nu... | from solution import efficient_gen_prime, generate_key, validate_keys
def test_efficient_gen_prime():
# Check for 16-bit prime generation with a fixed seed
prime = efficient_gen_prime(16, seed=42)
assert prime.bit_length() == 16
assert isprime(prime)
def test_generate_key():
n, e, d = generate... | [
{
"docstring": "Generates a prime number with k bits using a probabilistic approach.\n\nArgs:\nk (int): Number of bits.\nseed (int): Optional seed for deterministic randomness.\n\nReturns:\nint: A prime number with k bits.",
"function_declaration": "def efficient_gen_prime(k, seed=None):",
"function_nam... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(n, k=30):\n \"\"\"\n Miller-Rabin primality test to check if n is a probable prime.\n \"\"\"\n if n in (2, 3):\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00026967",
"row_id": 26967,
"seed_ids": "[154]"
} | 0.612336 | Data_Structure_26967 | I | [
"efficient_gen_prime",
"generate_key",
"validate_keys"
] | 3 | [
[
"generate_key",
"efficient_gen_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 1d40e2ed06541b8c73e0792704b42aba8fecc4da | 9b2bf82d4b4bc9bd7312ee1f84765960888840d2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26984_I | As a software engineer at a security company, you need to implement an authentication feature that relies on prime numbers for encryption keys. Your task is to write a function to generate the first `k` prime numbers greater than or equal to a given integer n.
**Task**:
Write a function `generate_primes` that accepts ... | from typing import List
import math
def is_prime(num: int) -> bool:
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i +=... | from solution import generate_primes
def test_generate_primes_example1():
assert generate_primes(10, 5) == [11, 13, 17, 19, 23]
def test_generate_primes_example2():
assert generate_primes(50, 3) == [53, 59, 61]
def test_generate_primes_edge_case_small_n():
assert generate_primes(1, 5) == [2, 3, 5, 7, 11]... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def generate_primes(n, k):",
"function_name": "generate_primes",
"parameter_list": "(n, k)"
}
] | [
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\nimport math\n\ndef is_prime(num: int) -> bool:\n if num <= 1:\n return False\n if num <= 3:\n return True\n if... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00026984",
"row_id": 26984,
"seed_ids": "[143]"
} | 0.697495 | Data_Structure_26984 | I | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 16838b4e1304da1578979b1a08b842321c6c742d | b555b1bb5fe22ada0222af3aa661fadb82a4acf8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27001_I | ### Question
You are given three matrices: `matA`, `matB`, and `matC`, each of size `n x n`.
You are required to implement a function `matrix_operations` that takes these matrices along with an integer `p` as inputs and returns the product of the following operations:
1. Matrix multiplication of `matA` and `matB`.
2... | def matrix_multiply(mat1, mat2):
"""
Multiplies two matrices mat1 and mat2.
"""
n = len(mat1)
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += mat1[i][k] * mat2[k][j]
return result
def... | from solution import matrix_operations
def test_matrix_operations_basic():
matA = [
[1, 2],
[3, 4]
]
matB = [
[5, 6],
[7, 8]
]
matC = [
[2, 0],
[0, 2]
]
p = 2
expected_result = [
[76, 88],
[172, 200]
]
assert matrix... | [
{
"docstring": "Multiplies two matrices mat1 and mat2.",
"function_declaration": "def matrix_multiply(mat1, mat2):",
"function_name": "matrix_multiply",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": "Raises matrix mat to the power of `power`.\nUses exponentiation by squaring for efficie... | [
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": "def matrix_multiply(mat1, mat2):\n n = len(mat1)\n result = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00027001",
"row_id": 27001,
"seed_ids": "[340]"
} | 0.531089 | Data_Structure_27001 | I | [
"matrix_multiply",
"matrix_exponentiate",
"matrix_operations"
] | 3 | [
[
"matrix_exponentiate",
"matrix_multiply"
],
[
"matrix_operations",
"matrix_exponentiate"
],
[
"matrix_operations",
"matrix_multiply"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 68a0f930369567fc248ba0623afc3fcebc32159d | aa522def94b58bd38a5af15f14d59a76834f2328 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27043_I | #### Problem Statement
You are provided with two utility functions: `int_to_base` and `base_to_int` to convert numbers between integer form and base-represented strings. Your task is to implement a new function called `convert_base` that leverages these utilities to convert a number represented as a string in one base ... | def int_to_base(number, base):
"""
Converts an integer to its string representation in a specified base.
"""
if number == 0:
return "0"
digits = []
while number:
digits.append(int(number % base))
number //= base
return ''.join(chr(digit + ord('0')) if digit < 10 else ... | from solution import int_to_base, base_to_int, convert_base
def test_int_to_base():
assert int_to_base(5, 2) == "101"
assert int_to_base(255, 16) == "FF"
assert int_to_base(10, 10) == "10"
assert int_to_base(0, 10) == "0"
assert int_to_base(35, 36) == "Z"
def test_base_to_int():
assert base_to... | [
{
"docstring": "Converts an integer to its string representation in a specified base.",
"function_declaration": "def int_to_base(number, base):",
"function_name": "int_to_base",
"parameter_list": "(number, base)"
},
{
"docstring": "Converts a string representation of a number in a specified ... | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def int_to_base(num, base):\n \"\"\"\n Converts an integer to a base-represented string.\n \"\"\"\n if num == 0:\n return \"0\"\n digits... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00027043",
"row_id": 27043,
"seed_ids": "[164]"
} | 0.817644 | Data_Structure_27043 | I | [
"int_to_base",
"base_to_int",
"convert_base"
] | 3 | [
[
"convert_base",
"base_to_int"
],
[
"convert_base",
"int_to_base"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5d3e56072e20655297e4b2bf1ebd7e7f668f3e20 | 8a19ca25fca7eed503e2c3293af20b28ad535018 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27133_I | Optimized Very Large Array Sort
**Scenario**:
You have been appointed as a software engineer at a logistics company. Your task is to write a function that sorts arrays of shipment weights. Some arrays might be very large or almost sorted. To accommodate this, you will enhance an existing sorting algorithm.
**Task**:
... | def binary_search(arr, val, start, end):
"""
Perform binary search to find the index at which val should be inserted
in the subarray arr[start:end]. Return the appropriate index.
"""
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
start = mid + 1
el... | from solution import optimized_insertion_sort
def test_optimized_insertion_sort_unsorted_array():
assert optimized_insertion_sort([8, 3, 5, 4, 2, 7]) == [2, 3, 4, 5, 7, 8]
def test_optimized_insertion_sort_sorted_array():
assert optimized_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_optimized_... | [
{
"docstring": "Perform binary search to find the index at which val should be inserted\nin the subarray arr[start:end]. Return the appropriate index.",
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
... | [
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_insertion_sort(arr):\n \"\"\"\n Enhanced insertion sort algorithm with binary search to find \n the correct insertion position.\n \"... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027133",
"row_id": 27133,
"seed_ids": "[7]"
} | 0.536828 | Data_Structure_27133 | I | [
"binary_search",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 815fc07154c2481f516c38dfe65f7b81c0eec1c2 | 0a2489e82837b195e72e594e3daa54c3ced2a98b | |||
v1.0 | instruct | Data_Structure | Data_Structure_27178_I | You are to implement two functions as described in the following tasks:
1. **Implement the Extended GCD Algorithm**: Write a function `extended_gcd(a: int, b: int) -> (int, int, int)` that returns a tuple `(s, t, g)` such that `a * s + b * t = g` where `g` is the greatest common divisor (GCD) of `a` and `b`.
2. **Imp... | def extended_gcd(a, b):
"""
Returns a tuple (s, t, g) such that a * s + b * t = g where g is the greatest common divisor of a and b.
"""
if b == 0:
return 1, 0, a
else:
s, t, g = extended_gcd(b, a % b)
return t, s - (a // b) * t, g
def modular_inverse(a, m):
"""
Retu... | from solution import extended_gcd, modular_inverse
def test_extended_gcd():
# Basic tests
assert extended_gcd(30, 20) == (1, -1, 10)
assert extended_gcd(35, 15) == (1, -2, 5)
assert extended_gcd(101, 10) == (1, -10, 1)
# Edge cases
assert extended_gcd(1, 1) == (0, 1, 1)
assert extended_gcd... | [
{
"docstring": "Returns a tuple (s, t, g) such that a * s + b * t = g where g is the greatest common divisor of a and b.",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns an integer x such that (a * x) ... | [
0,
0,
1,
1,
0,
0,
0,
1,
0
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def extended_gcd(a, b):\n \"\"\"\n Extended Euclidean Algorithm that computes the gcd of a and b\n while also finding coefficients s and t such that ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00027178",
"row_id": 27178,
"seed_ids": "[161]"
} | 0.624587 | Data_Structure_27178 | I | [
"extended_gcd",
"modular_inverse"
] | 2 | [
[
"modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4be4e24b7107f5c642c2a59578439684817df9ed | b8fb997e1d75be2e6134fada73a88d9c88900fb1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27182_I | ### Coding Problem: Enhanced Insertion Sort
**Context**:
You are tasked with implementing an enhanced version of insertion sort that leverages a binary search approach to find the appropriate insertion index. This will ensure that the sorting process performs better, particularly for larger datasets.
**Challenge**:
W... | from typing import List
def search_insert(arr: List[int], value: int) -> int:
"""
Helper function that uses binary search to find the index where the value should be inserted.
"""
low, high = 0, len(arr)
while low < high:
mid = (low + high) // 2
if arr[mid] < value:
low ... | from solution import enhanced_insertion_sort
def test_empty_array():
assert enhanced_insertion_sort([]) == []
def test_single_element_array():
assert enhanced_insertion_sort([1]) == [1]
def test_sorted_array():
assert enhanced_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_ar... | [
{
"docstring": "Helper function that uses binary search to find the index where the value should be inserted.",
"function_declaration": "def search_insert(arr, value):",
"function_name": "search_insert",
"parameter_list": "(arr, value)"
},
{
"docstring": "Sorts an array using an enhanced ins... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(arr: List[int], value: int) -> int:\n \"\"\"\n This function finds the index at which the value should be i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027182",
"row_id": 27182,
"seed_ids": "[199]"
} | 0.563156 | Data_Structure_27182 | I | [
"search_insert",
"enhanced_insertion_sort"
] | 2 | [
[
"enhanced_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 92a0b4f3a628c0f2f648842d1cd609484dd37108 | 93394c1e9322684807cb32badb6b41c8d458274e | |||
v1.0 | instruct | Data_Structure | Data_Structure_27192_I | ### Question
You are tasked with implementing a sorting function using the Bogo Sort algorithm. This algorithm repeatedly shuffles the array until it is sorted, checking after every shuffle to see if the array is in the correct order.
Write a function `bogo_sort` which takes a list of integers as input and returns th... | import random
def is_sorted(arr):
"""
Recursively checks if the array is sorted in ascending order.
"""
if len(arr) <= 1:
return True
return arr[0] <= arr[1] and is_sorted(arr[1:])
def bogo_sort(arr):
"""
Sorts the array using the highly inefficient Bogo Sort algorithm.
Repeate... | from solution import bogo_sort, is_sorted
import pytest
def test_is_sorted_single_element():
assert is_sorted([1]) == True
assert is_sorted([2]) == True
def test_is_sorted_multiple_elements():
assert is_sorted([1, 2, 3, 4, 5]) == True
assert is_sorted([1, 3, 2, 4, 5]) == False
assert is_sorted([5,... | [
{
"docstring": "Recursively checks if the array is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the array using the highly inefficient Bogo Sort algorithm.\nRepeatedly shuffles the... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Check if the list is sorted in ascending order.\n Returns True if sorted, False otherwise.\n \"\"\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027192",
"row_id": 27192,
"seed_ids": "[16]"
} | 0.582084 | Data_Structure_27192 | I | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 03a86f168fe5e0866f6b75db9ae867fa4b7c6a95 | dbce71425ad229449e5cbba7616cd8cd1c9ee5aa | |||
v1.0 | instruct | Data_Structure | Data_Structure_27228_I | ### Question: Shell Sort Implementation and Optimization
You are tasked with writing a function that implements Shell Sort with an optimized gap sequence. The goal is to sort an array of integers effectively and handle edge cases properly.
**Prompt**:
Implement the function `optimized_shell_sort` which takes a list o... | from typing import List
def optimized_shell_sort(arr: List[int]) -> List[int]:
n = len(arr)
gaps = _sedgewick_sequence(n)
for gap in gaps:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - ga... | from solution import optimized_shell_sort
def test_optimized_shell_sort_standard_case():
assert optimized_shell_sort([12, 34, 54, 2, 3]) == [2, 3, 12, 34, 54]
def test_optimized_shell_sort_with_repeated_elements():
assert optimized_shell_sort([6, 2, 5, 9, 0, 2]) == [0, 2, 2, 5, 6, 9]
assert optimized_shel... | [
{
"docstring": null,
"function_declaration": "def optimized_shell_sort(arr):",
"function_name": "optimized_shell_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def _sedgewick_sequence(n):",
"function_name": "_sedgewick_sequence",
"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 optimized_shell_sort(arr):\n \"\"\"\n Function to sort the array using optimized Shell Sort with Sedgewick gap sequence.\n \"\"\"\n # Sedgewic... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027228",
"row_id": 27228,
"seed_ids": "[22]"
} | 0.584768 | Data_Structure_27228 | I | [
"optimized_shell_sort",
"_sedgewick_sequence"
] | 2 | [
[
"optimized_shell_sort",
"_sedgewick_sequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fe4b6d5f638780879305197cc60ad168551ac20e | e26afd572de37889fcb5cdd78135d0622130f895 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27302_I | ### Question
#### Context
Bogo Sort is an intentionally inefficient sorting algorithm based on the generate-and-test paradigm. Given an array of integers, Bogo Sort repeatedly checks if the array is sorted and randomly shuffles it if it is not. Although highly impractical, this algorithm serves as a fascinating study ... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if the list is sorted in ascending order.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def custom_bogo_sort(arr: List[int]) -> List[int]:
"""
Sort the list using Bogo ... | from solution import custom_bogo_sort
def test_sorted_list():
assert custom_bogo_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list():
assert custom_bogo_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_empty_list():
assert custom_bogo_sort([]) == []
def test_single_element_list():
... | [
{
"docstring": "Helper function to check if the list is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sort the list using Bogo Sort algorithm",
"function_declaration": "def custom_bog... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Returns True if the array is sorted in ascending order, othe... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027302",
"row_id": 27302,
"seed_ids": "[16]"
} | 0.560737 | Data_Structure_27302 | I | [
"is_sorted",
"custom_bogo_sort"
] | 2 | [
[
"custom_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 76653914e89aca03c71c393ee2aa30c5b282796d | 53c3a606ee2fee93185155325f654663964f56a1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27303_I | ### KMP String Matching Implementation and Enhancement
Given the KMP algorithm for string matching, your task is to enhance its functionality by implementing a function that, in addition to finding all positions where the pattern occurs in the text, also returns the total number of occurrences of the pattern, and the ... | from typing import List, Tuple
def compute_pi_table(pattern: str) -> List[int]:
# pi[i] is the length of the longest proper prefix which is also a suffix for substring pattern[0:i+1]
pi = [0] * len(pattern)
k = 0
for i in range(1, len(pattern)):
while k > 0 and pattern[k] != pattern[i]:
... | from solution import enhanced_knuth_morris_pratt
def test_enhanced_knuth_morris_pratt_example_case():
text = 'hello there hero!'
pattern = 'he'
assert enhanced_knuth_morris_pratt(text, pattern) == ([0, 7, 12], 3, [0, 0])
def test_enhanced_knuth_morris_pratt_no_match():
text = 'abcdef'
pattern = 'g... | [
{
"docstring": null,
"function_declaration": "def compute_pi_table(pattern):",
"function_name": "compute_pi_table",
"parameter_list": "(pattern)"
},
{
"docstring": null,
"function_declaration": "def enhanced_knuth_morris_pratt(text, pattern):",
"function_name": "enhanced_knuth_morris... | [
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, Tuple\n\ndef build_pi_table(pattern: str) -> List[int]:\n \"\"\"\n Constructs the prefix table (pi table) for the given pattern... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027303",
"row_id": 27303,
"seed_ids": "[93]"
} | 0.568477 | Data_Structure_27303 | I | [
"compute_pi_table",
"enhanced_knuth_morris_pratt"
] | 2 | [
[
"enhanced_knuth_morris_pratt",
"compute_pi_table"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8d52513b82f2ee71c7603590e0608ab9f6b32479 | 9aa9efa385a93549dbf98779819c88e4d4315c7c | |||
v1.0 | instruct | Data_Structure | Data_Structure_27311_I | ### Question
#### Context:
You are tasked with analyzing the connectivity of a social network, represented as a graph where nodes are users and edges are friendships between users. You need to determine which users are reachable from a particular user, and also check if it's possible to visit all users starting from t... | def dfs_traverse(graph, start):
"""
Returns a set of nodes reachable from the start node using DFS.
"""
visited = set()
def dfs(node):
if node not in visited:
visited.add(node)
for neighbor in graph.get(node, []):
dfs(neighbor)
dfs(start)
... | from solution import dfs_traverse, bfs_traverse, is_connected
def test_dfs_traverse():
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
assert dfs_traverse(graph, 'A') == {'A', 'B', 'C', 'D', 'E'... | [
{
"docstring": "Returns a set of nodes reachable from the start node using DFS.",
"function_declaration": "def dfs_traverse(graph, start):",
"function_name": "dfs_traverse",
"parameter_list": "(graph, start)"
},
{
"docstring": "Returns a set of nodes reachable from the start node using BFS."... | [
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 dfs_traverse(graph, start):\n \"\"\"\n Returns a set of nodes reachable from the start node using DFS.\n \"\"\"\n visited = set()\n stack =... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027311",
"row_id": 27311,
"seed_ids": "[224]"
} | 0.594424 | Data_Structure_27311 | I | [
"dfs_traverse",
"bfs_traverse",
"is_connected"
] | 3 | [
[
"is_connected",
"bfs_traverse"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c6f88c2d93fc8560d7f3518c38c72b884e5f4dc5 | 79aa7601f223ad6cfdcd1b2a1f670c86a95713eb | |||
v1.0 | instruct | Data_Structure | Data_Structure_27314_I | **Context**:
You have been hired by a social networking company to analyze clusters of users who are all friends with each other. This analysis will help in determining closely-knit groups within the network, which can be useful for suggestions, targeted ads, and group activities.
**Task**:
Implement a function `find_... | from itertools import combinations
def is_clique(edges, vertices):
for v1, v2 in combinations(vertices, 2):
if v2 not in edges[v1]:
return False
return True
def find_all_cliques(edges: dict) -> list:
vertices = list(edges.keys())
n = len(vertices)
max_cliques = []
# Check ... | from solution import find_all_cliques
def test_simple_case():
edges = {
'1': {'2', '5'},
'2': {'1', '3'},
'3': {'2', '4'},
'4': {'3', '5'},
'5': {'1', '4'}
}
result = find_all_cliques(edges)
expected = [['1', '2'], ['2', '3'], ['3', '4'], ['4', '5'], ['1', '5']]
... | [
{
"docstring": null,
"function_declaration": "def is_clique(edges, vertices):",
"function_name": "is_clique",
"parameter_list": "(edges, vertices)"
},
{
"docstring": null,
"function_declaration": "def find_all_cliques(edges):",
"function_name": "find_all_cliques",
"parameter_list... | [
0,
0,
0,
0,
1,
0,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_all_cliques(edges):\n \"\"\"\n Find all maximal cliques in an undirected graph represented as an adjacency list.\n \"\"\"\n # Helper func... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00027314",
"row_id": 27314,
"seed_ids": "[236]"
} | 0.501421 | Data_Structure_27314 | I | [
"is_clique",
"find_all_cliques"
] | 2 | [
[
"find_all_cliques",
"is_clique"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 47fcaddbe40ca0f7aa0c8be531b71d10caf637a9 | 4a80c4c14deaaed1cd2154ab78343cb5597245f1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27348_I | You are tasked with implementing a function to verify two conditions for a given pair of integers:
1. Whether these two integers are co-prime (i.e., their greatest common divisor is 1).
2. If they are co-prime, find their modular inverse.
### Function Specification
Implement the function `modular_inverse(a: int, m: in... | def gcd(a, b):
while b:
a, b = b, a % b
return a
def modular_inverse(a, m):
"""
Returns whether a and m are coprime and the modular inverse of a under modulo m.
If they are not coprime, returns -1 as the modular inverse.
"""
if gcd(a, m) != 1:
return [False, -1]
# U... | from solution import modular_inverse
def test_modular_inverse_coprime():
result = modular_inverse(3, 11)
assert result == [True, 4], f"Expected [True, 4] but got {result}"
def test_modular_inverse_not_coprime():
result = modular_inverse(10, 20)
assert result == [False, -1], f"Expected [False, -1] ... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns whether a and m are coprime and the modular inverse of a under modulo m.\nIf they are not coprime, returns -1 as the modular inverse.",
"function_d... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"\n Helper function to compute the greatest common divisor (GCD) of a and b using the Euclidean algorithm.\n \"\"\"\n while ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00027348",
"row_id": 27348,
"seed_ids": "[161]"
} | 0.644435 | Data_Structure_27348 | I | [
"gcd",
"modular_inverse"
] | 2 | [
[
"modular_inverse",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a07243d0903b039ff82c89c7e6a750fb26054423 | e90e7ac0c481ca828f7e26c21d1b1cfe84330f43 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27350_I | ## Objective
Implement a function to encode a list of positive integers using Elias Gamma and Elias Delta codes and verify their correctness by decoding the encoded results back to integers.
## Description
Write the functions `elias_gamma_encode`, `elias_delta_encode`, `elias_gamma_decode`, and `elias_delta_decode` ... | def to_binary(n):
return bin(n)[2:]
def elias_gamma_encode(numbers):
encoded = []
for number in numbers:
binary_repr = to_binary(number)
length = len(binary_repr)
unary_repr = '0' * (length - 1) + '1'
encoded.append(unary_repr + binary_repr[1:])
return encoded
def elias... | from solution import elias_gamma_encode, elias_gamma_decode, elias_delta_encode, elias_delta_decode
def test_elias_gamma_encode_decode():
numbers = [1, 2, 3, 4, 5, 10, 100, 1000]
encoded = elias_gamma_encode(numbers)
decoded = elias_gamma_decode(encoded)
assert decoded == numbers
def test_elias_delta_... | [
{
"docstring": null,
"function_declaration": "def to_binary(n):",
"function_name": "to_binary",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def elias_gamma_encode(numbers):",
"function_name": "elias_gamma_encode",
"parameter_list": "(numbers)"
},
... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef elias_gamma_encode(numbers):\n encoded_numbers = []\n for number in numbers:\n n_bin = bin(number)[2:]\n n_len = len(n_... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00027350",
"row_id": 27350,
"seed_ids": "[333]"
} | 0.528807 | Data_Structure_27350 | I | [
"to_binary",
"elias_gamma_encode",
"elias_gamma_decode",
"elias_delta_encode",
"elias_delta_decode"
] | 5 | [
[
"elias_delta_encode",
"to_binary"
],
[
"elias_gamma_encode",
"to_binary"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4a6dd2ef631dd79799d9d22d842e72e9569a2b8b | 63d05224db5e6c46f1fa83341ab1c308b988f9bf | |||
v1.0 | instruct | Data_Structure | Data_Structure_27353_I | ### Question Statement
You are given a sorting algorithm called Bogo Sort which sorts an array by repeatedly shuffling it until it is sorted. The algorithm is highly inefficient but serves as a theoretical model for understanding randomness in sorting.
#### Task
Write a function `find_maximum_bogo_sort_iterations(arr)... | import random
def is_sorted(arr):
"""
Checks if a given array is sorted in non-decreasing order.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def bogo_sort(arr):
"""
Performs Bogo Sort on the array and returns the number of iteratio... | from solution import is_sorted, bogo_sort, find_maximum_bogo_sort_iterations
def test_is_sorted():
assert is_sorted([1, 2, 3])
assert not is_sorted([1, 3, 2])
assert is_sorted([5])
assert is_sorted([])
def test_bogo_sort_sorted_array():
arr = [1, 2, 3]
assert bogo_sort(arr) == 0 # Because it ... | [
{
"docstring": "Checks if a given array is sorted in non-decreasing order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Performs Bogo Sort on the array and returns the number of iterations.\nBogo Sort shuffles the... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if the array is sorted.\n \"\"\"\n return all(arr[i] <= arr[i+1] for i in... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027353",
"row_id": 27353,
"seed_ids": "[16]"
} | 0.595445 | Data_Structure_27353 | I | [
"is_sorted",
"bogo_sort",
"find_maximum_bogo_sort_iterations"
] | 3 | [
[
"bogo_sort",
"is_sorted"
],
[
"find_maximum_bogo_sort_iterations",
"bogo_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d7227adcd8f31d179165a54a5666ce9f59836e24 | 244bf2990e98e021758a1fee5d38238d89a03c62 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27364_I | **Problem**: Maximum Clique Identification with Filtering
You are given an undirected graph represented as an adjacency list. Your task is to identify all maximal cliques in the graph using the Bron-Kerbosch algorithm and further filter these cliques to only return those cliques whose size is above a given threshold.
... | def bron_kerbosch(R, P, X, edges, cliques):
"""
Bron-Kerbosch recursive algorithm to find all maximal cliques.
"""
if not P and not X:
cliques.append(R)
return
for v in list(P):
bron_kerbosch(R | {v}, P & edges[v], X & edges[v], edges, cliques)
P.remove(v)
X.a... | from solution import filter_cliques
def test_filter_cliques():
edges = {
"1": {"2", "3"},
"2": {"1", "3", "4"},
"3": {"1", "2", "4"},
"4": {"2", "3"}
}
threshold = 2
expected = [["1", "2", "3"], ["2", "3", "4"]]
result = filter_cliques(edges, threshold)
assert le... | [
{
"docstring": "Bron-Kerbosch recursive algorithm to find all maximal cliques.",
"function_declaration": "def bron_kerbosch(R, P, X, edges, cliques):",
"function_name": "bron_kerbosch",
"parameter_list": "(R, P, X, edges, cliques)"
},
{
"docstring": "Given an undirected graph represented by ... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bron_kerbosch(r, p, x, graph, cliques):\n if not p and not x:\n cliques.append(r)\n return\n for v in list(p):\n bron_kerbosch(... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00027364",
"row_id": 27364,
"seed_ids": "[236]"
} | 0.525474 | Data_Structure_27364 | I | [
"bron_kerbosch",
"filter_cliques"
] | 2 | [
[
"filter_cliques",
"bron_kerbosch"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1c0d20b7bbed347ebb0826746c32108691521618 | 55203b34a9e41c9c7d71100562b3076ad8144037 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27375_I | Implementing RSA Key Generation
#### Context:
You are tasked with building a secure communication system and decide to use the RSA algorithm for encrypting messages. The core part of this implementation involves generating the RSA keys correctly. Your job is to refine and complete the RSA key generation function.
###... | import random
from sympy import isprime
from sympy import mod_inverse
def generate_prime_candidate(bits):
"""Generate an odd integer randomly"""
p = random.getrandbits(bits)
# apply a mask to set MSB and LSB to 1
p |= (1 << bits - 1) | 1
return p
def generate_prime_number(bits):
"""Generate a ... | from solution import generate_key
def test_generate_key_returns_three_integers():
n, e, d = generate_key(32, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
def test_encryption_decryption():
k = 32
seed = 42
n, e, d = generate_key(k, seed)
origin... | [
{
"docstring": "Generate an odd integer randomly",
"function_declaration": "def generate_prime_candidate(bits):",
"function_name": "generate_prime_candidate",
"parameter_list": "(bits)"
},
{
"docstring": "Generate a prime number of bit length `bits`",
"function_declaration": "def generat... | [
0,
0,
0,
0,
0,
0,
1,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\nfrom math import gcd\n\ndef generate_large_prime(bits, seed=None):\n if seed is not None:\n r... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00027375",
"row_id": 27375,
"seed_ids": "[154]"
} | 0.591092 | Data_Structure_27375 | I | [
"generate_prime_candidate",
"generate_prime_number",
"generate_key"
] | 3 | [
[
"generate_key",
"generate_prime_number"
],
[
"generate_prime_number",
"generate_prime_candidate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 392a94d5731caea3233d5b2939a2abf57d24f591 | 28ed0fe5396590adb6814f75ac92b7ba8a418655 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27379_I | You are tasked with converting a given Binary Tree into a doubly linked list. The doubly linked list should be sorted if the tree is a Binary Search Tree. Each node in the doubly linked list should have two pointers (`left` for the previous node and `right` for the next node), and it should be created in an in-order fa... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def bin_tree_to_list(root: TreeNode) -> TreeNode:
if not root:
return None
# Initialize the previous node as None
bin_tree_to_list_util.prev = None
... | import pytest
from solution import TreeNode, bin_tree_to_list, print_list
def test_empty_tree():
assert bin_tree_to_list(None) == None
def test_single_node_tree():
root = TreeNode(1)
head = bin_tree_to_list(root)
assert head.val == 1
assert head.left == None
assert head.right == None
def test... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef bi... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027379",
"row_id": 27379,
"seed_ids": "[293]"
} | 0.502788 | Data_Structure_27379 | I | [
"bin_tree_to_list",
"bin_tree_to_list_util",
"print_list"
] | 3 | [
[
"bin_tree_to_list",
"bin_tree_to_list_util"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 1ed8b6744fcca7f7b1223dcf988dafce3236eb75 | 46475912b8572d54bb93d77e6d803c649f4a9cb1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27382_I | Radix Sort Implementation with Simulation Mode
**Context**:
You are given a list of non-negative integers and required to sort them using Radix Sort. Radix Sort processes each digit of the numbers, starting from the least significant digit to the most significant digit.
In this exercise, you will implement the Radix... | from typing import List
def counting_sort_for_radix(arr: List[int], exp: int) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i] += count[i - 1]
... | from solution import radix_sort
def test_radix_sort_empty():
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort([5]) == [5]
def test_radix_sort_already_sorted():
assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_radix_sort_reverse_sorted():
assert radix_... | [
{
"docstring": null,
"function_declaration": "def counting_sort_for_radix(arr, exp):",
"function_name": "counting_sort_for_radix",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort",
... | [
1,
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_for_radix(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n \n output = [0] * n\n count = [0] ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00027382",
"row_id": 27382,
"seed_ids": "[15]"
} | 0.630452 | Data_Structure_27382 | I | [
"counting_sort_for_radix",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort_for_radix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c57b802671b2c13203665e19df10a387680e03b0 | 412d4d2fa9b7bf4d739db75552a04c389238feb6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27429_I | ### Matrix Exponentiation and Multiplication
You have been provided functions for matrix multiplication, identity matrix creation, and matrix exponentiation.
You are tasked to implement a function `pow_matrix_sum(mat: list, exponents: list) -> list` that calculates the sum of a matrix raised to multiple powers.
####... | def multiply(mat1, mat2):
"""
Multiplies two matrices mat1 and mat2.
"""
n = len(mat1)
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += mat1[i][k] * mat2[k][j]
return result
def identi... | from solution import multiply, identity, matrix_exponentiation, pow_matrix_sum
def test_multiply():
assert multiply([[1, 2], [3, 4]], [[1, 0], [0, 1]]) == [[1, 2], [3, 4]]
assert multiply([[1]], [[1]]) == [[1]]
assert multiply([[0, 1], [1, 0]], [[1, 2], [3, 4]]) == [[3, 4], [1, 2]]
def test_identity():
... | [
{
"docstring": "Multiplies two matrices mat1 and mat2.",
"function_declaration": "def multiply(mat1, mat2):",
"function_name": "multiply",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": "Returns an identity matrix of given size.",
"function_declaration": "def identity(size):",
"f... | [
0,
0,
1,
1,
0,
0,
0,
1,
0
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply(mat1, mat2):\n \"\"\"\n Multiplies two matrices mat1 and mat2.\n \"\"\"\n n = len(mat1)\n result = [[0] * n for _ in range(n)]\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00027429",
"row_id": 27429,
"seed_ids": "[340]"
} | 0.53244 | Data_Structure_27429 | I | [
"multiply",
"identity",
"matrix_exponentiation",
"pow_matrix_sum"
] | 4 | [
[
"matrix_exponentiation",
"identity"
],
[
"matrix_exponentiation",
"multiply"
],
[
"pow_matrix_sum",
"matrix_exponentiation"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 973a5371adc425679106634340e188fc4e744a88 | 5c612ed826a1bdb9408ac48859bd7441545a601b | |||
v1.0 | instruct | Data_Structure | Data_Structure_27489_I | ### Advanced String Matching
As a software developer, you are tasked with creating a function that leverages an advanced string matching algorithm to search for a pattern in a large body of text. The requirement is to implement the Knuth-Morris-Pratt (KMP) string matching algorithm.
#### Task
Write a function `detec... | from typing import List
def compute_prefix_function(pattern: str) -> List[int]:
"""
Computes the prefix function for the Knuth-Morris-Pratt algorithm.
"""
m = len(pattern)
pi = [0] * m
k = 0
for q in range(1, m):
while k > 0 and pattern[k] != pattern[q]:
k = pi[k - ... | from solution import detect_pattern_occurrences
def test_detect_pattern_occurrences_basic():
assert detect_pattern_occurrences('hello there hero!', 'he') == [0, 7, 12]
def test_empty_text():
assert detect_pattern_occurrences('', 'he') == []
def test_empty_pattern():
assert detect_pattern_occurrences('hel... | [
{
"docstring": "Computes the prefix function for the Knuth-Morris-Pratt algorithm.",
"function_declaration": "def compute_prefix_function(pattern):",
"function_name": "compute_prefix_function",
"parameter_list": "(pattern)"
},
{
"docstring": "Uses the KMP algorithm to find and return the sta... | [
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 build_lps(pattern: str) -> List[int]:\n \"\"\"\n Builds the longest prefix suffix (LPS) array used in KMP algorithm.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027489",
"row_id": 27489,
"seed_ids": "[93]"
} | 0.615944 | Data_Structure_27489 | I | [
"compute_prefix_function",
"detect_pattern_occurrences"
] | 2 | [
[
"detect_pattern_occurrences",
"compute_prefix_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9a6d62e694219011ee5063f9fd2464e89bb49269 | 581079deae60e0ffb9b90fe4cafd5eb68842a7cb | |||
v1.0 | instruct | Data_Structure | Data_Structure_27525_I | ### Prime Numbers and their Neighbors
You are tasked to implement a function `find_prime_neighbors(n)`, which finds the closest prime numbers that are smaller and larger than a given positive integer `n`.
#### Detailed Description & Requirements:
1. **Input**: An integer `n` (1 ≤ n ≤ 10^7).
2. **Output**: A tuple of ... | def prime_check(n):
"""Return True if n is a prime number
Else return False.
"""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
j = 5
while j * j <= n:
if n % j == 0 or n % (j + 2) == 0:
retur... | from solution import find_prime_neighbors
def test_find_prime_neighbors():
assert find_prime_neighbors(10) == (7, 11)
assert find_prime_neighbors(6) == (5, 7)
assert find_prime_neighbors(2) == (-1, 3)
assert find_prime_neighbors(1) == (-1, 2)
assert find_prime_neighbors(3) == (2, 5)
assert find... | [
{
"docstring": "Return True if n is a prime number\nElse return False.",
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": "Finds the closest prime numbers smaller and larger than a given positive integer n.",
"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": "def prime_check(n):\n \"\"\"Return True if n is a prime number\n Else return False.\n \"\"\"\n if n <= 1:\n return False\n if n == 2 or ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00027525",
"row_id": 27525,
"seed_ids": "[143]"
} | 0.649043 | Data_Structure_27525 | I | [
"prime_check",
"find_prime_neighbors"
] | 2 | [
[
"find_prime_neighbors",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ccf3f1112a374787b48d2fa94cced69405f68787 | 8d94d9c4c4abb6aca3d59b7efe3d8a4640b73e0c | |||
v1.0 | instruct | Data_Structure | Data_Structure_27534_I | ### Coding Challenge
**Context**: In many applications, such as search engines, recommendation systems, and data clustering, measuring the similarity between vectors is crucial. Cosine similarity is an effective method to ascertain the degree of similarity between two vectors.
**Problem Statement**: Write a Python fu... | import math
def dot_product(v1, v2):
return sum(x * y for x, y in zip(v1, v2))
def magnitude(v):
return math.sqrt(sum(x ** 2 for x in v))
def cosine_similarity(v1, v2):
return dot_product(v1, v2) / (magnitude(v1) * magnitude(v2))
def generalized_cosine_similarity(vectors):
if not vectors or not vect... | from solution import generalized_cosine_similarity
def test_generalized_cosine_similarity_with_simple_vectors():
vectors = [
[1, 1, 1],
[1, 2, -1]
]
expected = [
[1.0, 0.47140452079103173],
[0.47140452079103173, 1.0]
]
result = generalized_cosine_similarity(vectors... | [
{
"docstring": null,
"function_declaration": "def dot_product(v1, v2):",
"function_name": "dot_product",
"parameter_list": "(v1, v2)"
},
{
"docstring": null,
"function_declaration": "def magnitude(v):",
"function_name": "magnitude",
"parameter_list": "(v)"
},
{
"docstring... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import List\n\ndef generalized_cosine_similarity(vectors: List[List[float]]) -> List[List[float]]:\n n = len(vectors)\n m = len... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027534",
"row_id": 27534,
"seed_ids": "[149]"
} | 0.651552 | Data_Structure_27534 | I | [
"dot_product",
"magnitude",
"cosine_similarity",
"generalized_cosine_similarity"
] | 4 | [
[
"cosine_similarity",
"dot_product"
],
[
"cosine_similarity",
"magnitude"
],
[
"generalized_cosine_similarity",
"cosine_similarity"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 5d889d3a086f31596c8144f67a1cca605b79333e | b87f91050ce7292752f4a94ce2ccb4a2ffbfcfda | |||
v1.0 | instruct | Data_Structure | Data_Structure_27570_I | ### Fibonacci Sequence Algorithm Implementation
#### Objective
You are provided with code snippets that compute the nth Fibonacci number using different algorithmic approaches: Recursive, Dynamic Programming, and Iterative. Your task is to write a Python function that computes the nth Fibonacci number using the **Matr... | def matrix_mult(A, B):
# Multiplies two 2x2 matrices A and B
return [[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]]
def matrix_pow(matrix, n):
# Exponentiates matrix using binary exp... | from solution import fib_matrix_exp
def test_fib_matrix_exp_0():
assert fib_matrix_exp(0) == 0
def test_fib_matrix_exp_1():
assert fib_matrix_exp(1) == 1
def test_fib_matrix_exp_2():
assert fib_matrix_exp(2) == 1
def test_fib_matrix_exp_3():
assert fib_matrix_exp(3) == 2
def test_fib_matrix_exp_10(... | [
{
"docstring": null,
"function_declaration": "def matrix_mult(A, B):",
"function_name": "matrix_mult",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def matrix_pow(matrix, n):",
"function_name": "matrix_pow",
"parameter_list": "(matrix, 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": "def matrix_mult(A, B):\n # Multiplies two 2x2 matrices A and B\n 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]],... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00027570",
"row_id": 27570,
"seed_ids": "[37]"
} | 0.732431 | Data_Structure_27570 | I | [
"matrix_mult",
"matrix_pow",
"fib_matrix_exp"
] | 3 | [
[
"fib_matrix_exp",
"matrix_pow"
],
[
"matrix_pow",
"matrix_mult"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 497e42da3025cb309740edbc009707b1e7dac325 | 46cf7ace60182e6fa30f07c8ed05596aff2cf13e | |||
v1.0 | instruct | Data_Structure | Data_Structure_27590_I | ### Diffie-Hellman Key Exchange Implementation
#### Objective
Implement the `diffie_hellman_key_exchange` function using Diffie-Hellman algorithm principles. Your task also includes creating a prime-checking function and finding a primitive root related to the given prime.
#### Detailed Requirements
1. **Functions t... | def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i ** 2 <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
def find_primitive_root(p):
... | import pytest
from solution import is_prime, find_primitive_root, diffie_hellman_key_exchange
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(13) == True
assert is_prime(25) == False
def test_find... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def find_primitive_root(p):",
"function_name": "find_primitive_root",
"parameter_list": "(p)"
},
{
"d... | [
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import random\n\ndef prime_check(num):\n if num < 2:\n return False\n for i in range(2, int(num**0.5) + 1):\n if ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00027590",
"row_id": 27590,
"seed_ids": "[146]"
} | 0.513193 | Data_Structure_27590 | I | [
"is_prime",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 3 | [
[
"diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"diffie_hellman_key_exchange",
"is_prime"
],
[
"find_primitive_root",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 147a74a59077f70f92c156dac22b84676bba6e61 | 1db933d814173a3573751fc917c72579e911cbb5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27643_I | ### Assignment: Optimized GCD and LCM Calculation
You are tasked with implementing and optimizing a set of utility functions for computing the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) for two integers. In addition to the traditional approach, you need to ensure that bitwise operations are leverage... | def gcd(a, b):
"""Compute the Greatest Common Divisor (GCD) of two integers using Euclid's algorithm."""
if a <= 0 or b <= 0:
raise ValueError("Both a and b should be positive integers.")
while b:
a, b = b, a % b
return a
def trailing_zero(x):
"""Count the number of trailing zeros i... | import pytest
from solution import gcd, lcm, trailing_zero, gcd_bit
def test_gcd():
assert gcd(48, 18) == 6
assert gcd(5, 3) == 1
assert gcd(1, 1) == 1
with pytest.raises(ValueError):
gcd(0, 10)
with pytest.raises(ValueError):
gcd(10, 0)
with pytest.raises(ValueError):
... | [
{
"docstring": "Compute the Greatest Common Divisor (GCD) of two integers using Euclid's algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Count the number of trailing zeros in the binary representation of x.",
"f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a: int, b: int) -> int:\n if a <= 0 or b <= 0:\n raise ValueError(\"Both numbers must be positive integers.\")\n \n while b:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027643",
"row_id": 27643,
"seed_ids": "[166]"
} | 0.639106 | Data_Structure_27643 | I | [
"gcd",
"trailing_zero",
"gcd_bit",
"lcm"
] | 4 | [
[
"gcd_bit",
"trailing_zero"
],
[
"lcm",
"gcd"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 19051e141993713174c26254a8e128c2b43ae916 | 90d9d6cdac4047eb20af56cc19d483bdf0e66884 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27663_I | Implement an Optimized Random Sorting Algorithm
#### Context
Bogo Sort is a humorous yet impractical sorting algorithm that works by randomly shuffling an array until it is sorted. You are tasked with creating a more practical version of a similarly random-based sorting algorithm, called **Improved Randomized Sort**, ... | import random
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def randomized_partition(arr, low, high):
... | from solution import improved_random_sort
def test_empty_list():
assert improved_random_sort([]) == []
def test_single_element():
assert improved_random_sort([1]) == [1]
def test_sorted_list():
assert improved_random_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list():
assert imp... | [
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def randomized_partition(arr, low, high):",
"function_name": "randomized_partition",
... | [
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 partition(arr: List[int], low: int, high: int) -> int:\n pivot = arr[high]\n i = low - 1\n for j in ran... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027663",
"row_id": 27663,
"seed_ids": "[16]"
} | 0.648561 | Data_Structure_27663 | I | [
"partition",
"randomized_partition",
"randomized_quick_sort",
"improved_random_sort"
] | 4 | [
[
"improved_random_sort",
"randomized_quick_sort"
],
[
"randomized_partition",
"partition"
],
[
"randomized_quick_sort",
"randomized_partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 5ab270a97123298798a33b5234c88805d95152cc | 2269cb50221baad847f7d8e5d959b91f794690da | |||
v1.0 | instruct | Data_Structure | Data_Structure_27682_I | ### Question: Advanced Palindrome Checker
Implement a Python function that checks if a given string is a palindrome, considering only alphanumeric characters and ignoring case. Additionally, the function should address the following requirements:
1. Handle mixed case and punctuation by normalizing the string to lower... | import re
from collections import deque
def normalize_string(s):
return re.sub(r'[^a-zA-Z0-9]', '', s).lower()
def check_palindrome_two_pointer(s):
normalized = normalize_string(s)
left, right = 0, len(normalized) - 1
while left < right:
if normalized[left] != normalized[right]:
re... | from solution import check_palindrome
def test_two_pointer_method():
assert check_palindrome("A man, a plan, a canal: Panama", "two_pointer") == True
assert check_palindrome("race a car", "two_pointer") == False
assert check_palindrome("", "two_pointer") == True
assert check_palindrome(" ", "two_pointe... | [
{
"docstring": null,
"function_declaration": "def normalize_string(s):",
"function_name": "normalize_string",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def check_palindrome_two_pointer(s):",
"function_name": "check_palindrome_two_pointer",
"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": "import collections\n\ndef normalize_string(s: str) -> str:\n \"\"\"\n Removes non-alphanumeric characters from a string and converts to lowercase.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027682",
"row_id": 27682,
"seed_ids": "[70]"
} | 0.785353 | Data_Structure_27682 | I | [
"normalize_string",
"check_palindrome_two_pointer",
"check_palindrome_reverse",
"check_palindrome_stack",
"check_palindrome_deque",
"check_palindrome"
] | 6 | [
[
"check_palindrome",
"check_palindrome_deque"
],
[
"check_palindrome",
"check_palindrome_reverse"
],
[
"check_palindrome",
"check_palindrome_stack"
],
[
"check_palindrome",
"check_palindrome_two_pointer"
],
[
"check_palindrome_deque",
"normalize_string"
],
... | 8 | [] | false | [] | false | pytest | true | [] | true | 0f2933183940b425fdef05e90235c98e940db57c | 33bfc4e6950641f0dc0db711d97c28bc2bd5c527 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27689_I | Implementing and Enhancing Diffie-Hellman Key Exchange
The goal of this question is to verify your understanding of the Diffie-Hellman key exchange process and associated number-theoretic functions. You will implement an enhanced Diffie-Hellman key exchange algorithm incorporating optimized versions of prime checking,... | import math
from typing import List, Optional
def optimized_prime_check(num: int) -> bool:
"""
Efficiently checks if a number is prime.
:param num: An integer to check for primality (1 <= num <= 10^12).
:return: True if `num` is a prime number, False otherwise.
"""
if num <= 1:
ret... | from solution import optimized_prime_check, optimized_find_primitive_root, enhanced_diffie_hellman_key_exchange
def test_optimized_prime_check():
assert optimized_prime_check(2) is True
assert optimized_prime_check(3) is True
assert optimized_prime_check(4) is False
assert optimized_prime_check(5) is T... | [
{
"docstring": "Efficiently checks if a number is prime.\n\n:param num: An integer to check for primality (1 <= num <= 10^12).\n:return: True if `num` is a prime number, False otherwise.",
"function_declaration": "def optimized_prime_check(num):",
"function_name": "optimized_prime_check",
"parameter... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef optimized_prime_check(num: int) -> bool:\n \"\"\"Returns True if num is a prime number, False otherwise.\"\"\"\n if num <= 1:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00027689",
"row_id": 27689,
"seed_ids": "[146]"
} | 0.511653 | Data_Structure_27689 | I | [
"optimized_prime_check",
"optimized_find_primitive_root",
"enhanced_diffie_hellman_key_exchange"
] | 3 | [
[
"enhanced_diffie_hellman_key_exchange",
"optimized_find_primitive_root"
],
[
"enhanced_diffie_hellman_key_exchange",
"optimized_prime_check"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 69c44bf175b9d4450e7143753b0b43c9c950b06f | eb5099474176e1c4212b72d6b9d0a1527f006e34 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27759_I | ### Question:
**Strongly Connected Graph Detection**
In graph theory, a *strongly connected component* (SCC) of a directed graph is a maximal strongly connected subgraph. A directed graph is said to be strongly connected if there is a path in each direction between each pair of vertices of the graph (i.e., from each ... | from typing import List, Tuple
def dfs(graph: List[List[int]], start: int, visited: List[bool]):
stack = [start]
while stack:
node = stack.pop()
for neighbor in graph[node]:
if not visited[neighbor]:
visited[neighbor] = True
stack.append(neighbor)
de... | from solution import is_strongly_connected
def test_strongly_connected():
# Fully connected simple graph
assert is_strongly_connected(3, [(0, 1), (1, 2), (2, 0)]) == True
def test_not_strongly_connected():
# Not strongly connected graph with one disconnected node
assert is_strongly_connected(4, [(0, 1... | [
{
"docstring": null,
"function_declaration": "def dfs(graph, start, visited):",
"function_name": "dfs",
"parameter_list": "(graph, start, visited)"
},
{
"docstring": null,
"function_declaration": "def is_strongly_connected(vertex_count, edges):",
"function_name": "is_strongly_connect... | [
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\nfrom collections import defaultdict, deque\n\ndef is_strongly_connected(vertex_count: int, edges: List[Tuple[int, int]]) -> bo... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027759",
"row_id": 27759,
"seed_ids": "[225]"
} | 0.550314 | Data_Structure_27759 | I | [
"dfs",
"is_strongly_connected"
] | 2 | [
[
"is_strongly_connected",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ac3f31bfbd17fae80ad4b8284282215b620bf95b | 0474ab3335ad9a5badd311c1eec4a317a7d7d356 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27778_I | You are provided an array of integers. Your task is to implement the Merge Sort algorithm to sort the array in ascending order. Your implementation must adhere to the following requirements and constraints:
#### Input
* An array `arr` with `n` integers, where `0 <= n <= 10^5` and `-10^9 <= arr[i] <= 10^9`.
#### Outpu... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
# Split the array into two halves
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
# Merge the two halves
return merge(left_half, right_hal... | from solution import merge_sort
def test_empty_array():
assert merge_sort([]) == []
def test_single_element_array():
assert merge_sort([1]) == [1]
assert merge_sort([-1]) == [-1]
def test_sorted_array():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
assert merge_sort([-5, -4, -3, -2, -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)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts the given array in ascending order using the Merge Sort algorit... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027778",
"row_id": 27778,
"seed_ids": "[12]"
} | 0.701057 | Data_Structure_27778 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4bae84e6720f8cbbb3f1d05e0bc419c3ae247271 | 7ea9e63fb50b94d622ed68101023859f4bdf79a0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_27789_I | ### Question
You are required to implement a function that multiplies two positive integers using only bitwise operations and addition (which we've covered already) and returns the product. This exercise will assess your understanding of bitwise manipulation and fundamental arithmetic operations without relying on dire... | def add_bitwise(a, b):
"""
Function to add two integers using only bitwise operations.
"""
while b != 0:
carry = a & b
a = a ^ b
b = carry << 1
return a
def multiply_bitwise(a: int, b: int) -> int:
"""
Multiplies two positive integers using bitwise operations and add... | from solution import multiply_bitwise
def test_multiply_bitwise_positive_numbers():
assert multiply_bitwise(3, 5) == 15
assert multiply_bitwise(6, 7) == 42
assert multiply_bitwise(10, 10) == 100
assert multiply_bitwise(2, 8) == 16
assert multiply_bitwise(1234, 5678) == 7006652
def test_multiply_bi... | [
{
"docstring": "Function to add two integers using only bitwise operations.",
"function_declaration": "def add_bitwise(a, b):",
"function_name": "add_bitwise",
"parameter_list": "(a, b)"
},
{
"docstring": "Multiplies two positive integers using bitwise operations and addition.",
"functio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n \"\"\"\n Returns the sum of a and b using bitwise operations.\n \"\"\"\n while b != 0:\n carry = a & b\n a = a ^ b\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027789",
"row_id": 27789,
"seed_ids": "[209]"
} | 0.730043 | Data_Structure_27789 | I | [
"add_bitwise",
"multiply_bitwise"
] | 2 | [
[
"multiply_bitwise",
"add_bitwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cc18e6babb1c262a07164ad07e6e6ef21cc28b34 | 2b1dde87bfdabc294546630f6279049dd66da0af |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.