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_47357_I
### RSA Key Pair Generation and Encryption #### Objective Your task is to implement the RSA key generation, encryption, and decryption functions. This will test your understanding of modular arithmetic and prime generation, both fundamental concepts in cryptography. ### Problem Statement Create a Python function `gen...
import random from math import gcd def is_prime(n, k=128): """Test if a number is prime using Miller-Rabin primality test.""" if n <= 1: return False if n <= 3: return True if n % 2 == 0: return False r, d = 0, n - 1 while d % 2 == 0: r += 1 d //= 2 ...
from solution import generate_key_pair, encrypt, decrypt def test_generate_key_pair(): n, e, d = generate_key_pair(16) assert n > 0 assert e > 0 assert d > 0 def test_encrypt_decrypt(): n, e, d = generate_key_pair(16) data = 20 encrypted = encrypt(data, e, n) decrypted = decrypt(en...
[ { "docstring": "Test if a number is prime using Miller-Rabin primality test.", "function_declaration": "def is_prime(n, k=128):", "function_name": "is_prime", "parameter_list": "(n, k=128)" }, { "docstring": "Generate an odd integer randomly.", "function_declaration": "def generate_prime...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime\n\ndef generate_prime_candidate(length):\n \"\"\" Generate an odd integer randomly \"\"\"\n p = random.getrandb...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00047357", "row_id": 47357, "seed_ids": "[154]" }
0.663506
Data_Structure_47357
I
[ "is_prime", "generate_prime_candidate", "generate_prime_number", "modinv", "generate_key_pair", "encrypt", "decrypt" ]
7
[ [ "generate_key_pair", "generate_prime_number" ], [ "generate_key_pair", "modinv" ], [ "generate_prime_number", "generate_prime_candidate" ], [ "generate_prime_number", "is_prime" ] ]
4
[]
false
[]
false
pytest
true
[]
true
92530522538f47411b4c749fa7e0f7dd0b5419f8
ee1731071e2b3659a3e892f90add819611172bb8
v1.0
instruct
Data_Structure
Data_Structure_47358_I
### Question: Efficient Sorting for a Record Management System #### Context: You are developing a record management system where performance is critical. The system handles sorting of user records based on their ages. Due to performance constraints, you need to replace your current inefficient sorting algorithm (Excha...
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts an array of integers in ascending order using the Merge Sort algorithm. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) retu...
from solution import merge_sort def test_merge_sort_with_normal_case(): assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] def test_merge_sort_with_empty_array(): assert merge_sort([]) == [] def test_merge_sort_with_single_element_array(): assert merge_sort([1]) == [1] def test_...
[ { "docstring": "Sorts an array of integers in ascending order using the Merge Sort algorithm.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merges two sorted input lists into a single sorted list.", "function...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array of integers in ascending order using the Merge Sort al...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047358", "row_id": 47358, "seed_ids": "[28]" }
0.658009
Data_Structure_47358
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
510d307b97535d036db2c29f5b2bd81dd73b14cd
654e3207e55962aabe1ae49ca438c956b57cf1ce
v1.0
instruct
Data_Structure
Data_Structure_47361_I
### Word Search Algorithm Implementation #### Context You are tasked with developing a system that can find specific words within a matrix of characters, akin to solving a word search puzzle. This involves checking horizontal, vertical paths to find any of the given words. To accomplish this efficiently, you should us...
from typing import List, Set, Dict, Tuple class TrieNode: def __init__(self): self.children: Dict[str, TrieNode] = {} self.word: str = None def build_trie(words: List[str]) -> TrieNode: root = TrieNode() for word in words: node = root for char in word: if char n...
from solution import find_words def test_find_words_example(): board = [ ['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v'] ] words = ["oath", "pea", "eat", "rain"] result = find_words(board, words) assert set(result) == {"oath", "eat"} def t...
[]
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.is_end_of_word = False\n\nclass Trie:\n def _...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00047361", "row_id": 47361, "seed_ids": "[115]" }
0.637227
Data_Structure_47361
I
[ "build_trie", "find_words" ]
2
[ [ "find_words", "build_trie" ] ]
1
[]
false
[ "TrieNode" ]
true
pytest
true
[]
true
3cdcb11a99e7193e02ac270db41c653b6688fa29
51f1be4b07f12d7077f23f08f0265381f26c05b4
v1.0
instruct
Data_Structure
Data_Structure_47398_I
You are given an unsorted array of integers. You need to implement the `pancake_sort` function, which sorts the array using Pancake Sorting algorithm. Your implementation should sort the array in ascending order using the process of repeatedly flipping portions of the array, similar to sorting a stack of pancakes by si...
from typing import List def flip(arr: List[int], k: int) -> None: """Reverses the order of the first k elements in the array.""" arr[:k] = arr[:k][::-1] def find_max_index(arr: List[int], n: int) -> int: """Finds the index of the maximum element in arr[0..n-1].""" max_index = 0 for i in range(1, n...
from solution import pancake_sort def test_pancake_sort_simple(): assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4] def test_pancake_sort_already_sorted(): assert pancake_sort([1, 2, 3, 4]) == [1, 2, 3, 4] def test_pancake_sort_reverse_sorted(): assert pancake_sort([4, 3, 2, 1]) == [1, 2, 3, 4] def test...
[ { "docstring": "Reverses the order of the first k elements in the array.", "function_declaration": "def flip(arr, k):", "function_name": "flip", "parameter_list": "(arr, k)" }, { "docstring": "Finds the index of the maximum element in arr[0..n-1].", "function_declaration": "def find_max_...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef flip(arr: List[int], k: int) -> None:\n \"\"\"\n Helper function to reverse the order of the first k elements in the arra...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047398", "row_id": 47398, "seed_ids": "[9]" }
0.739115
Data_Structure_47398
I
[ "flip", "find_max_index", "pancake_sort" ]
3
[ [ "pancake_sort", "find_max_index" ], [ "pancake_sort", "flip" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f6bbb64bca8115cffe08c9ce7172b59e41f4a179
381aaabc164c6574129ef0f3840ae9531673eb9e
v1.0
instruct
Data_Structure
Data_Structure_47406_I
You are working as a software engineer tasked with creating an optimized sort function. One of the basic tasks is to work with simple sorting algorithms. Your goal is to implement and enhance a sorting function that uses the insertion sort algorithm. #### Function Signature ```python def optimized_insertion_sort(arr, ...
def binary_search(arr, val, start, end): """ Helper function to perform binary search to find the insertion index. """ if start == end: if arr[start] > val: return start else: return start + 1 if start > end: return start mid = (start + end) // 2...
from solution import optimized_insertion_sort def test_single_element_array(): assert optimized_insertion_sort([1]) == [1] def test_sorted_array(): assert optimized_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): assert optimized_insertion_sort([5, 4, 3, 2, 1]) == [1, ...
[ { "docstring": "Helper function to perform binary search to find the insertion index.", "function_declaration": "def binary_search(arr, val, start, end):", "function_name": "binary_search", "parameter_list": "(arr, val, start, end)" }, { "docstring": "Sort an array using an optimized version...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def binary_search(arr, val, start, end):\n \"\"\"\n Helper function to perform binary search to find the insertion index.\n \"\"\"\n if start == e...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00047406", "row_id": 47406, "seed_ids": "[7]" }
0.588591
Data_Structure_47406
I
[ "binary_search", "optimized_insertion_sort" ]
2
[ [ "optimized_insertion_sort", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
49b8fbfccbd8529e98213058a6f803498a89b709
a448325a4bed0f3550f31160fbb1a12c0ab1384b
v1.0
instruct
Data_Structure
Data_Structure_47440_I
You are given two lists representing large sparse vectors of possibly different lengths. Each list contains floating-point numbers where most of the elements are zeros. You need to write a function that: 1. Converts these sparse vectors into a more efficient storage structure that only stores non-zero elements. 2. Com...
def vector_to_index_value_list(vector): """ Converts a vector into an efficient storage structure by keeping index-value pairs of non-zero elements. """ return [(i, v) for i, v in enumerate(vector) if v != 0.0] def sparse_vector_dot_product(vector1, vector2): """ Computes the dot product of two...
from solution import sparse_vector_dot_product def test_example_cases(): assert sparse_vector_dot_product([1.0, 2.0, 3.0], [0.0, 2.0, 2.0]) == 10.0 assert sparse_vector_dot_product([], [0.0, 2.0, 0.0]) == 0.0 assert sparse_vector_dot_product([0.0, 0.0, 0.0], [0.0, 0.0, 0.0]) == 0.0 assert sparse_vector...
[ { "docstring": "Converts a vector into an efficient storage structure by keeping index-value pairs of non-zero elements.", "function_declaration": "def vector_to_index_value_list(vector):", "function_name": "vector_to_index_value_list", "parameter_list": "(vector)" }, { "docstring": "Compute...
[ 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 vector_to_index_value_list(vector):\n \"\"\"\n Converts a sparse vector to list of tuples containing index and value of non-zero elements.\n \"\"...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047440", "row_id": 47440, "seed_ids": "[341]" }
0.468359
Data_Structure_47440
I
[ "vector_to_index_value_list", "sparse_vector_dot_product" ]
2
[ [ "sparse_vector_dot_product", "vector_to_index_value_list" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f1dd116b3f5b8c206a1fe2e3974b033c7ae51bc3
dd55fd28f249dd0eef101e69fcf10f9cde1dc11a
v1.0
instruct
Data_Structure
Data_Structure_47460_I
**Prime Generation with Optimized Prime Check** ### Problem Statement You are tasked with writing a function that generates all prime numbers up to a given integer \( n \). Your implementation should leverage the provided `prime_check` function to determine primality efficiently. ### Function Signature ```python def...
from typing import List def prime_check(num: int) -> bool: if num <= 1: return False if num == 2 or num == 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while (i * i) <= num: if num % i == 0 or num % (i + 2) == 0: return False ...
from solution import generate_primes def test_small_range(): assert generate_primes(10) == [2, 3, 5, 7] assert generate_primes(2) == [2] assert generate_primes(3) == [2, 3] assert generate_primes(5) == [2, 3, 5] def test_up_to_twenty(): assert generate_primes(20) == [2, 3, 5, 7, 11, 13, 17, 19] d...
[ { "docstring": null, "function_declaration": "def prime_check(num):", "function_name": "prime_check", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def generate_primes(n):", "function_name": "generate_primes", "parameter_list": "(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": "from typing import List\n\ndef prime_check(num: int) -> bool:\n if num <= 1:\n return False\n if num == 2 or num == 3:\n return True\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00047460", "row_id": 47460, "seed_ids": "[143]" }
0.704058
Data_Structure_47460
I
[ "prime_check", "generate_primes" ]
2
[ [ "generate_primes", "prime_check" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6c54063fc0762e169028fd21a73c3fc560017761
65ef1b823b93e5b4c50bb92b8a43629a64896923
v1.0
instruct
Data_Structure
Data_Structure_47471_I
You've been tasked with creating a function to identify prime numbers within a given range efficiently. Your function will be part of a larger application that relies heavily on prime number calculations. Implement a function `prime_in_range(start: int, end: int) -> List[int]` that will return a list of all prime numb...
from typing import List def is_prime(n: int) -> bool: """ Helper function to determine if a number is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) ...
from solution import prime_in_range def test_prime_in_range_all_primes(): assert prime_in_range(10, 50) == [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] def test_prime_in_range_no_primes(): assert prime_in_range(14, 16) == [] def test_prime_in_range_single_element_prime(): assert prime_in_range(29, 29) ==...
[ { "docstring": "Helper function to determine if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of all prime numbers within the range [start, end] inclusive.", "function_declaration": ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00047471", "row_id": 47471, "seed_ids": "[143]" }
0.612123
Data_Structure_47471
I
[ "is_prime", "prime_in_range" ]
2
[ [ "prime_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f62ab82da87d8f16a58ef6de4821ff295e34cef7
3f9f2f464972affaea95673efa51a0a1bcc285a9
v1.0
instruct
Data_Structure
Data_Structure_47502_I
**Question**: Implement an in-place merge sort for an array of integers. **Scenario**: You are given an array of integers that you need to sort in non-decreasing order using the merge sort algorithm. For this task, you must implement the merge sort algorithm in such a way that it does not use any additional arrays to ...
from typing import List def merge_sort_in_place(arr: List[int], left: int = 0, right: int = None) -> None: if right is None: right = len(arr) - 1 if left < right: middle = (left + right) // 2 merge_sort_in_place(arr, left, middle) merge_sort_in_place(arr, middle + 1, right) ...
from solution import merge_sort_in_place def test_merge_sort_in_place_with_mixed_numbers(): arr = [38, 27, 43, 3, 9, 82, 10] merge_sort_in_place(arr) assert arr == [3, 9, 10, 27, 38, 43, 82] def test_merge_sort_in_place_with_sorted_numbers(): arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] merge_sort_in_place(a...
[ { "docstring": null, "function_declaration": "def merge_sort_in_place(arr, left=0, right=None):", "function_name": "merge_sort_in_place", "parameter_list": "(arr, left=0, right=None)" }, { "docstring": null, "function_declaration": "def merge(arr, left, middle, right):", "function_na...
[ 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_in_place(arr: List[int]) -> None:\n def merge(arr, start, mid, end):\n start2 = mid + 1\n # If the ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047502", "row_id": 47502, "seed_ids": "[12]" }
0.630141
Data_Structure_47502
I
[ "merge_sort_in_place", "merge" ]
2
[ [ "merge_sort_in_place", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6d95f3f1abdea2539bd81437c1d4074c21942a1e
df78f6554cf4c7cbc3607231f5ef0c8ccb235c1b
v1.0
instruct
Data_Structure
Data_Structure_47530_I
### Pancake Sort Implementation and Analysis **Context**: Pancake sorting is an analogy-based sorting method where you sort an array just like how a chef would arrange a pile of pancakes by flipping them with a spatula. Your task is to use the principles of Pancake Sort to sort an array of numbers. **Problem Statemen...
from typing import List, Tuple def flip(arr: List[int], k: int) -> None: """Reverses the order of the first k elements in the array.""" arr[:k] = arr[:k][::-1] def pancake_sort_with_flips(arr: List[int]) -> Tuple[List[int], List[int]]: res = [] n = len(arr) for size in range(n, 1, -1): ...
from solution import pancake_sort_with_flips def test_regular_list(): arr = [3, 2, 4, 1] sorted_arr, flips = pancake_sort_with_flips(arr) assert sorted_arr == [1, 2, 3, 4] # Check if final array is sorted assert sorted_arr == sorted(arr) def test_empty_list(): arr = [] sorted_arr, flips = ...
[ { "docstring": "Reverses the order of the first k elements in the array.", "function_declaration": "def flip(arr, k):", "function_name": "flip", "parameter_list": "(arr, k)" }, { "docstring": null, "function_declaration": "def pancake_sort_with_flips(arr):", "function_name": "pancake...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\ndef flip(arr: List[int], k: int) -> None:\n arr[:k] = reversed(arr[:k])\n\ndef pancake_sort_with_flips(arr: List[int]) ->...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00047530", "row_id": 47530, "seed_ids": "[9]" }
0.735829
Data_Structure_47530
I
[ "flip", "pancake_sort_with_flips" ]
2
[ [ "pancake_sort_with_flips", "flip" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f2a4fa9c184e87cd959c2b2c86d26fb9f4b177aa
5f794fe60bb6bb696e156224544cd7804eb233d4
v1.0
instruct
Data_Structure
Data_Structure_47535_I
**Max Flow Problem: BottleNeck Capacity Calculation** **Scenario:** A company is analyzing their transportation network to find out the maximum flow of goods from a main warehouse (source) to retail stores (sink). This network can be represented as a directed graph where nodes represent locations (e.g., warehouses, st...
from typing import List, Tuple def dfs_find_path(capacity: List[List[int]], flow: List[List[int]], source: int, sink: int, parent: List[int]) -> bool: visited = [False] * len(capacity) stack = [source] visited[source] = True while stack: u = stack.pop() for v in range(len(capacity)): ...
from solution import max_flow_bottleneck def test_example_case(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert max_flow_bottlenec...
[ { "docstring": null, "function_declaration": "def dfs_find_path(capacity, flow, source, sink, parent):", "function_name": "dfs_find_path", "parameter_list": "(capacity, flow, source, sink, parent)" }, { "docstring": null, "function_declaration": "def max_flow_bottleneck(capacity, source,...
[ 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": "from typing import List, Tuple\n\ndef max_flow_bottleneck(capacity: List[List[int]], source: int, sink: int) -> Tuple[int, int]:\n def bfs(source: int, sin...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00047535", "row_id": 47535, "seed_ids": "[240]" }
0.569342
Data_Structure_47535
I
[ "dfs_find_path", "max_flow_bottleneck" ]
2
[ [ "max_flow_bottleneck", "dfs_find_path" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3e591899f1bc87e05342de0417555951eb254271
1efc8031326349f8b138efbc9108e859b518f2ef
v1.0
instruct
Data_Structure
Data_Structure_47538_I
Diffie-Hellman Key Exchange **Context**: Alice and Bob wish to securely exchange keys over a public channel using the Diffie-Hellman Key Exchange Protocol. To ensure security, they must verify the parameters they use to generate their keys. #### Question Implement a function `safe_diffie_hellman(p: int, a: int) -> b...
import sympy def prime_check(num: int) -> bool: return sympy.isprime(num) def find_primitive_root(p: int) -> int: for g in range(2, p): if all(pow(g, (p - 1) // q, p) != 1 for q in sympy.factorint(p - 1)): return g return -1 def alice_private_key(p: int) -> int: return 6 # For si...
import pytest from solution import safe_diffie_hellman, prime_check, find_primitive_root def test_safe_diffie_hellman_success(): assert safe_diffie_hellman(23, 5) == True def test_safe_diffie_hellman_fail_non_prime(): assert safe_diffie_hellman(22, 5) == False def test_safe_diffie_hellman_fail_non_primit...
[ { "docstring": null, "function_declaration": "def prime_check(num):", "function_name": "prime_check", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def find_primitive_root(p):", "function_name": "find_primitive_root", "parameter_list": "(p)" }, { ...
[ 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 prime_check(num: int) -> bool:\n \"\"\"Check if a number is prime.\"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00047538", "row_id": 47538, "seed_ids": "[146]" }
0.447541
Data_Structure_47538
I
[ "prime_check", "find_primitive_root", "alice_private_key", "alice_public_key", "bob_private_key", "bob_public_key", "alice_shared_key", "bob_shared_key", "safe_diffie_hellman" ]
9
[ [ "safe_diffie_hellman", "alice_private_key" ], [ "safe_diffie_hellman", "alice_public_key" ], [ "safe_diffie_hellman", "alice_shared_key" ], [ "safe_diffie_hellman", "bob_private_key" ], [ "safe_diffie_hellman", "bob_public_key" ], [ "safe_diffie_hell...
8
[]
false
[]
false
pytest
true
[ "sympy" ]
false
bee88d51bb6709978c6e29a7f68a23aab1820338
6010da3c664fb34f1b9aa803c7ce0b0958bffae8
v1.0
instruct
Data_Structure
Data_Structure_47573_I
### Question: Optimized Matrix Multiplication and Exponentiation You are given three operations related to matrix computations: matrix multiplication, identity matrix generation, and matrix exponentiation. Your task is to implement optimized versions of these operations. **1. Optimized Matrix Multiplication:** Implem...
def optimized_multiply(matA: list, matB: list) -> list: """ Multiplies two square matrices matA and matB using Strassen's algorithm Time Complexity: Approximately O(n^2.81) """ def add_matrix(A, B): size = len(A) return [[A[i][j] + B[i][j] for j in range(size)] for i in range(size)] ...
from solution import optimized_multiply, identity, matrix_exponentiation def test_optimized_multiply(): matA = [ [1, 2], [3, 4] ] matB = [ [2, 0], [1, 2] ] assert optimized_multiply(matA, matB) == [[4, 4], [10, 8]] def test_identity(): assert identity(3) == [ ...
[ { "docstring": "Multiplies two square matrices matA and matB using Strassen's algorithm\nTime Complexity: Approximately O(n^2.81)", "function_declaration": "def optimized_multiply(matA, matB):", "function_name": "optimized_multiply", "parameter_list": "(matA, matB)" }, { "docstring": "Return...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def optimized_multiply(matA: list, matB: list) -> list:\n \"\"\"\n Multiplies two square matrices matA and matB using Strassen's algorithm\n Time Com...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00047573", "row_id": 47573, "seed_ids": "[340]" }
0.501305
Data_Structure_47573
I
[ "optimized_multiply", "identity", "matrix_exponentiation" ]
3
[ [ "matrix_exponentiation", "identity" ], [ "matrix_exponentiation", "optimized_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3a40a614fa82cec8738de774470c94cd2b10f14f
1184fc97dc1c31845b9c10b3a5b191a0e49429e4
v1.0
instruct
Data_Structure
Data_Structure_47625_I
### Bogo Sort Implementation Challenge #### Context Bogo Sort, also whimsically known as Monkey Sort or Stupid Sort, is a highly ineffective and impractical sorting algorithm that permutes an array randomly until it is sorted. While its conceptual simplicity is intriguing, its execution can be extraordinarily time-con...
import random from typing import List def is_sorted(arr: List[int]) -> bool: """ Helper function to check if the array is sorted. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def bogo_sort(arr: List[int]) -> List[int]: """ Sorts the...
from solution import bogo_sort def test_bogo_sort_sorted_array(): arr = [1, 2, 3, 4, 5] assert bogo_sort(arr) == [1, 2, 3, 4, 5] def test_bogo_sort_reverse_sorted_array(): arr = [5, 4, 3, 2, 1] assert bogo_sort(arr) == [1, 2, 3, 4, 5] def test_bogo_sort_random_array(): arr = [3, 1, 2] assert ...
[ { "docstring": "Helper function to check if the array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts the given array using the Bogo Sort algorithm.", "function_declaration": "def bogo_sort(arr):...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Check if the array is sorted in non-decreasing order.\n \...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047625", "row_id": 47625, "seed_ids": "[16]" }
0.616364
Data_Structure_47625
I
[ "is_sorted", "bogo_sort" ]
2
[ [ "bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0e2cbe4053cc0ecf5a408153f2cfd71a9d69a4ce
8f88cdeafe6c0511ea2cb99612349fba45a43fce
v1.0
instruct
Data_Structure
Data_Structure_47666_I
### Insertion Sort with Binary Search Insertion In this task, you are required to implement an insertion sort algorithm using binary search to find the correct insertion point. **Scenario**: Given an unsorted array of integers, the goal is to sort the array using an optimized insertion sort mechanism. Traditional inse...
def search_insert(arr, target): """ Binary search to find the index where target should be inserted to keep arr sorted. """ left, right = 0, len(arr) while left < right: mid = (left + right) // 2 if arr[mid] < target: left = mid + 1 else: right = mid ...
from solution import insertion_sort_with_binary_search def test_empty_list(): assert insertion_sort_with_binary_search([]) == [] def test_single_element(): assert insertion_sort_with_binary_search([5]) == [5] def test_sorted_list(): assert insertion_sort_with_binary_search([1, 2, 3, 4, 5]) == [1, 2, 3, 4...
[ { "docstring": "Binary search to find the index where target should be inserted to keep arr sorted.", "function_declaration": "def search_insert(arr, target):", "function_name": "search_insert", "parameter_list": "(arr, target)" }, { "docstring": "Sorts a list of integers using insertion sor...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from bisect import bisect_left\n\ndef search_insert(sorted_sublist, value):\n \"\"\"\n Utilizes binary search to find the index at which 'value' should ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047666", "row_id": 47666, "seed_ids": "[199]" }
0.593416
Data_Structure_47666
I
[ "search_insert", "insertion_sort_with_binary_search" ]
2
[ [ "insertion_sort_with_binary_search", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f9f26252a1572e744d97220e7890a4807a86ca0d
0e643d81ac7cd17faad1076469cf852d51a1e20f
v1.0
instruct
Data_Structure
Data_Structure_47678_I
### Gnome Sort in a Dynamic List Scenario You are given the task of implementing a sorting function using the Gnome Sort algorithm. As a part of this, you need to ensure the function can handle being given in a dynamic list scenario: elements might be frequently added to the list, and you need to maintain the list in ...
def gnome_sort(arr): """ Performs Gnome Sort on the list. """ index = 0 while index < len(arr): if index == 0 or arr[index] >= arr[index - 1]: index += 1 else: arr[index], arr[index - 1] = arr[index - 1], arr[index] index -= 1 return arr def d...
from solution import dynamic_gnome_sort def test_already_sorted(): assert dynamic_gnome_sort([1, 2, 3], [4, 5]) == [1, 2, 3, 4, 5] def test_reverse_ordered_inserts(): assert dynamic_gnome_sort([1, 2, 3], [6, 5, 4]) == [1, 2, 3, 4, 5, 6] def test_inserts_causing_shuffles(): assert dynamic_gnome_sort([1, 3...
[ { "docstring": "Performs Gnome Sort on the list.", "function_declaration": "def gnome_sort(arr):", "function_name": "gnome_sort", "parameter_list": "(arr)" }, { "docstring": "Adds elements from new_elements to initial_list one by one,\nsorting the list using Gnome Sort after each addition.",...
[ 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 gnome_sort(arr):\n index = 0\n while index < len(arr):\n if index == 0:\n index += 1\n if arr[index] >= arr[index - 1]:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047678", "row_id": 47678, "seed_ids": "[13]" }
0.612973
Data_Structure_47678
I
[ "gnome_sort", "dynamic_gnome_sort" ]
2
[ [ "dynamic_gnome_sort", "gnome_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
943ec546247f6113fb8eebdb9018bf83c42b363f
9d7b34911ff4bba20801d26af1a2134c59166640
v1.0
instruct
Data_Structure
Data_Structure_47682_I
### Question: Advanced GCD Analysis and Application You have been provided with two different implementations of the greatest common divisor (GCD) - one using Euclid's division-based algorithm and the other using bitwise operations. Additionally, you understand the relationship between GCD and the least common multipl...
def gcd_bitwise(a, b): """ Computes the GCD using the efficient bitwise method. """ if a == 0: return b if b == 0: return a # Finding common factors of 2 shift = 0 while ((a | b) & 1) == 0: a >>= 1 b >>= 1 shift += 1 while (a & 1) == 0: ...
from solution import advanced_gcd_analysis def test_advanced_gcd_analysis_case_1(): assert advanced_gcd_analysis(34, 40) == (2, 680, 3) def test_advanced_gcd_analysis_case_2(): assert advanced_gcd_analysis(10, 15) == (5, 30, 1) def test_advanced_gcd_analysis_case_3(): assert advanced_gcd_analysis(0, 5) =...
[ { "docstring": "Computes the GCD using the efficient bitwise method.", "function_declaration": "def gcd_bitwise(a, b):", "function_name": "gcd_bitwise", "parameter_list": "(a, b)" }, { "docstring": "Computes the LCM using the relationship between GCD and LCM.", "function_declaration": "d...
[ 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 advanced_gcd_analysis(a: int, b: int) -> tuple:\n def gcd(a: int, b: int) -> int:\n if a == 0:\n return b\n if b == 0:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00047682", "row_id": 47682, "seed_ids": "[166]" }
0.66662
Data_Structure_47682
I
[ "gcd_bitwise", "lcm", "count_trailing_zeros", "advanced_gcd_analysis" ]
4
[ [ "advanced_gcd_analysis", "count_trailing_zeros" ], [ "advanced_gcd_analysis", "gcd_bitwise" ], [ "advanced_gcd_analysis", "lcm" ] ]
3
[]
false
[]
false
pytest
true
[]
true
f86626e394a05ee18252e74592ca41780dfbc357
d39688a25dcee4af5f3341811b822b859885a281
v1.0
instruct
Data_Structure
Data_Structure_47693_I
### Problem: Enhanced GCD and LCM Calculator Given two non-negative integers x and y, your task is to write two functions: 1. **`enhanced_gcd(x, y)`** that calculates the greatest common divisor by intelligently combining the properties of the standard Euclidean algorithm with the binary GCD algorithm to maximize effi...
def enhanced_gcd(x, y): """ Calculates the greatest common divisor (GCD) of x and y using the Euclidean algorithm. """ while y != 0: x, y = y, x % y return x def enhanced_lcm(x, y): """ Calculates the least common multiple (LCM) of x and y using the GCD. """ if x == 0 or y =...
from solution import enhanced_gcd, enhanced_lcm def test_enhanced_gcd_with_non_zero_numbers(): assert enhanced_gcd(18, 24) == 6 assert enhanced_gcd(48, 18) == 6 assert enhanced_gcd(7, 3) == 1 assert enhanced_gcd(54, 24) == 6 def test_enhanced_gcd_with_zero(): assert enhanced_gcd(0, 0) == 0 ass...
[ { "docstring": "Calculates the greatest common divisor (GCD) of x and y using the Euclidean algorithm.", "function_declaration": "def enhanced_gcd(x, y):", "function_name": "enhanced_gcd", "parameter_list": "(x, y)" }, { "docstring": "Calculates the least common multiple (LCM) of x and y usi...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def enhanced_gcd(x, y):\n \"\"\"\n Optimized function to calculate GCD using a combination of Euclidean and Binary GCD algorithms.\n \"\"\"\n # Ba...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047693", "row_id": 47693, "seed_ids": "[166]" }
0.714368
Data_Structure_47693
I
[ "enhanced_gcd", "enhanced_lcm" ]
2
[ [ "enhanced_lcm", "enhanced_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0b4339b925f37d6c5805797931cff3a1dfc20da1
83b73e676cff56ca8c16f7e80be20f471f86aed2
v1.0
instruct
Data_Structure
Data_Structure_47707_I
Implement Stooge Sort with Enhancements #### Scenario: You are given an array of integers that you need to sort efficiently for academic research purposes. Although Stooge Sort is generally inefficient, this exercise will help you understand recursive algorithms and their characteristics. #### Problem Statement: Writ...
def insertion_sort(arr, l, h): for i in range(l + 1, h + 1): key = arr[i] j = i - 1 while j >= l and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def enhanced_stoogesort(arr, l, h, threshold): if h - l + 1 <= threshold: insertion_sort...
from solution import enhanced_stoogesort def test_stooge_sort_small_array(): arr = [9, 1, 4, 7, 3] enhanced_stoogesort(arr, 0, 4, 2) assert arr == [1, 3, 4, 7, 9] def test_stooge_sort_medium_array(): arr = [5, 2, 9, 1, 5, 6] enhanced_stoogesort(arr, 0, 5, 3) assert arr == [1, 2, 5, 5, 6, 9] d...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr, l, h):", "function_name": "insertion_sort", "parameter_list": "(arr, l, h)" }, { "docstring": null, "function_declaration": "def enhanced_stoogesort(arr, l, h, threshold):", "function_name": "enhanced_stoogesort", ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef insertion_sort(arr: List[int], l: int, h: int) -> None:\n for i in range(l + 1, h + 1):\n key = arr[i]\n j = i...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047707", "row_id": 47707, "seed_ids": "[10]" }
0.5913
Data_Structure_47707
I
[ "insertion_sort", "enhanced_stoogesort" ]
2
[ [ "enhanced_stoogesort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d75f9041986bb6cc0aa59dd256b20ad36fa05ca2
07af2e6503db8982bdc4e9e3b5422b566af3234d
v1.0
instruct
Data_Structure
Data_Structure_47762_I
### Question: Implementing Advanced Markov Chain Mechanisms #### Context You are tasked to improve and extend the functionality of a Markov Chain simulator that transitions between states based on predefined probabilities. This Markov Chain is represented using dictionaries, and your task is to address some shortcomin...
import random def validate_initial_state(chain, state): """ Validate if the initial state exists in the Markov chain and has outgoing transitions. :param chain: dict - The Markov chain with state transitions. :param state: str - The initial state. :return: bool - True if the state is valid, el...
from solution import validate_initial_state, validate_chain, markov_chain_simulation # Test validate_initial_state def test_validate_initial_state(): chain = { 'A': {'B': 0.5, 'C': 0.5}, 'B': {'A': 0.5, 'C': 0.5}, 'C': {} } assert validate_initial_state(chain, 'A') == True asser...
[ { "docstring": "Validate if the initial state exists in the Markov chain and has outgoing transitions.\n\n:param chain: dict - The Markov chain with state transitions.\n:param state: str - The initial state.\n:return: bool - True if the state is valid, else False.", "function_declaration": "def validate_ini...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef validate_initial_state(chain, state):\n \"\"\"\n Validate if the initial state exists in the Markov chain and has outgoing transiti...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047762", "row_id": 47762, "seed_ids": "[232]" }
0.432349
Data_Structure_47762
I
[ "validate_initial_state", "validate_chain", "markov_chain_simulation" ]
3
[ [ "markov_chain_simulation", "validate_initial_state" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4442c768c13a4227f09fca72830bf72b78276638
2014a88c4c8b4ad626a48f9fb0814dda5d4687bb
v1.0
instruct
Data_Structure
Data_Structure_47776_I
### Scenario: You are tasked with developing an efficient sorting algorithm for a set of non-negative integers. Your objective is to implement Radix Sort which is suitable for sorting large arrays with wide-ranging values without using comparison-based methods. ### Challenge: Implement a function `radix_sort(arr: List...
from typing import List def counting_sort(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] i = n - 1 while i >= ...
from solution import radix_sort def test_radix_sort_basic(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] assert radix_sort([329, 457, 657, 839, 436, 720, 355]) == [329, 355, 436, 457, 657, 720, 839] def test_radix_sort_empty(): assert radix_sort([]) == [] def...
[ { "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 radix_sort(arr: List[int]) -> List[int]:\n if not arr:\n return []\n\n # Helper function to do counting sort accor...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047776", "row_id": 47776, "seed_ids": "[15]" }
0.656161
Data_Structure_47776
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
11f9cc04d58d501c8c23ccf440fb4708acacec86
25940233f51072a7b815abf42f5b8b06c0083000
v1.0
instruct
Data_Structure
Data_Structure_47785_I
### GCD and Trailing Zeros Combined Assessment You are tasked with solving a problem that requires advanced understanding and manipulation of integers using bitwise operations and GCD algorithms. #### Problem Statement Given an array of non-negative integers, your task is to compute the GCD of all integers in the ar...
from typing import List, Tuple from functools import reduce def gcd(a, b): """ Helper function to calculate GCD using bitwise operations. """ while b: a, b = b, a % b return a def compute_gcd_and_trailing_zeros(arr: List[int]) -> Tuple[int, int]: """ Given a list of non-negative in...
from solution import compute_gcd_and_trailing_zeros def test_example1(): assert compute_gcd_and_trailing_zeros([40, 60, 80]) == (20, 2) def test_example2(): assert compute_gcd_and_trailing_zeros([7, 14, 28]) == (7, 0) def test_single_element(): assert compute_gcd_and_trailing_zeros([15]) == (15, 0) def ...
[ { "docstring": "Helper function to calculate GCD using bitwise operations.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Given a list of non-negative integers 'arr', returns a tuple where the first\nelement is the GCD of all...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nfrom functools import reduce\n\ndef gcd(a, b):\n \"\"\"\n Helper function to calculate GCD using bitwise operations.\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00047785", "row_id": 47785, "seed_ids": "[166]" }
0.591836
Data_Structure_47785
I
[ "gcd", "compute_gcd_and_trailing_zeros" ]
2
[ [ "compute_gcd_and_trailing_zeros", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
20d1766068cb3105de413432ffaf97bb615849fb
3c85094e9bb9361684a4396a91f85eccae9c5c72
v1.0
instruct
Data_Structure
Data_Structure_47797_I
### Krishnamurthy Number Detection #### Scenario: You are tasked with creating an efficient function to detect if a given number is a Krishnamurthy number. This will help in a mathematical exploration module to identify special numbers automatically. #### Function Details: **Function Name**: `is_krishnamurthy_number`...
def factorial(n): """ Return the factorial of a given number n. """ if n == 0 or n == 1: return 1 result = 1 for i in range(2, n + 1): result *= i return result def is_krishnamurthy_number(n): """ Return True if the given number n is a Krishnamurthy number, else Fals...
from solution import is_krishnamurthy_number def test_is_krishnamurthy_number_true_cases(): assert is_krishnamurthy_number(1) == True assert is_krishnamurthy_number(2) == True assert is_krishnamurthy_number(145) == True assert is_krishnamurthy_number(40585) == True def test_is_krishnamurthy_number_fal...
[ { "docstring": "Return the factorial of a given number n.", "function_declaration": "def factorial(n):", "function_name": "factorial", "parameter_list": "(n)" }, { "docstring": "Return True if the given number n is a Krishnamurthy number, else False.", "function_declaration": "def is_kri...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def factorial(n):\n \"\"\"\n Returns the factorial of a given number n.\n \"\"\"\n if n == 0 or n == 1:\n return 1\n result = 1\n for...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00047797", "row_id": 47797, "seed_ids": "[142]" }
0.608001
Data_Structure_47797
I
[ "factorial", "is_krishnamurthy_number" ]
2
[ [ "is_krishnamurthy_number", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ed94e32efe0705a120489b4c032d6ac5e603315d
405534565ed490b9a72c33359c3543f918865f9e
v1.0
instruct
Data_Structure
Data_Structure_47845_I
### Question: Implement Advanced Matrix Operations You are given a task to implement an optimized matrix inversion function. The provided function `invert_matrix(m)` inverts an `n x n` matrix `m`. However, it is inefficient for large matrices due to recursive determinant calculations. Your task is to rewrite this func...
import numpy as np def lu_decomposition(matrix): """ Perform LU decomposition using the Doolittle factorization. """ n = len(matrix) L = np.zeros((n, n)) U = np.zeros((n, n)) for i in range(n): L[i][i] = 1.0 for j in range(i, n): sum = 0.0 for k in range...
from solution import invert_matrix def test_invert_matrix_2x2(): m = [[4, 3], [3, 2]] expected = [[-2.0, 3.0], [3.0, -4.0]] result = invert_matrix(m) assert np.allclose(result, expected), f"Expected {expected}, got {result}" def test_invert_matrix_3x3(): m = [ [1, 2, 3], [0, 1, 4],...
[ { "docstring": "Perform LU decomposition using the Doolittle factorization. ", "function_declaration": "def lu_decomposition(matrix):", "function_name": "lu_decomposition", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def invert_matrix(m):", "function...
[ 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 numpy as np\n\ndef lu_decomposition(matrix):\n \"\"\" Perform LU decomposition using the Doolittle factorization. \"\"\"\n n = len(matrix)\n L...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00047845", "row_id": 47845, "seed_ids": "[347]" }
0.521205
Data_Structure_47845
I
[ "lu_decomposition", "invert_matrix" ]
2
[ [ "invert_matrix", "lu_decomposition" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
858c45be8283afd7c78ec689a89744fcb2e7429b
2d58492a91c4cc088d919a938f6b70714eca272d
v1.0
instruct
Data_Structure
Data_Structure_47894_I
### Scenario: You have been hired by a company to assess their understanding of sorting algorithms. You decide to present a fun and educational challenge using the notorious Bogo Sort, hoping to illustrate the inefficiency of brute-force algorithms. ### Task: Implement a function `is_sorted(arr)` that checks if an ar...
import random def is_sorted(arr): """ Checks if the array is sorted in ascending order. Parameters: arr (list): List of integers to check. Returns: bool: True if the list is sorted in ascending order, False otherwise. """ return all(arr[i] <= arr[i+1] for i in range(len(arr) -...
from solution import is_sorted, improved_bogo_sort def test_is_sorted(): assert is_sorted([1, 2, 3, 4, 5]) == True assert is_sorted([5, 4, 3, 2, 1]) == False assert is_sorted([1, 3, 2, 4, 5]) == False assert is_sorted([10]) == True assert is_sorted([]) == True def test_improved_bogo_sort(): in...
[ { "docstring": "Checks if the array is sorted in ascending order.\n\nParameters:\narr (list): List of integers to check.\n\nReturns:\nbool: True if the list is sorted in ascending order, False otherwise.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "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": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Check if the array is sorted in ascending order.\n \"\"\"\n for i in range(len(arr) - 1):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047894", "row_id": 47894, "seed_ids": "[16]" }
0.565054
Data_Structure_47894
I
[ "is_sorted", "improved_bogo_sort" ]
2
[ [ "improved_bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
35f54effada063faadae43359e388d3690e85a73
67acd451dad73d3549b56a11ac1209632628c7bc
v1.0
instruct
Data_Structure
Data_Structure_47897_I
#### Scenario As a software developer in a company that processes large datasets daily, you are tasked with implementing a stable and efficient sorting algorithm. The key requirement is that the algorithm must handle very large arrays efficiently while ensuring that the relative order of equal elements is preserved. #...
def merge_sort(arr: list) -> list: """ Sorts the input list using the Merge Sort algorithm. Args: arr (list): A list of integers to sort. Returns: list: A sorted list of integers in non-decreasing order. """ if len(arr) <= 1: return arr # Find the mid-point mid = len(a...
from solution import merge_sort def test_merge_sort_with_unsorted_array(): assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] def test_merge_sort_with_sorted_array(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_with_reverse_sorted_array(): assert mer...
[ { "docstring": "Sorts the input list using the Merge Sort algorithm.\n\nArgs:\narr (list): A list of integers to sort.\n\nReturns:\nlist: A sorted list of integers in non-decreasing order.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" },...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts the input list using the Merge Sort algorithm.\n \n Args:\n arr (list): A list of integers to sort.\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047897", "row_id": 47897, "seed_ids": "[12]" }
0.616477
Data_Structure_47897
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b4bc50211630798bebb803fba1b6121200f4d304
c66faa3225343e7da6e5179b2c3ed0ec832a719a
v1.0
instruct
Data_Structure
Data_Structure_48004_I
#### Scenario You are tasked with sorting a list of floating-point numbers that represent scores achieved by students in a coding competition. The scores range uniformly from 0 to 100. Given the nature of the scores, a suitable approach for sorting is Bucket Sort, with an efficient secondary sorting mechanism. For this...
def insertion_sort(bucket): """ Helper function to perform insertion sort on a bucket. """ for i in range(1, len(bucket)): key = bucket[i] j = i - 1 while j >= 0 and key < bucket[j]: bucket[j + 1] = bucket[j] j -= 1 bucket[j + 1] = key return b...
from solution import insertion_sort, bucket_sort def test_bucket_sort_example(): assert bucket_sort([78.23, 98.01, 26.78, 34.56, 50.11]) == [26.78, 34.56, 50.11, 78.23, 98.01] def test_bucket_sort_single_element(): assert bucket_sort([42.0]) == [42.0] def test_bucket_sort_already_sorted(): assert bucket_...
[ { "docstring": "Helper function to perform insertion sort on a bucket.", "function_declaration": "def insertion_sort(bucket):", "function_name": "insertion_sort", "parameter_list": "(bucket)" }, { "docstring": "Sorts an array of floating-point numbers using Bucket Sort.", "function_decla...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def bucket_sort(arr: list) -> list:\n \"\"\"\n Sorts an array of floating-point numbers using Bucket Sort.\n \"\"\"\n if not arr:\n return ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048004", "row_id": 48004, "seed_ids": "[26]" }
0.558707
Data_Structure_48004
I
[ "insertion_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f448dab96e9ae01ccf522618532b28f495f2ca99
f12ccec75a56db0759fef2d22f415eaa8aa6f548
v1.0
instruct
Data_Structure
Data_Structure_48015_I
### Question: Computing and Using Bézout's Coefficients You are tasked with writing a function to compute the Bézout coefficients \( s \) and \( t \) such that for two given integers `num1` and `num2`: \[ num1 \cdot s + num2 \cdot t = \text{GCD}(num1, num2) \] Using the Extended Euclidean Algorithm provided, impleme...
def extended_euclidean_algorithm(a, b): """ Uses the Extended Euclidean Algorithm to find the integers x and y such that: ax + by = gcd(a, b) """ if a == 0: return b, 0, 1 else: gcd, x1, y1 = extended_euclidean_algorithm(b % a, a) x = y1 - (b // a) * x1 y = x1 ...
from solution import bezout_and_check def test_bezout_and_check_30_20_10(): s, t, result = bezout_and_check(30, 20, 10) assert result == True assert 30 * s + 20 * t == 10 def test_bezout_and_check_35_15_5(): s, t, result = bezout_and_check(35, 15, 5) assert result == True assert 35 * s + 15 * ...
[ { "docstring": "Uses the Extended Euclidean Algorithm to find the integers x and y such that:\nax + by = gcd(a, b)", "function_declaration": "def extended_euclidean_algorithm(a, b):", "function_name": "extended_euclidean_algorithm", "parameter_list": "(a, b)" }, { "docstring": "Finds the Béz...
[ 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 extended_gcd(a, b):\n if b == 0:\n return a, 1, 0\n g, x1, y1 = extended_gcd(b, a % b)\n x = y1\n y = x1 - (a // b) * y1\n return g,...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00048015", "row_id": 48015, "seed_ids": "[156]" }
0.621081
Data_Structure_48015
I
[ "extended_euclidean_algorithm", "bezout_and_check" ]
2
[ [ "bezout_and_check", "extended_euclidean_algorithm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1129b275b7888ca15187e087febe1b5b8bfefeab
1cbb8a593c1c4f5029e3792f4c21535e1fb07cf0
v1.0
instruct
Data_Structure
Data_Structure_48045_I
### Merge Sort Implementation Challenge #### Scenario: You are given an array of integers that may contain both negative and positive values. Your task is to sort this array in ascending order using the Merge Sort algorithm. Merge Sort separates the list into halves, recursively sorts each half, and then merges the so...
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts an array of integers in ascending order using the merge sort algorithm. Parameters: arr (List[int]): The array of integers to be sorted. Returns: List[int]: The sorted array of integers. """ if...
from solution import merge_sort def test_empty_array(): assert merge_sort([]) == [] def test_single_element_array(): assert merge_sort([2]) == [2] def test_all_positive_numbers(): assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] def test_all_negative_numbers(): assert merg...
[ { "docstring": "Sorts an array of integers in ascending order using the merge sort algorithm.\n\nParameters:\narr (List[int]): The array of integers to be sorted.\n\nReturns:\nList[int]: The sorted array of integers.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "p...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n def merge(left: List[int], right...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048045", "row_id": 48045, "seed_ids": "[12]" }
0.635569
Data_Structure_48045
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
16a6cacecc4e337c82a76764c36c55a3212d490f
4a451f05f387fd18a2099c791c49cefed254ef80
v1.0
instruct
Data_Structure
Data_Structure_48067_I
### Question: Implement Radix Sort with Negative Numbers Support Radix sort as implemented above only handles non-negative integers. Adapt this algorithm to be capable of handling both positive and negative integers within the given list. #### Task Write a function `radix_sort_with_negatives(arr)` that sorts an arra...
def counting_sort(arr, exp): """ A helper function to perform counting sort on arr based on the digit at exp (1, 10, 100, ...), suitable for positive integers. """ n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = abs(arr[i]) // exp count[inde...
def test_radix_sort_with_negatives(): assert radix_sort_with_negatives([-17, 543, -998, 0, 14, -5, 4000, -4001]) == [-4001, -998, -17, -5, 0, 14, 543, 4000] def test_radix_sort_with_negatives_all_positive(): assert radix_sort_with_negatives([3, 1, 2, 5, 4]) == [1, 2, 3, 4, 5] def test_radix_sort_with_negative...
[ { "docstring": "A helper function to perform counting sort on arr based on the\ndigit at exp (1, 10, 100, ...), suitable for positive integers.", "function_declaration": "def counting_sort(arr, exp):", "function_name": "counting_sort", "parameter_list": "(arr, exp)" }, { "docstring": "A help...
[ 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):\n \"\"\"\n A helper function to perform counting sort on arr based on the\n digit at exp (1, 10, 100, ...), suitable for...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00048067", "row_id": 48067, "seed_ids": "[15]" }
0.638898
Data_Structure_48067
I
[ "counting_sort", "radix_sort", "radix_sort_with_negatives" ]
3
[ [ "radix_sort", "counting_sort" ], [ "radix_sort_with_negatives", "radix_sort" ] ]
2
[]
false
[]
false
pytest
false
[]
true
d667d8bbe5d3db54d61741a1bd096684f19cfafa
0948443e81bb0a42addc436deb8c62b2f067ca17
v1.0
instruct
Data_Structure
Data_Structure_48077_I
### Sudoku Solver with Heuristic Backtracking #### Background Sudoku is a popular number puzzle that requires filling a 9x9 grid in such a way that each row, column, and each of the 9 3x3 subgrids contains all digits from 1 to 9 exactly once. Given a partially filled grid, we need to fill the rest and complete the puz...
from typing import List, Tuple def find_unassigned_cell(board: List[List[str]]) -> Tuple[int, int]: min_options = float('inf') best_cell = (-1, -1) for r in range(9): for c in range(9): if board[r][c] == '.': options = get_possible_values(board, r, c) ...
from solution import sudoku_solver def test_sudoku_solver(): board = [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], [...
[ { "docstring": null, "function_declaration": "def find_unassigned_cell(board):", "function_name": "find_unassigned_cell", "parameter_list": "(board)" }, { "docstring": null, "function_declaration": "def get_possible_values(board, row, col):", "function_name": "get_possible_values", ...
[ 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 sudoku_solver(board: List[List[str]]) -> bool:\n def is_valid(board, row, col, num):\n for i in range(9):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048077", "row_id": 48077, "seed_ids": "[179]" }
0.677337
Data_Structure_48077
I
[ "find_unassigned_cell", "get_possible_values", "sudoku_solver" ]
3
[ [ "find_unassigned_cell", "get_possible_values" ], [ "sudoku_solver", "find_unassigned_cell" ], [ "sudoku_solver", "get_possible_values" ] ]
3
[]
false
[]
false
pytest
true
[]
true
467aafa3e8169d3a93a055dfa2a414579569d079
2ee625acce4d78c7b5d0d6fa4286e588e19f9089
v1.0
instruct
Data_Structure
Data_Structure_48078_I
Maximum Flow in Transportation Network **Context**: In a city transportation network, various intersections are linked by roads with a certain capacity representing the maximum number of vehicles that can pass through per unit time. The goal is to determine the maximum number of vehicles that can travel from a designa...
from collections import deque from typing import List def bfs(capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool: visited = [False] * len(capacity) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() for v, cap in enumerate(capacit...
from solution import maximum_flow def test_simple_case(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert maximum_flow(capacity, sou...
[ { "docstring": null, "function_declaration": "def bfs(capacity, source, sink, parent):", "function_name": "bfs", "parameter_list": "(capacity, source, sink, parent)" }, { "docstring": null, "function_declaration": "def maximum_flow(capacity, source, sink):", "function_name": "maximum...
[ 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 maximum_flow(capacity: list[list[int]], source: int, sink: int) -> int:\n from collections import deque\n \n n = len(capacity)\n residual_capa...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048078", "row_id": 48078, "seed_ids": "[240]" }
0.634938
Data_Structure_48078
I
[ "bfs", "maximum_flow" ]
2
[ [ "maximum_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
320feb5e597d117c9b314e2cecb73463e0d40dad
ee509907f02deba2ab97635ec1b4aa24fd684cc1
v1.0
instruct
Data_Structure
Data_Structure_48088_I
You are given the implementation of Bitonic Sort. Your task is to modify the provided algorithm to handle arrays whose sizes are not powers of two by padding the array with `float('inf')` values to the next power of two, then sorting the padded array, and finally returning the sorted non-inf part. ### Function Signatu...
def next_power_of_two(n): """ Returns the next power of two greater than or equal to n """ if n == 0: return 1 n -= 1 n |= n >> 1 n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 n += 1 return n def bitonic_merge(arr, low, cnt, direction): """ Helper function to merg...
from solution import custom_bitonic_sort def test_custom_bitonic_sort_ascending(): assert custom_bitonic_sort([3, 7, 2, 5, 1], reverse=True) == [1, 2, 3, 5, 7] assert custom_bitonic_sort([10, 2, 3], reverse=True) == [2, 3, 10] assert custom_bitonic_sort([], reverse=True) == [] assert custom_bitonic_sor...
[ { "docstring": "Returns the next power of two greater than or equal to n ", "function_declaration": "def next_power_of_two(n):", "function_name": "next_power_of_two", "parameter_list": "(n)" }, { "docstring": "Helper function to merge bitonic sequence ", "function_declaration": "def bito...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef bitonic_compare_and_swap(arr, i, j, direction):\n if (direction == (arr[i] > arr[j])):\n arr[i], arr[j] = arr[j, arr[i]\n\ndef bi...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00048088", "row_id": 48088, "seed_ids": "[17]" }
0.679704
Data_Structure_48088
I
[ "next_power_of_two", "bitonic_merge", "bitonic_sort_recursive", "bitonic_sort", "custom_bitonic_sort" ]
5
[ [ "bitonic_sort", "bitonic_sort_recursive" ], [ "bitonic_sort_recursive", "bitonic_merge" ], [ "custom_bitonic_sort", "bitonic_sort" ], [ "custom_bitonic_sort", "next_power_of_two" ] ]
4
[]
false
[]
false
pytest
true
[]
true
b37f9abc5c926a548bf03a23ee2920a0e5ed9f6c
b3f0c574ed41c70896db5ff47fe96e16d3ff9084
v1.0
instruct
Data_Structure
Data_Structure_48161_I
## Question: Implement a Secure Communication Protocol Using Modular Arithmetic You are working on designing a secure communication protocol that relies on modular arithmetic to encode and decode messages. An essential part of this protocol involves finding modular inverses to decrypt messages. ### Task Your task is ...
def extended_gcd(a, b): """ Returns a tuple (x, y, gcd(a, b)) where x and y satisfy the equation ax + by = gcd(a, b). """ if b == 0: return (1, 0, a) else: x1, y1, gcd = extended_gcd(b, a % b) x = y1 y = x1 - (a // b) * y1 return (x, y, gcd) def modular_inver...
from solution import extended_gcd, modular_inverse def test_extended_gcd(): assert extended_gcd(30, 20) == (1, -1, 10) assert extended_gcd(20, 30) == (-1, 1, 10) assert extended_gcd(35, 15) == (1, -2, 5) assert extended_gcd(101, 10) == (1, -10, 1) assert extended_gcd(10, 101) == (-10, 1, 1) def te...
[ { "docstring": "Returns a tuple (x, y, gcd(a, b)) where x and y satisfy the equation ax + by = gcd(a, b).", "function_declaration": "def extended_gcd(a, b):", "function_name": "extended_gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the modular inverse of a modulo m.\nIf a and m...
[ 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 extended_gcd(a, b):\n \"\"\"\n Computes the coefficients x and y such that ax + by = gcd(a, b) using the extended Euclidean algorithm.\n \n :p...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048161", "row_id": 48161, "seed_ids": "[161]" }
0.533773
Data_Structure_48161
I
[ "extended_gcd", "modular_inverse" ]
2
[ [ "modular_inverse", "extended_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
47ba38216ebaac41fa6d558938c8625d26c23869
b9a89ab291fa9c72fdfdaaf225f0e8f2328445fc
v1.0
instruct
Data_Structure
Data_Structure_48200_I
### Ternary Search Implementation You are provided with a basic implementation of the Ternary Search algorithm. Your understanding of this algorithm will be assessed through modifications and enhancements. #### Problem Statement 1. Implement a revised version of `ternary_search` that addresses potential edge cases an...
def ternary_search(arr, key, left, right): if right >= left: mid1 = left + (right - left) // 3 mid2 = right - (right - left) // 3 if arr[mid1] == key: return mid1 if arr[mid2] == key: return mid2 if key < arr[mid1]: return ternary_search(...
from solution import search_in_sorted_array, is_sorted def test_is_sorted(): assert is_sorted([1, 2, 3, 4, 5]) == True assert is_sorted([5, 4, 3, 2, 1]) == False assert is_sorted([1, 1, 1, 1, 1]) == True assert is_sorted([]) == True assert is_sorted([1]) == True def test_search_in_sorted_array(): ...
[ { "docstring": null, "function_declaration": "def ternary_search(arr, key, left, right):", "function_name": "ternary_search", "parameter_list": "(arr, key, left, right)" }, { "docstring": null, "function_declaration": "def search_in_sorted_array(arr, key):", "function_name": "search_...
[ 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 ternary_search(arr, key, left, right):\n if right >= left:\n mid1 = left + (right - left) // 3\n mid2 = right - (right - left) // 3\n\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00048200", "row_id": 48200, "seed_ids": "[193]" }
0.604973
Data_Structure_48200
I
[ "ternary_search", "search_in_sorted_array", "is_sorted" ]
3
[ [ "search_in_sorted_array", "ternary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3009c8e28a9bfe7e95ecb4ee4cdf4cf317e861a1
f54686dcd895936ecfdd591976dda9a846495637
v1.0
instruct
Data_Structure
Data_Structure_48248_I
### Scenario You are tasked with implementing a network routing system for a telecommunication company, ensuring optimal bandwidth utilization without any data loss. The network is modeled as a directed graph where nodes represent network routers/switches and edges represent communication channels with specific bandwid...
from collections import deque def bfs(C, F, source, sink, P): visited = [False] * len(C) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() for v, cap in enumerate(C[u]): if not visited[v] and cap - F[u][v] > 0: # Residual capacity available ...
from solution import max_flow def test_ford_fulkerson_basic(): capacity = [ [0, 10, 10, 0, 0, 0], [0, 0, 5, 15, 0, 0], [0, 0, 0, 10, 10, 0], [0, 0, 0, 0, 10, 10], [0, 0, 0, 15, 0, 10], [0, 0, 0, 0, 0, 0] ] assert max_flow(capacity, 0, 5, "ford_fulkerson") == ...
[ { "docstring": null, "function_declaration": "def bfs(C, F, source, sink, P):", "function_name": "bfs", "parameter_list": "(C, F, source, sink, P)" }, { "docstring": null, "function_declaration": "def dfs(C, F, u, sink, P):", "function_name": "dfs", "parameter_list": "(C, F, u, s...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef bfs(C, F, source, sink, P):\n visited = [False] * len(C)\n queue = deque([source])\n visited[source] = True\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00048248", "row_id": 48248, "seed_ids": "[240]" }
0.594683
Data_Structure_48248
I
[ "bfs", "dfs", "ford_fulkerson", "edmonds_karp", "dinic_bfs", "dinic_dfs", "dinic", "max_flow" ]
8
[ [ "dinic", "dinic_bfs" ], [ "dinic", "dinic_dfs" ], [ "edmonds_karp", "bfs" ], [ "ford_fulkerson", "dfs" ], [ "max_flow", "dinic" ], [ "max_flow", "edmonds_karp" ], [ "max_flow", "ford_fulkerson" ] ]
7
[]
false
[]
false
pytest
true
[]
true
72fd42442387784fc7b48267663b45431371a8c0
39d949c1b59cb8d666c3aef6cd809c063125b4dd
v1.0
instruct
Data_Structure
Data_Structure_48251_I
### Problem: Insertion Sort with Binary Search Helper You are tasked with implementing the `insertion_sort` algorithm, which sorts an array of integers in ascending order. To achieve this efficiently, you will use the provided `search_insert` function to find the appropriate index for each element. #### Function Sign...
from typing import List def search_insert(array: List[int], val: int) -> int: low = 0 high = len(array) - 1 while low <= high: mid = low + (high - low) // 2 if val > array[mid]: low = mid + 1 else: high = mid - 1 return low def insertion_sort(array: List...
from solution import insertion_sort def test_insertion_sort_example_1(): assert insertion_sort([4, 3, 2, 1]) == [1, 2, 3, 4] def test_insertion_sort_example_2(): assert insertion_sort([10, 8, 12, 5, 6, 2]) == [2, 5, 6, 8, 10, 12] def test_insertion_sort_empty(): assert insertion_sort([]) == [] def test_...
[ { "docstring": null, "function_declaration": "def search_insert(array, val):", "function_name": "search_insert", "parameter_list": "(array, val)" }, { "docstring": null, "function_declaration": "def insertion_sort(array):", "function_name": "insertion_sort", "parameter_list": "(a...
[ 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 \"\"\"\n Helper function to determine the insertion index for `val` i...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048251", "row_id": 48251, "seed_ids": "[199]" }
0.592361
Data_Structure_48251
I
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7e70bd50f05da605e5c0e432c0a97fdbf5a58230
adba36038dcaf6de9635209c549536fa866f0001
v1.0
instruct
Data_Structure
Data_Structure_48345_I
You are part of a team developing an intelligent recommendation system. Your task involves implementing the nearest neighbor algorithm to help categorize new data points based on existing labeled data. Implement a function `nearest_neighbor_classify` that, given an input vector and a labeled dataset, identifies the c...
from typing import Tuple, Dict, Any import math def nearest_neighbor_classify(x: Tuple[float, ...], tSet: Dict[Tuple[float, ...], Any]) -> Any: """ Identifies the closest vector in the training set to the input vector using Euclidean distance, and returns the label associated with that vector. """ ...
from solution import nearest_neighbor_classify def test_exact_match(): x = (1.0, 2.0) tSet = { (1.0, 2.0): "A", (0.9, 2.0): "B" } assert nearest_neighbor_classify(x, tSet) == "A" def test_closest_match(): x = (1.0, 2.0) tSet = { (1.1, 2.1): "A", (0.9, 2.0): "C" ...
[ { "docstring": "Identifies the closest vector in the training set to the input vector using Euclidean distance,\nand returns the label associated with that vector.", "function_declaration": "def nearest_neighbor_classify(x, tSet):", "function_name": "nearest_neighbor_classify", "parameter_list": "(x...
[ 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 Tuple, Dict, Any\nimport math\n\ndef nearest_neighbor_classify(x: Tuple[float, ...], tSet: Dict[Tuple[float, ...], Any]) -> Any:\n \"\"\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00048345", "row_id": 48345, "seed_ids": "[260]" }
0.654796
Data_Structure_48345
I
[ "nearest_neighbor_classify", "euclidean_distance" ]
2
[ [ "nearest_neighbor_classify", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4c9860e95f9eee1ffe6f80d97adde5def907519b
8982e6fa7b0108294c1f982088583f5ca32b07e4
v1.0
instruct
Data_Structure
Data_Structure_48361_I
### RSA Key Generation and Message Encryption/Decryption Given the RSA encryption system, your task is to implement the functions needed to generate an RSA key pair (public and private keys) and use these to encrypt and decrypt a given message. #### Task Implement the following functions: 1. `generate_key(k, seed=No...
import random from sympy import isprime, mod_inverse def generate_key(k, seed=None): """ Generates an RSA public-private key pair where k is the number of bits in the modulus n. """ if seed: random.seed(seed) # Ensure k is at least 8 bits if k < 8: raise ValueError("Bit length k...
from solution import generate_key, encrypt, decrypt def test_generate_key(): n, e, d = generate_key(16, seed=42) assert isinstance(n, int) and n > 0 assert isinstance(e, int) and e > 0 assert isinstance(d, int) and d > 0 def test_encrypt_decrypt(): n, e, d = generate_key(16, seed=42) data ...
[ { "docstring": "Generates an RSA public-private key pair where k is the number of bits in the modulus n.", "function_declaration": "def generate_key(k, seed=None):", "function_name": "generate_key", "parameter_list": "(k, seed=None)" }, { "docstring": null, "function_declaration": "def g...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_large_prime(bits, seed=None):\n \"\"\"Generate a random large prime number of approxi...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00048361", "row_id": 48361, "seed_ids": "[154]" }
0.687186
Data_Structure_48361
I
[ "generate_key", "get_prime", "get_coprime", "gcd", "encrypt", "decrypt" ]
6
[ [ "generate_key", "get_coprime" ], [ "generate_key", "get_prime" ], [ "get_coprime", "gcd" ] ]
3
[]
false
[]
false
pytest
true
[ "sympy" ]
false
6cce2026e8e32ec5c63b2c6a93e30c719212e602
4e15d2d48cd39875e07e9801481a85bc8fbf66b9
v1.0
instruct
Data_Structure
Data_Structure_48383_I
#### Context You are working on a project to develop a library of functions related to number theory and integer operations. One of the components that you need to implement involves efficiently determining the greatest common divisor (GCD), least common multiple (LCM), and handling other related bitwise operations. #...
def gcd(a: int, b: int) -> int: """ Returns the greatest common divisor of a and b using the Euclidean algorithm. """ if a == 0 or b == 0: raise ValueError("Inputs must be non-zero integers.") a, b = abs(a), abs(b) while b != 0: a, b = b, a % b return a def lcm(a: int, b: in...
from solution import gcd, lcm, trailing_zero, gcd_bit def test_gcd_basic(): assert gcd(48, 18) == 6 assert gcd(-48, -18) == 6 assert gcd(14, 21) == 7 def test_gcd_edge_cases(): try: gcd(0, 18) except ValueError: assert True else: assert False def test_lcm_basic(): ...
[ { "docstring": "Returns the greatest common divisor of a and b using the Euclidean algorithm.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the least common multiple of a and b.", "function_declaration": "def lcm...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def gcd(a: int, b: int) -> int:\n \"\"\"\n Returns the greatest common divisor of a and b using the Euclidean algorithm.\n \"\"\"\n if a == 0 or b...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00048383", "row_id": 48383, "seed_ids": "[166]" }
0.588661
Data_Structure_48383
I
[ "gcd", "lcm", "trailing_zero", "gcd_bit" ]
4
[ [ "lcm", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d502063684b5c28d1745494be9ccee6230cdc917
24399e6d7c83dc6823d1c9ab5aaac540ac06b0e2
v1.0
instruct
Data_Structure
Data_Structure_48425_I
You are given an \(n \times n\) matrix of integers. Your task is to write a function `invert_matrix(matrix: List[List[int]]) -> List[List[float]]` that returns the inverse of the matrix. If the matrix is not invertible, return an error code inside a nested list. ### Guidelines 1. Implement the inversion process for sq...
from typing import List def determinant(matrix: List[List[int]], n: int) -> int: """ Helper function to compute determinant of given matrix of size n x n """ if n == 1: return matrix[0][0] if n == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] det = 0 for c in r...
from solution import invert_matrix def test_invert_2x2_matrix(): matrix = [ [4, 7], [2, 6] ] result = invert_matrix(matrix) expected = [ [0.6, -0.7], [-0.2, 0.4] ] for r, e in zip(result, expected): assert all(abs(val_r - val_e) < 1e-9 for val_r, val_e in...
[ { "docstring": "Helper function to compute determinant of given matrix of size n x n ", "function_declaration": "def determinant(matrix, n):", "function_name": "determinant", "parameter_list": "(matrix, n)" }, { "docstring": "Helper function to get cofactor of matrix[p][q] ", "function_d...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef invert_matrix(matrix: List[List[int]]) -> List[List[float]]:\n def matrix_minor(m, i, j):\n return [row[:j] + row[j+1...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048425", "row_id": 48425, "seed_ids": "[347]" }
0.587468
Data_Structure_48425
I
[ "determinant", "get_cofactor", "adjoint", "invert_matrix" ]
4
[ [ "adjoint", "determinant" ], [ "adjoint", "get_cofactor" ], [ "invert_matrix", "adjoint" ], [ "invert_matrix", "determinant" ] ]
4
[]
false
[]
false
pytest
true
[]
true
c9163e59454fb64969b043e5fb3d009820146981
de0b9ca86157927b848af4409512585c35912b3d
v1.0
instruct
Data_Structure
Data_Structure_48443_I
You are tasked with implementing a secure key exchange protocol between two parties, Alice and Bob. Specifically, you will use the Diffie-Hellman key exchange algorithm, while ensuring the primality and suitability of the given numbers. #### Problem Statement Implement the function `secure_key_exchange(a: int, p: int)...
import random def is_prime(n): if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def gcd(a, b): wh...
from solution import secure_key_exchange from solution import is_prime, gcd, find_primitive_root 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(23) == True assert is_prime(24) == False def test_g...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function...
[ 0, 0, 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": "def secure_key_exchange(a: int, p: int) -> bool:\n import random\n \n def is_prime(n):\n \"\"\"Return True if n is a prime number, else False....
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00048443", "row_id": 48443, "seed_ids": "[146]" }
0.461888
Data_Structure_48443
I
[ "is_prime", "gcd", "find_primitive_root", "secure_key_exchange" ]
4
[ [ "find_primitive_root", "is_prime" ], [ "secure_key_exchange", "find_primitive_root" ], [ "secure_key_exchange", "is_prime" ] ]
3
[]
false
[]
false
pytest
true
[]
true
4247c9ae51607ccd1f9058bc2c83621816dea4b4
01b0e974df69589e63073e430b9d0e042ab3eb4b
v1.0
instruct
Data_Structure
Data_Structure_48464_I
### Question: Implement an Efficient Bucket Sort Algorithm #### Background Bucket Sort is a sorting algorithm that distributes elements of an array into a number of buckets. Each bucket is then sorted individually using a different sorting algorithm. Finally, the sorted buckets are concatenated to form a sorted array....
from typing import List import math def efficient_bucket_sort(arr: List[int], bucket_size: int) -> List[int]: """ Sorts a list of non-negative integers using the bucket sort algorithm. Parameters: arr (List[int]): List of non-negative integers to sort. bucket_size (int): The size of ea...
from solution import efficient_bucket_sort def test_empty_array(): assert efficient_bucket_sort([], 5) == [] def test_single_element_array(): assert efficient_bucket_sort([1], 5) == [1] def test_sorted_array(): assert efficient_bucket_sort([1, 2, 3, 4, 5], 2) == [1, 2, 3, 4, 5] def test_reverse_sorted_a...
[ { "docstring": "Sorts a list of non-negative integers using the bucket sort algorithm.\n\nParameters:\n arr (List[int]): List of non-negative integers to sort.\n bucket_size (int): The size of each bucket.\n \nReturns:\n List[int]: Sorted list of integers.", "function_declaration": "def efficien...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def efficient_bucket_sort(arr, bucket_size):\n \"\"\"\n Sorts an array using an efficient bucket sort algorithm.\n \n Parameters:\n arr (list o...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048464", "row_id": 48464, "seed_ids": "[26]" }
0.558774
Data_Structure_48464
I
[ "efficient_bucket_sort", "quicksort" ]
2
[ [ "efficient_bucket_sort", "quicksort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0eb3c75affb8be52b5d8e74be267c177c8e7dc52
5b7a00a95dea49113f46e82fb4dafb53e1e66fe3
v1.0
instruct
Data_Structure
Data_Structure_48476_I
### Quick Sort Optimization and Implementation Quick Sort is a widely used sorting algorithm known for its efficiency in average cases while having potential performance pitfalls with poor pivot choices. Your task is to implement a hybrid version of Quick Sort that improves upon the traditional algorithm by optimizing...
def median_of_three(arr, low, high): mid = (low + high) // 2 if arr[low] > arr[mid]: arr[low], arr[mid] = arr[mid], arr[low] if arr[low] > arr[high]: arr[low], arr[high] = arr[high], arr[low] if arr[mid] > arr[high]: arr[mid], arr[high] = arr[high], arr[mid] return mid def i...
from solution import hybrid_quick_sort def test_hybrid_quick_sort_normal_case(): arr = [3, 6, 8, 10, 1, 2, 1] assert hybrid_quick_sort(arr) == [1, 1, 2, 3, 6, 8, 10] def test_hybrid_quick_sort_with_threshold(): arr = [3, 6, 8, 10, 1, 2, 1] assert hybrid_quick_sort(arr, threshold=2) == [1, 1, 2, 3, 6, ...
[ { "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 insertion_sort(arr, low, high):", "function_name": "insertion_sort", ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def insertion_sort(arr, left, right):\n for i in range(left + 1, right + 1):\n key = arr[i]\n j = i - 1\n while j >= left and arr[j] >...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00048476", "row_id": 48476, "seed_ids": "[25]" }
0.576793
Data_Structure_48476
I
[ "median_of_three", "insertion_sort", "quick_sort_helper", "hybrid_quick_sort" ]
4
[ [ "hybrid_quick_sort", "quick_sort_helper" ], [ "quick_sort_helper", "insertion_sort" ], [ "quick_sort_helper", "median_of_three" ] ]
3
[]
false
[]
false
pytest
true
[]
true
d327a5f0c6ed617822145ca682102449e0c5b9d7
d5dc00cdea3729b4b5dd9e1de21b16a31ad2d439
v1.0
instruct
Data_Structure
Data_Structure_48516_I
#### Scenario You have been hired to optimize a warehouse inventory system. The system must keep an ordered list of product prices; however, products arrive in an arbitrary order. You need to implement an optimized insertion sort algorithm that leverages binary search to find the correct insertion points to minimize t...
from bisect import bisect_left def search_insert(array, value): """ Find the index where value should be inserted to keep array sorted. """ return bisect_left(array, value) def optimized_insertion_sort(array: list) -> list: """ Perform an optimized insertion sort on the input array using binar...
from solution import optimized_insertion_sort def test_optimized_insertion_sort_basic(): assert optimized_insertion_sort([4, 2, 3, 1]) == [1, 2, 3, 4] assert optimized_insertion_sort([7, 2, 5, 3, 9]) == [2, 3, 5, 7, 9] def test_optimized_insertion_sort_already_sorted(): assert optimized_insertion_sort([1,...
[ { "docstring": "Find the index where value should be inserted to keep array sorted.", "function_declaration": "def search_insert(array, value):", "function_name": "search_insert", "parameter_list": "(array, value)" }, { "docstring": "Perform an optimized insertion sort on the input array usi...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def search_insert(arr, val):\n \"\"\"\n A helper function that uses binary search to find the insertion index for val in arr.\n \"\"\"\n low, high...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048516", "row_id": 48516, "seed_ids": "[199]" }
0.52068
Data_Structure_48516
I
[ "search_insert", "optimized_insertion_sort" ]
2
[ [ "optimized_insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
82ef9bf0020ab169f52527fa99b176abcb115aa6
cca6732bebf2ea0a98a8ebcc951189f1e7f7e2c1
v1.0
instruct
Data_Structure
Data_Structure_48553_I
#### Problem Description: You are given two words, `begin_word` and `end_word`, and a dictionary of words called `word_list`. All the words in the dictionary and the given words are of the same length and contain only lowercase alphabets. You are to find the length of the shortest transformation sequence from `begin_w...
from collections import deque from typing import List def ladder_length(begin_word: str, end_word: str, word_list: List[str]) -> int: """ Finds the shortest transformation sequence from begin_word to end_word, changing only one letter at a time, using words from word_list. """ if end_word not in wo...
from solution import ladder_length def test_ladder_length_basic_case(): assert ladder_length("hit", "cog", ["hot","dot","dog","lot","log","cog"]) == 5 def test_ladder_length_no_such_transformation(): assert ladder_length("hit", "cog", ["hot","dot","dog","lot","log"]) == -1 def test_ladder_length_same_begin_e...
[ { "docstring": "Finds the shortest transformation sequence from begin_word to end_word,\nchanging only one letter at a time, using words from word_list.", "function_declaration": "def ladder_length(begin_word, end_word, word_list):", "function_name": "ladder_length", "parameter_list": "(begin_word, ...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef ladder_length(begin_word, end_word, word_list):\n def get_neighbors(word):\n neighbors = []\n for i in r...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00048553", "row_id": 48553, "seed_ids": "[187]" }
0.628366
Data_Structure_48553
I
[ "ladder_length", "visit_word_node" ]
2
[ [ "ladder_length", "visit_word_node" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e7de38b1795324cd5e5b9ea5014a0d1603a1a865
490dcdce8ea997512e9add59d1184ce451ec3882
v1.0
instruct
Data_Structure
Data_Structure_48562_I
You are given an implementation of the RSA key generation algorithm and the procedures for encryption and decryption. Your task is to complete the function `rsa_encryption` which takes in a string message and a bit length `k`, and returns the encrypted message using RSA encryption. You need to generate the RSA keys (wi...
import random from sympy import isprime, gcd from sympy.ntheory.generate import randprime import math def modinv(a, m): m0, x0, x1 = m, 0, 1 if m == 1: return 0 while a > 1: q = a // m m, a = a % m, m x0, x1 = x1 - q * x0, x0 return x1 + m0 if x1 < 0 else x1 def generat...
from solution import rsa_encryption def test_rsa_encryption(): message = "HELLO" k = 64 n, e, d, encrypted_message = rsa_encryption(message, k) # Check if n, e, d have been generated properly assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) # Check...
[ { "docstring": null, "function_declaration": "def modinv(a, m):", "function_name": "modinv", "parameter_list": "(a, m)" }, { "docstring": "Generate RSA keys given a bit length `k`.\nReturns (n, e, d) for modulus n, public exponent e, and private exponent d.", "function_declaration": "def...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_prime_candidate(bit_length):\n candidate = random.getrandbits(bit_length)\n candid...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00048562", "row_id": 48562, "seed_ids": "[154]" }
0.710454
Data_Structure_48562
I
[ "modinv", "generate_rsa_keys", "rsa_encrypt", "rsa_encryption" ]
4
[ [ "generate_rsa_keys", "modinv" ], [ "rsa_encryption", "generate_rsa_keys" ], [ "rsa_encryption", "rsa_encrypt" ] ]
3
[]
false
[]
false
pytest
true
[ "sympy" ]
false
a6a07ecff646eaf1903e8ee35c2410471a06e072
840e1967f622ccddc0ed963c462beed3d959c39a
v1.0
instruct
Data_Structure
Data_Structure_48609_I
### Question: Subtree Validation Given two binary trees represented by their root nodes `big` and `small`, write a function `is_subtree(big, small)` to determine if `small` is a subtree of `big`. A subtree of a node in a binary tree should consist of that node and all its descendants in the exact structure. ### Fu...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_subtree(big: TreeNode, small: TreeNode) -> bool: if not small: return True if not big: return False if same_tree(big, small): retu...
import pytest from solution import TreeNode, is_subtree def test_is_subtree_case_1(): big = TreeNode(3) big.left = TreeNode(4) big.right = TreeNode(5) big.left.left = TreeNode(1) big.left.right = TreeNode(2) small = TreeNode(4) small.left = TreeNode(1) small.right = TreeNode(2) as...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef are_identical(root1, root2):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048609", "row_id": 48609, "seed_ids": "[288]" }
0.552729
Data_Structure_48609
I
[ "is_subtree", "same_tree" ]
2
[ [ "is_subtree", "same_tree" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
ec871770c2697b5ab1ca0bf7079fcc79c3aa5c98
018daf43277cdb5dcae8aa6098a5d9d280e3783f
v1.0
instruct
Data_Structure
Data_Structure_48615_I
### RSA Encryption/Decryption Implementation You are tasked with securing a communication channel using RSA encryption. You need to create functions to securely transmit numeric data using RSA. Below is the RSA key generation and encryption code provided for your reference. You need to implement the necessary wrapper ...
import random from sympy import isprime, gcd, mod_inverse def generate_prime(bit_length): while True: p = random.getrandbits(bit_length) if isprime(p): return p def rsa_generate_keys(bit_length): """ Generates RSA keys of the specified bit length. """ e = 65537 # commo...
from solution import rsa_generate_keys, rsa_encrypt, rsa_decrypt def test_rsa_generate_keys_bit_length_16(): public_key, private_key, modulus = rsa_generate_keys(16) assert type(public_key) == tuple assert type(private_key) == int assert type(modulus) == int def test_rsa_generate_keys_bit_length_32()...
[ { "docstring": null, "function_declaration": "def generate_prime(bit_length):", "function_name": "generate_prime", "parameter_list": "(bit_length)" }, { "docstring": "Generates RSA keys of the specified bit length.", "function_declaration": "def rsa_generate_keys(bit_length):", "func...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef rsa_generate_keys(bit_length):\n def generate_large_prime(bits):\n while True:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00048615", "row_id": 48615, "seed_ids": "[154]" }
0.620347
Data_Structure_48615
I
[ "generate_prime", "rsa_generate_keys", "rsa_encrypt", "rsa_decrypt" ]
4
[ [ "rsa_generate_keys", "generate_prime" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
5937b97b6f82103f25231e52ba33aa3da55793df
dc7c9347e95648ea28397bdf1280b62e51231778
v1.0
instruct
Data_Structure
Data_Structure_48678_I
### Matrix Exponentiation Programming Assessment #### Context: Matrix exponentiation is a fundamental technique used in various applications ranging from computer graphics to solving linear recurrence relations efficiently. The core algorithm leverages repeated squaring to achieve logarithmic reduction in the number ...
def matrix_multiply(mat1, mat2): size = len(mat1) result = [[0] * size for _ in range(size)] for i in range(size): for j in range(size): for k in range(size): result[i][j] += mat1[i][k] * mat2[k][j] return result def identity_matrix(size): return [[1 if...
from solution import power_matrix, matrix_multiply def test_power_matrix_example1(): mat = [ [1, 2], [3, 4] ] p = 2 expected = [ [7, 10], [15, 22] ] assert power_matrix(mat, p) == expected def test_power_matrix_example2(): mat = [ [1, 0], [0,...
[ { "docstring": null, "function_declaration": "def matrix_multiply(mat1, mat2):", "function_name": "matrix_multiply", "parameter_list": "(mat1, mat2)" }, { "docstring": null, "function_declaration": "def identity_matrix(size):", "function_name": "identity_matrix", "parameter_list"...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def identity_matrix(size):\n \"\"\"\n Returns the identity matrix of given size.\n \"\"\"\n return [[1 if i == j else 0 for j in range(size)] for ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00048678", "row_id": 48678, "seed_ids": "[340]" }
0.548534
Data_Structure_48678
I
[ "matrix_multiply", "identity_matrix", "power_matrix" ]
3
[ [ "power_matrix", "identity_matrix" ], [ "power_matrix", "matrix_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
61448cc8dd69078eb407cd467123b54bc4eab8c9
dd028d4675942089a252398c644f0516cfe0f784
v1.0
instruct
Data_Structure
Data_Structure_48700_I
#### Context You are tasked with implementing a more efficient variant of the Insertion Sort algorithm to handle larger datasets. You will modify the traditional Insertion Sort to use binary search to locate the position where the current element should be inserted. #### Task Write a function `binary_injection_sort(ar...
def binary_search(arr, val, start, end): while start < end: mid = (start + end) // 2 if arr[mid] < val: start = mid + 1 else: end = mid return start def binary_injection_sort(arr): for i in range(1, len(arr)): val = arr[i] pos = binary_search(...
from solution import binary_injection_sort def test_binary_injection_sort_unsorted(): assert binary_injection_sort([4, 2, 8, 5, 7]) == [2, 4, 5, 7, 8] def test_binary_injection_sort_reverse_sorted(): assert binary_injection_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_binary_injection_sort_already_sorte...
[ { "docstring": null, "function_declaration": "def binary_search(arr, val, start, end):", "function_name": "binary_search", "parameter_list": "(arr, val, start, end)" }, { "docstring": null, "function_declaration": "def binary_injection_sort(arr):", "function_name": "binary_injection_...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def binary_search(arr, val, start, end):\n \"\"\"\n Helper function to perform binary search.\n It returns the index where the value should be insert...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048700", "row_id": 48700, "seed_ids": "[7]" }
0.558476
Data_Structure_48700
I
[ "binary_search", "binary_injection_sort" ]
2
[ [ "binary_injection_sort", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
025b7a4edf7b663febee4c0702564b2809bbe806
2e07b3cb2513d32b486a6ab6123adfd8d33ef533
v1.0
instruct
Data_Structure
Data_Structure_48713_I
<|Analysis Begin|> ### Algorithm/Data Structure: This algorithm implements a **Trie** (Prefix Tree) combined with **Backtracking** to solve the "Word Search II" problem, which involves finding all words from a list that exist in a given board. ### Complexity: - **Time Complexity**: O(M * (4 * 3^L)), where M is the n...
class TrieNode: def __init__(self): self.children = {} self.word = None def build_trie(words): root = TrieNode() for word in words: node = root for letter in word: if letter not in node.children: node.children[letter] = TrieNode() node...
from solution import find_words_in_board def test_find_words_in_board_example(): board = [ ['o', 'a', 'a', 'n'], ['e', 't', 'a', 'e'], ['i', 'h', 'k', 'r'], ['i', 'f', 'l', 'v'] ] words = ["oath", "pea", "eat", "rain"] result = find_words_in_board(board, words) expec...
[]
[ 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": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.word = None\n\ndef build_trie(words):\n root = TrieNode()\n for word ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00048713", "row_id": 48713, "seed_ids": "[115]" }
0.521376
Data_Structure_48713
I
[ "build_trie", "find_words_in_board" ]
2
[ [ "find_words_in_board", "build_trie" ] ]
1
[]
false
[ "TrieNode" ]
true
pytest
true
[]
true
3b1596cf83abda069a41f53b646a725f99da7ab3
0427f05a0d901ef2d1b42eeac53b14c186c7d35e
v1.0
instruct
Data_Structure
Data_Structure_48734_I
You are given three functions: `find_order`, `euler_totient`, and `find_primitive_root`, which are used to determine the primitive roots of a given integer `n` based on advanced number theory concepts. **Objectives**: 1. Implement the `find_order` function, which finds the smallest positive integer `k` such that `a^k ...
import math from functools import reduce from sympy import gcd def find_order(a, n): """ Returns the smallest positive integer k such that a^k % n == 1, or -1 if no such integer exists. """ if gcd(a, n) != 1: return -1 k = 1 ak = a % n while ak != 1: ak = (ak * a) %...
from solution import find_order, euler_totient, find_primitive_root def test_find_order(): assert find_order(10, 7) == 6 assert find_order(2, 9) == 6 assert find_order(3, 11) == 5 assert find_order(11, 13) == 12 assert find_order(2, 4) == -1 # gcd(2, 4) != 1, so should return -1 def test_euler_to...
[ { "docstring": "Returns the smallest positive integer k such that a^k % n == 1,\nor -1 if no such integer exists.", "function_declaration": "def find_order(a, n):", "function_name": "find_order", "parameter_list": "(a, n)" }, { "docstring": "Computes Euler's Totient function φ(n), which coun...
[ 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(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef find_order(a, n):\n \"\"\" Find the smallest positive integer k such that a^k % ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048734", "row_id": 48734, "seed_ids": "[160]" }
0.473936
Data_Structure_48734
I
[ "find_order", "euler_totient", "find_primitive_root", "prime_factors" ]
4
[ [ "find_primitive_root", "euler_totient" ], [ "find_primitive_root", "prime_factors" ] ]
2
[]
false
[]
false
pytest
true
[ "sympy" ]
false
298976bc4ef2ca92f3757c447052a3496492e7a8
c254eedcd3ddfa00511223cc6d393830b98d7d64
v1.0
instruct
Data_Structure
Data_Structure_48739_I
### Question: Longest Increasing Subsequence with Multiple Implementations You are given an unsorted array of integers. Your task is to implement a function that finds the length of the longest increasing subsequence (LIS). Write a function `find_LIS_length(sequence: List[int]) -> int` that accomplishes this task. Y...
from typing import List import bisect def find_LIS_length_dp(sequence: List[int]) -> int: """ Returns the length of the longest increasing subsequence using dynamic programming. Time complexity: O(n^2) """ if not sequence: return 0 n = len(sequence) lis = [1] * n for i...
import pytest from solution import find_LIS_length, find_LIS_length_dp, find_LIS_length_optimized def test_find_LIS_length_empty(): assert find_LIS_length([]) == 0 assert find_LIS_length_dp([]) == 0 assert find_LIS_length_optimized([]) == 0 def test_find_LIS_length_single_element(): assert find_LIS_le...
[ { "docstring": "Returns the length of the longest increasing subsequence using dynamic programming.\nTime complexity: O(n^2)", "function_declaration": "def find_LIS_length_dp(sequence):", "function_name": "find_LIS_length_dp", "parameter_list": "(sequence)" }, { "docstring": "Returns the len...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport bisect\n\ndef find_LIS_length_dp(sequence: List[int]) -> int:\n \"\"\"\n Returns the length of the longest increasing su...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00048739", "row_id": 48739, "seed_ids": "[32]" }
0.739986
Data_Structure_48739
I
[ "find_LIS_length_dp", "find_LIS_length_optimized", "find_LIS_length" ]
3
[ [ "find_LIS_length", "find_LIS_length_optimized" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f094e28fe8bb6a3e8ff1a18af1c6699bf70d2065
a7426bbe4e04d6523f0efff8ac765f6113238de2
v1.0
instruct
Data_Structure
Data_Structure_48741_I
Given an integer `N`, write a function `find_min_perfect_squares(N)` that finds the minimum number of perfect squares whose sum equals N, where a perfect square is defined as k^2 for some integer k. The function should return an integer between 1 and 4 as guaranteed by Lagrange's four-square theorem. ### Input - A sin...
import math def is_square(n): sq = int(math.sqrt(n)) return sq * sq == n def find_min_perfect_squares(n): """ Returns the minimum number of perfect squares whose sum equals n. """ # Check if n is a perfect square if is_square(n): return 1 # Check if n can be decomposed int...
from solution import find_min_perfect_squares def test_example_1(): assert find_min_perfect_squares(9) == 1 def test_example_2(): assert find_min_perfect_squares(10) == 2 def test_example_3(): assert find_min_perfect_squares(12) == 3 def test_example_4(): assert find_min_perfect_squares(31) == 4 de...
[ { "docstring": null, "function_declaration": "def is_square(n):", "function_name": "is_square", "parameter_list": "(n)" }, { "docstring": "Returns the minimum number of perfect squares whose sum equals n.", "function_declaration": "def find_min_perfect_squares(n):", "function_name": ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef find_min_perfect_squares(N):\n \"\"\"\n Returns the minimum number of perfect squares whose sum equals N.\n \"\"\"\n # Check fo...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00048741", "row_id": 48741, "seed_ids": "[148]" }
0.787176
Data_Structure_48741
I
[ "is_square", "find_min_perfect_squares" ]
2
[ [ "find_min_perfect_squares", "is_square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
63b1a9592da6eb181137b640f2b1b91eedbc41fc
ac355cb7d12bce2d30ce2e2519d62408e589e9c1
v1.0
instruct
Data_Structure
Data_Structure_48773_I
#### Scenario You are given a special class of numbers called "power sum numbers." These numbers possess a unique property where the sum of their digits, each raised to a consecutive power starting from 1, equals the original number. For example, 89 satisfies this property because 8^1 + 9^2 = 89. #### Task Write a fu...
def is_power_sum_number(n): """ Check if a number n is a power sum number. """ digits = list(map(int, str(n))) sum_of_powers = sum(d ** (i + 1) for i, d in enumerate(digits)) return sum_of_powers == n def find_power_sum_numbers(low, high): """ Find all power sum numbers in the range [lo...
from solution import find_power_sum_numbers def test_find_power_sum_numbers_basic_range(): assert find_power_sum_numbers(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9] def test_find_power_sum_numbers_example_range(): assert find_power_sum_numbers(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89] def test_find_power_sum_numb...
[ { "docstring": "Check if a number n is a power sum number.", "function_declaration": "def is_power_sum_number(n):", "function_name": "is_power_sum_number", "parameter_list": "(n)" }, { "docstring": "Find all power sum numbers in the range [low, high] inclusive.", "function_declaration": ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_power_sum_number(n):\n \"\"\"\n Check if a number n is a power sum number.\n \"\"\"\n digits = list(map(int, str(n)))\n sum_of_powers = ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00048773", "row_id": 48773, "seed_ids": "[135]" }
0.684777
Data_Structure_48773
I
[ "is_power_sum_number", "find_power_sum_numbers" ]
2
[ [ "find_power_sum_numbers", "is_power_sum_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1fb2d9372bf75b30baeb272652e5f06ceda06454
ed2677e0b0a51c5a9e0763c38d090973ef686aa9
v1.0
instruct
Data_Structure
Data_Structure_48777_I
### Question: Enhanced GCD and Trailing Zero Count You are asked to implement a new function that combines the calculation of GCD using bitwise operations and also provides the count of trailing zeros in binary representation of the inputs and the result. The function should handle edge cases such as zero inputs and o...
def count_trailing_zeros(n): """ Counts the number of trailing zeroes in the binary representation of n. """ if n == 0: return 0 count = 0 while (n & 1) == 0: n >>= 1 count += 1 return count def gcd(a, b): """ Computes the GCD of a and b using bitwise operati...
from solution import advanced_gcd_and_trailing_zeros def test_advanced_gcd_and_trailing_zeros_example_case(): assert advanced_gcd_and_trailing_zeros(40, 24) == (8, 3, 3, 3) def test_advanced_gcd_and_trailing_zeros_zero_case(): assert advanced_gcd_and_trailing_zeros(0, 5) == (5, 0, 0, 0) assert advanced_gc...
[ { "docstring": "Counts the number of trailing zeroes in the binary representation of n.", "function_declaration": "def count_trailing_zeros(n):", "function_name": "count_trailing_zeros", "parameter_list": "(n)" }, { "docstring": "Computes the GCD of a and b using bitwise operations.", "f...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def advanced_gcd_and_trailing_zeros(a: int, b: int) -> (int, int, int, int):\n \"\"\"\n Calculates the GCD of a and b using bitwise operations and count...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048777", "row_id": 48777, "seed_ids": "[166]" }
0.612716
Data_Structure_48777
I
[ "count_trailing_zeros", "gcd", "advanced_gcd_and_trailing_zeros" ]
3
[ [ "advanced_gcd_and_trailing_zeros", "count_trailing_zeros" ], [ "advanced_gcd_and_trailing_zeros", "gcd" ], [ "gcd", "count_trailing_zeros" ] ]
3
[]
false
[]
false
pytest
true
[]
true
05657f2f91cdadad9aad9b845cbe35e796867948
000702b0152dbaa3dfdea19a894c3191cb44535f
v1.0
instruct
Data_Structure
Data_Structure_48833_I
Secure Messaging System You have been tasked to implement a secure messaging system that uses the Diffie-Hellman key exchange protocol to establish a shared secret key between two parties, Alice and Bob. Follow the given steps and constraints to correctly perform the key exchange and verify the computed shared keys. ...
import random from typing import List, Tuple def prime_check(num: int) -> bool: """ Checks if a number is prime. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0...
from solution import prime_check, find_primitive_root, diffie_hellman_key_exchange def test_prime_check(): assert prime_check(2) assert prime_check(3) assert not prime_check(4) assert prime_check(5) assert not prime_check(1) assert prime_check(29) assert not prime_check(30) def test_find_p...
[ { "docstring": "Checks if a number is prime.", "function_declaration": "def prime_check(num):", "function_name": "prime_check", "parameter_list": "(num)" }, { "docstring": "Finds all primitive roots of a given prime number n.", "function_declaration": "def find_primitive_root(n):", "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List, Tuple\n\ndef prime_check(num: int) -> bool:\n \"\"\"\n Checks if a number is a prime number.\n \"\"\"\n if...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00048833", "row_id": 48833, "seed_ids": "[146]" }
0.484726
Data_Structure_48833
I
[ "prime_check", "find_primitive_root", "diffie_hellman_key_exchange" ]
3
[ [ "diffie_hellman_key_exchange", "prime_check" ], [ "find_primitive_root", "prime_check" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9c37d2b2cb518375af592f91817fb135d377d7a3
9b45fc3795d1978065606cc34daf086acddb84f8
v1.0
instruct
Data_Structure
Data_Structure_48836_I
### Question: Maximum Flow in a Network with BFS (Edmonds-Karp Algorithm) **Context**: You are working as a network engineer for a company that manages extensive data networks. One of your tasks is to ensure efficient data transfer from a source server to a sink server through the network. To do so, you need to calcul...
from collections import deque from typing import List def bfs(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool: visited = [False] * len(residual_graph) queue = deque([source]) visited[source] = True while queue: node = queue.popleft() for...
from solution import maximum_flow_bfs def test_maximum_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 maximum_flow_bfs(graph) == 23 def test_maxim...
[ { "docstring": null, "function_declaration": "def bfs(residual_graph, source, sink, parent):", "function_name": "bfs", "parameter_list": "(residual_graph, source, sink, parent)" }, { "docstring": null, "function_declaration": "def maximum_flow_bfs(adjacency_matrix):", "function_name"...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs_capacity(residual_graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00048836", "row_id": 48836, "seed_ids": "[229]" }
0.546787
Data_Structure_48836
I
[ "bfs", "maximum_flow_bfs" ]
2
[ [ "maximum_flow_bfs", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9fde93bbbca200693a124cc2b4082953c2a16ccd
915d7861118521e8e5c1997256af79b69abb234e
v1.0
instruct
Data_Structure
Data_Structure_48844_I
Radix Sort Implementation We need to implement the radix sort algorithm. Your task is to write a function that takes a list of non-negative integers and sorts it using the radix sort method. ### Input - A list `arr` of non-negative integers `arr = [n1, n2, n3, ..., nk]` where `0 <= ni <= 10^9` - An optional boolean p...
from typing import List 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: in...
def test_radix_sort_empty_array(): assert radix_sort([]) == [] def test_radix_sort_single_element(): assert radix_sort([42]) == [42] def test_radix_sort_multiple_elements(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_sorted_input(): a...
[ { "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] * 1...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00048844", "row_id": 48844, "seed_ids": "[15]" }
0.610739
Data_Structure_48844
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
false
[]
true
9c2be9492e455166f6b1a8ce2d2f9d04839f0257
09ce573d416269b70cdbe64fd38953e2a50f02c6
v1.0
instruct
Data_Structure
Data_Structure_48954_I
**String Matching with Wildcards** Given a text string and a pattern string, write a function `wildcard_search` to find all starting indices of substrings in the text that match the pattern. The pattern can contain wildcards represented by the character `?`, which matches any single character. Return the list of start...
from typing import List def kmp_partial_match_table(pattern: str) -> List[int]: """ Generates the KMP partial match table (also known as the "pi" table). """ m = len(pattern) pi = [0] * m k = 0 for q in range(1, m): while k > 0 and (pattern[k] != pattern[q] and pattern[k] != '?' and pa...
from solution import wildcard_search def test_wildcard_search_simple(): assert wildcard_search('hello there hero!', 'he?lo') == [0] def test_wildcard_search_multiple_matches(): assert wildcard_search('abcabcabcabc', 'a?c') == [0, 3, 6, 9] def test_wildcard_search_repeated_chars(): assert wildcard_search(...
[ { "docstring": "Generates the KMP partial match table (also known as the \"pi\" table). ", "function_declaration": "def kmp_partial_match_table(pattern):", "function_name": "kmp_partial_match_table", "parameter_list": "(pattern)" }, { "docstring": "Finds all starting indices of substrings in...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef compute_prefix_function_wildcard(pattern: str) -> List[int]:\n \"\"\"\n Computes the prefix function for the given patter...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00048954", "row_id": 48954, "seed_ids": "[93]" }
0.592823
Data_Structure_48954
I
[ "kmp_partial_match_table", "wildcard_search" ]
2
[ [ "wildcard_search", "kmp_partial_match_table" ] ]
1
[]
false
[]
false
pytest
true
[]
true
620572cb259f81a31cd3fced9f2d91885884fc99
e58c591c3049b1a53d40d776f556f1fed821a791
v1.0
instruct
Data_Structure
Data_Structure_49012_I
### Maximum Flow Problem in Flow Network In this task, you are required to implement the **Edmonds-Karp** algorithm to compute the maximum flow in a flow network. The implementation must demonstrate an understanding of BFS for finding augmenting paths and augmenting the flow according to the flow capacities. #### Fun...
from collections import deque from typing import List def bfs(capacity, flow, source, sink, parent): visited = set() queue = deque([source]) visited.add(source) while queue: u = queue.popleft() for v in range(len(capacity)): if v not in visited and capacity[u][v] - flow[u][v...
from solution import edmonds_karp def test_edmonds_karp_example(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert edmonds_karp(capa...
[ { "docstring": null, "function_declaration": "def bfs(capacity, flow, source, sink, parent):", "function_name": "bfs", "parameter_list": "(capacity, flow, source, sink, parent)" }, { "docstring": null, "function_declaration": "def edmonds_karp(capacity, source, sink):", "function_nam...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\nfrom typing import List\n\ndef edmonds_karp(capacity: List[List[int]], source: int, sink: int) -> int:\n n = len(capacity)\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049012", "row_id": 49012, "seed_ids": "[240]" }
0.565899
Data_Structure_49012
I
[ "bfs", "edmonds_karp" ]
2
[ [ "edmonds_karp", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b7c09edea5cdbd811c6f86fd0df2dee96a158405
c3e90672c215d7dfce2d7b2bbe07301c3d2a95fc
v1.0
instruct
Data_Structure
Data_Structure_49019_I
You are working on an embedded system where storage and processing efficiency are critical. You need to implement an efficient compression algorithm that uses bit manipulation to compress and decompress data. Given the functions `get_bit`, `set_bit`, `clear_bit`, and `update_bit`, extend their usage to implement a func...
def get_bit(num, bit): return (num >> bit) & 1 def set_bit(num, bit): return num | (1 << bit) def clear_bit(num, bit): return num & ~(1 << bit) def update_bit(num, bit, value): mask = ~(1 << bit) return (num & mask) | ((value & 1) << bit) def compress_data(bin_list): """ Compress a list ...
from solution import get_bit, set_bit, clear_bit, update_bit, compress_data, decompress_data def test_compress_decompress(): binary_list = ["101", "011", "110"] compressed = compress_data(binary_list) decompressed = decompress_data(compressed, 3, 3) assert decompressed == binary_list def test_single_b...
[ { "docstring": null, "function_declaration": "def get_bit(num, bit):", "function_name": "get_bit", "parameter_list": "(num, bit)" }, { "docstring": null, "function_declaration": "def set_bit(num, bit):", "function_name": "set_bit", "parameter_list": "(num, bit)" }, { "doc...
[ 0, 0, 0, 1, 0, 0, 0, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def get_bit(num, i):\n \"\"\"\n Get the bit value at position i.\n \"\"\"\n return (num >> i) & 1\n\ndef set_bit(num, i):\n \"\"\"\n Set the...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00049019", "row_id": 49019, "seed_ids": "[212]" }
0.603953
Data_Structure_49019
I
[ "get_bit", "set_bit", "clear_bit", "update_bit", "compress_data", "decompress_data" ]
6
[ [ "compress_data", "clear_bit" ], [ "compress_data", "set_bit" ], [ "decompress_data", "get_bit" ] ]
3
[]
false
[]
false
pytest
true
[]
true
6276087d42385692070c07dbc6b00fa51fa1fb39
97b66077e76a1b44cc80089c3f57bff886e494b0
v1.0
instruct
Data_Structure
Data_Structure_49069_I
You are given two singly linked lists, potentially sharing some nodes. Your task is to find the first common node where the lists intersect, if any. ### Function Signature ```python def find_intersection(head1: Node, head2: Node) -> Node: ``` ### Input * Two heads of linked lists: * `head1` - the head of the first...
class Node: def __init__(self, value): self.value = value self.next = None def get_length(head): length = 0 while head: length += 1 head = head.next return length def find_intersection(head1, head2): """ Returns the first common node in two singly linked lists, ...
import pytest from solution import Node, find_intersection def test_no_intersection(): head1 = Node(1) head1.next = Node(2) head1.next.next = Node(3) head2 = Node(4) head2.next = Node(5) head2.next.next = Node(6) assert find_intersection(head1, head2) is None def test_intersection_at_fir...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\ndef find_intersection(head1: Node, head2: Node) -> Node:\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00049069", "row_id": 49069, "seed_ids": "[245]" }
0.605776
Data_Structure_49069
I
[ "get_length", "find_intersection" ]
2
[ [ "find_intersection", "get_length" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
89e943f48a46851f722adbdfd832a0ae19982bd9
45977178fc1b3791e82846b47bc4d780e46242d7
v1.0
instruct
Data_Structure
Data_Structure_49074_I
## Nearest Neighbor Classifier ### Context You're working on a simple machine learning project and need to implement the Nearest Neighbor algorithm. This algorithm will classify a new data point based on its 'nearest' neighbor in an existing training set of classified points. The problem requires calculating the Eucli...
import math def euclidean_distance(point1, point2): """ Calculate the Euclidean distance between two points. """ return math.sqrt(sum((p1 - p2) ** 2 for p1, p2 in zip(point1, point2))) def nearest_neighbor(x: tuple, tSet: dict) -> any: """ Find the class label of the nearest neighbor to the po...
from solution import nearest_neighbor def test_simple_case(): x = (2.0, 3.0) tSet = { (1.0, 2.0): 'A', (4.0, 6.0): 'B', (2.5, 3.5): 'C' } assert nearest_neighbor(x, tSet) == 'C' def test_case_with_negative_coordinates(): x = (0.0, 0.0) tSet = { (-1.0, -1.0): 'A'...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef nearest_neighbor(x, tSet):\n \"\"\"\n Finds the nearest neighbor to the point x in the training set tSet.\n Args:\n x : tuple \...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049074", "row_id": 49074, "seed_ids": "[260]" }
0.718695
Data_Structure_49074
I
[ "euclidean_distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
15f8ff12dc20ff3b23b409d765f4a7a1fec30b20
626ff31b83e2cdf99b25321b84a28c614732be35
v1.0
instruct
Data_Structure
Data_Structure_49090_I
### Scenario You are building a sorting module for a parallel processing system that often deals with data sizes that are powers of two. The current implementation of bitonic sort needs to be enhanced to ensure it handles a common edge case effectively. ### Task Implement the `bitonic_sort` function to handle an empty...
def bitonic_sort(arr: list, reverse: bool = False) -> list: """ Bitonic sort function to sort an array with size a power of two. """ if len(arr) == 0: return [] if not is_power_of_two(len(arr)): raise ValueError("The length of the input list is not a power of two.") def...
from solution import bitonic_sort, is_power_of_two import pytest def test_bitonic_sort_empty_array(): assert bitonic_sort([]) == [] def test_bitonic_sort_single_element(): assert bitonic_sort([1]) == [1] def test_bitonic_sort_two_elements(): assert bitonic_sort([2, 1]) == [1, 2] def test_bitonic_sort_po...
[ { "docstring": "Bitonic sort function to sort an array with size a power of two.", "function_declaration": "def bitonic_sort(arr, reverse=False):", "function_name": "bitonic_sort", "parameter_list": "(arr, reverse=False)" }, { "docstring": null, "function_declaration": "def is_power_of_t...
[ 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 bitonic_sort(arr: list, reverse: bool = False) -> list:\n if len(arr) == 0:\n return arr\n \n if not (len(arr) > 0 and (len(arr) & (len(ar...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049090", "row_id": 49090, "seed_ids": "[17]" }
0.622052
Data_Structure_49090
I
[ "bitonic_sort", "is_power_of_two" ]
2
[ [ "bitonic_sort", "is_power_of_two" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7a4223178ee36df87dd9c58777949f5a89523bfd
dd69ff67e21a76021dad956931641628e5c81508
v1.0
instruct
Data_Structure
Data_Structure_49095_I
### Question #### Context You are working on a networking tool that needs to display IP addresses in their binary representation format. To achieve this, you must convert IP addresses provided in decimal notation to their corresponding binary format. #### Task Write two functions, `decimal_to_binary_util(val: str) ->...
def decimal_to_binary_util(val): """ Converts an 8-bit decimal number to an 8-bit binary string. """ return format(int(val), '08b') def decimal_to_binary_ip(ip): """ Converts an IP address from dotted-decimal notation to binary format. """ return '.'.join(decimal_to_binary_util(octet) f...
def test_decimal_to_binary_util(): assert decimal_to_binary_util("255") == "11111111" assert decimal_to_binary_util("0") == "00000000" assert decimal_to_binary_util("128") == "10000000" assert decimal_to_binary_util("1") == "00000001" assert decimal_to_binary_util("170") == "10101010" def test_deci...
[ { "docstring": "Converts an 8-bit decimal number to an 8-bit binary string.", "function_declaration": "def decimal_to_binary_util(val):", "function_name": "decimal_to_binary_util", "parameter_list": "(val)" }, { "docstring": "Converts an IP address from dotted-decimal notation to binary form...
[ 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 decimal_to_binary_util(val: str) -> str:\n \"\"\"\n Converts an 8-bit decimal number (integer value from 0 to 255) \n to an 8-bit binary string.\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049095", "row_id": 49095, "seed_ids": "[152]" }
0.613831
Data_Structure_49095
I
[ "decimal_to_binary_util", "decimal_to_binary_ip" ]
2
[ [ "decimal_to_binary_ip", "decimal_to_binary_util" ] ]
1
[]
false
[]
false
pytest
false
[]
true
4bc38eea3568383e7880aec1c4dcab9a89e0d681
bf764971915121179231bbe32e176bd2e439750a
v1.0
instruct
Data_Structure
Data_Structure_49116_I
You have been provided with an implementation of Heap Sort using both Max Heap and Min Heap. Your task is to implement a function that decides dynamically which heap sort to use based on a given configuration, and then sorts the array in ascending order. ### Function Signature ```python def dynamic_heap_sort(arr: Lis...
from typing import List def max_heapify(arr: List[int], n: int, i: int, simulate: bool): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: largest = right if largest != i...
from solution import dynamic_heap_sort def test_dynamic_heap_sort_max_heap(): arr = [4, 10, 3, 5, 1] sorted_arr = dynamic_heap_sort(arr, use_max_heap=True) assert sorted_arr == [1, 3, 4, 5, 10] def test_dynamic_heap_sort_min_heap(): arr = [4, 10, 3, 5, 1] sorted_arr = dynamic_heap_sort(arr, use_ma...
[ { "docstring": null, "function_declaration": "def max_heapify(arr, n, i, simulate):", "function_name": "max_heapify", "parameter_list": "(arr, n, i, simulate)" }, { "docstring": null, "function_declaration": "def heap_sort_max(arr, simulate):", "function_name": "heap_sort_max", "...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef dynamic_heap_sort(arr: List[int], use_max_heap: bool, simulation: bool = False) -> List[int]:\n n = len(arr)\n \n def ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00049116", "row_id": 49116, "seed_ids": "[8]" }
0.672081
Data_Structure_49116
I
[ "max_heapify", "heap_sort_max", "min_heapify", "heap_sort_min", "dynamic_heap_sort" ]
5
[ [ "dynamic_heap_sort", "heap_sort_max" ], [ "dynamic_heap_sort", "heap_sort_min" ], [ "heap_sort_max", "max_heapify" ], [ "heap_sort_min", "min_heapify" ] ]
4
[]
false
[]
false
pytest
true
[]
true
bd4bbde278b82e5d033fff34ddbc9bfc0e9810ca
ee788880d8e30b95b671e2eacc0ce5a8ec81e434
v1.0
instruct
Data_Structure
Data_Structure_49125_I
You are provided with a list of integers representing frequencies of occurrences of various events. Your task is to efficiently handle queries related to the sum of frequencies up to a specific index and also update the frequency of an event at a specific index. You will implement a Fenwick Tree (Binary Indexed Tree) t...
def update(bit_tree, idx, val): """ Updates the Fenwick Tree at given index by adding val to it. Fenwick Tree indices are 1-based, so we need to adjust the given index. """ idx += 1 # Convert to 1-based index while idx < len(bit_tree): bit_tree[idx] += val idx += idx & -idx def...
from solution import update, query, construct def test_construct(): frequencies = [3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3] bit_tree = construct(frequencies) expected_bit_tree = [0, 3, 5, -1, 10, 5, 9, -3, 19, 7, 9, 3] # Only testing some elements to ensure correctness assert bit_tree[:6] == expected_bit...
[ { "docstring": "Updates the Fenwick Tree at given index by adding val to it.\nFenwick Tree indices are 1-based, so we need to adjust the given index.", "function_declaration": "def update(bit_tree, idx, val):", "function_name": "update", "parameter_list": "(bit_tree, idx, val)" }, { "docstri...
[ 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 update(bit_tree, idx, val):\n \"\"\"\n Updates the Fenwick Tree at given index by adding val to it.\n Fenwick Tree indices are 1-based, so we nee...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00049125", "row_id": 49125, "seed_ids": "[305]" }
0.577133
Data_Structure_49125
I
[ "update", "query", "construct" ]
3
[ [ "construct", "update" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fb27929d0aa0ed4ec8cb1803155972af194f3ab6
f5d4b4ad82fc49b0f39a6329ef731693225dc4a5
v1.0
instruct
Data_Structure
Data_Structure_49234_I
### Maximum Flow Implementation **Context**: As part of a network design team, your task is to optimize the data transfer rate from the central server (source) to the client nodes (sinks) across a designed network. Understanding the maximum capacity achievable in given constraints of your network is crucial. **Objec...
from collections import deque def bfs(rGraph, source, sink, parent): """ Returns true if there is a path from source to sink in residual graph. Also fills parent[] to store the path """ visited = [False] * len(rGraph) queue = deque([source]) visited[source] = True while queue: u = ...
import pytest from solution import maximum_flow def test_example_1(): 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, 0, 5) == 23 def test_sin...
[ { "docstring": "Returns true if there is a path from source to sink in residual graph.\nAlso fills parent[] to store the path ", "function_declaration": "def bfs(rGraph, source, sink, parent):", "function_name": "bfs", "parameter_list": "(rGraph, source, sink, parent)" }, { "docstring": null...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef bfs(rGraph, s, t, parent):\n visited = [False] * len(rGraph)\n queue = deque([s])\n visited[s] = True\n \n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049234", "row_id": 49234, "seed_ids": "[240]" }
0.537845
Data_Structure_49234
I
[ "bfs", "maximum_flow" ]
2
[ [ "maximum_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
62c49a12fb287dc0d7b41df24dbd3aad5c39e96a
a0664ef1fe677a163ab95cbb839ecf76bdc35e4b
v1.0
instruct
Data_Structure
Data_Structure_49267_I
### Context You are given an array that you need to rotate to the right by `k` steps. The need for such rotations is common in algorithm design, where rearrangements optimize search or organization processes. ### Task Implement a function `optimized_rotate_array` which encapsulates the most efficient method to rotate ...
def optimized_rotate_array(array, k): """ Rotates the array 'k' times to the right. :param array: List[int] - List of integers that need to be rotated :param k: int - Number of steps to rotate the array :return: List[int] - Rotated array """ n = len(array) if n == 0: return arra...
from solution import optimized_rotate_array def test_rotate_normal_case(): assert optimized_rotate_array([1, 2, 3, 4, 5, 6, 7], 3) == [5, 6, 7, 1, 2, 3, 4] def test_rotate_with_zero_k(): assert optimized_rotate_array([1, 2, 3, 4, 5], 0) == [1, 2, 3, 4, 5] def test_rotate_with_large_k(): assert optimized_...
[ { "docstring": "Rotates the array 'k' times to the right.\n\n:param array: List[int] - List of integers that need to be rotated\n:param k: int - Number of steps to rotate the array\n:return: List[int] - Rotated array", "function_declaration": "def optimized_rotate_array(array, k):", "function_name": "op...
[ 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 optimized_rotate_array(array, k):\n \"\"\"\n Rotates the array 'k' times to the right.\n\n :param array: List[int] - List of integers that need t...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049267", "row_id": 49267, "seed_ids": "[283]" }
0.605821
Data_Structure_49267
I
[ "optimized_rotate_array", "reverse" ]
2
[ [ "optimized_rotate_array", "reverse" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3a85d6d315fb9fcb134da5e4e7e86dfe713bbbfb
52ecf9ec4f246f3a3c7b8a508e2a36064cc9dee3
v1.0
instruct
Data_Structure
Data_Structure_49280_I
### Question: Radix Sort Implementation You are tasked with implementing the `radix_sort` function that efficiently sorts a list of non-negative integers using the Radix Sort algorithm. This algorithm should handle the digits of numbers from the least significant to the most significant. **Function Signature:** ```pyt...
from typing import List def counting_sort(arr: List[int], exp: int, simulation: bool) -> List[int]: n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = (arr[i] // exp) % 10 count[index] += 1 for i in range(1, 10): count[i] += count[i - 1] i ...
from solution import radix_sort def test_radix_sort_example(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_single_element(): assert radix_sort([5]) == [5] def test_radix_sort_empty_list(): assert radix_sort([]) == [] def test_radix_sort_i...
[ { "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, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # St...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049280", "row_id": 49280, "seed_ids": "[15]" }
0.557245
Data_Structure_49280
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
83a69a25be85aa1fea2d2f973600bdd8e4ffaef0
4f099a5e10ddaf10e9ad6acb2ec34390a34e39a0
v1.0
instruct
Data_Structure
Data_Structure_49288_I
### Bogo Sort Simulation with Additional Constraints **Scenario**: You have encountered a whimsical sorting algorithm called Bogo Sort. However, in this magical land, it is used in a unique context at a magical marketplace lottery system where occasionally items are picked in a rush, causing chaos. The items need to b...
import random from typing import List, Tuple 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 shuffle(arr: List[int]) -> List[int]: """ Help...
from solution import constrained_bogo_sort def test_bogo_sort_sorted_array(): arr = [1, 2, 3, 4, 5] sorted_arr, iterations = constrained_bogo_sort(arr, 10) assert sorted_arr == [1, 2, 3, 4, 5] assert iterations == 0 def test_bogo_sort_reverse_sorted_array(): arr = [5, 4, 3, 2, 1] sorted_arr, i...
[ { "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 shuffle the array randomly.", "function_declaration": "def shuffle(arr):", "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List, Tuple\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"Check if the list is sorted.\"\"\"\n return all(arr[i] <...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049288", "row_id": 49288, "seed_ids": "[16]" }
0.539015
Data_Structure_49288
I
[ "is_sorted", "shuffle", "constrained_bogo_sort" ]
3
[ [ "constrained_bogo_sort", "is_sorted" ], [ "constrained_bogo_sort", "shuffle" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a46e3e3e8148c5e81eabf3f307d023f503b41398
4c558c414f8856604c2995889094dd02c6bb2d12
v1.0
instruct
Data_Structure
Data_Structure_49304_I
<|Analysis Begin|> ### Core Identification * **Algorithm/Data Structure**: The given code constructs "word squares" using a backtracking search algorithm. * **Complexity**: - **Time Complexity**: Worst-case time complexity is O(N * 26^L), where N is the number of words, and L is the length of each word. - **Space ...
from typing import List, Dict, Tuple, Set def build_prefix_map(words: List[str]) -> Dict[str, List[str]]: prefix_map = {} for word in words: for i in range(len(word)): prefix = word[:i+1] if prefix not in prefix_map: prefix_map[prefix] = [] prefix_map...
from solution import find_word_squares def test_find_word_squares_multiple_squares(): words = ["area", "lead", "wall", "lady", "ball"] result = find_word_squares(words) expected_output = [ ["wall", "area", "lead", "lady"], ["ball", "area", "lead", "lady"] ] assert sorted(result) == ...
[ { "docstring": null, "function_declaration": "def build_prefix_map(words):", "function_name": "build_prefix_map", "parameter_list": "(words)" }, { "docstring": null, "function_declaration": "def backtrack(step, word_len, word_square, results, prefix_map):", "function_name": "backtrac...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nfrom collections import defaultdict\n\ndef find_word_squares(words: List[str]) -> List[List[str]]:\n def build_prefix_dict(words):...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049304", "row_id": 49304, "seed_ids": "[87]" }
0.528528
Data_Structure_49304
I
[ "build_prefix_map", "backtrack", "find_word_squares" ]
3
[ [ "find_word_squares", "backtrack" ], [ "find_word_squares", "build_prefix_map" ] ]
2
[]
false
[]
false
pytest
true
[]
true
311086eb4b28ab8a2c903b8c5be24e316917f809
5f34667f405b689919c48c59cb5d0651b92eafe9
v1.0
instruct
Data_Structure
Data_Structure_49318_I
You are given an implementation of a Markov Chain that can iterate through states based on given transition probabilities. Your task is to extend this functionality by creating a function that simulates a Markov Chain for a specified number of steps and collects the states visited in a path. ### Function Signature ``...
import random def __choose_state(probabilities): """ Helper function to choose a state based on given probabilities. """ random_value = random.random() cumulative = 0.0 for state, probability in probabilities.items(): cumulative += probability if random_value < cumulative: ...
import pytest from solution import simulate_markov_chain def test_simulate_markov_chain_single_step(): chain = { 'A': {'A': 0.6, 'B': 0.4}, 'B': {'A': 0.3, 'B': 0.7} } initial_state = 'A' steps = 1 path = simulate_markov_chain(chain, initial_state, steps) assert len(path) =...
[ { "docstring": "Helper function to choose a state based on given probabilities.", "function_declaration": "def __choose_state(probabilities):", "function_name": "__choose_state", "parameter_list": "(probabilities)" }, { "docstring": "Simulate a Markov chain for a specified number of steps.\n...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef simulate_markov_chain(chain: dict, initial_state: str, steps: int) -> list:\n def choose_state(current_state):\n next_states = ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049318", "row_id": 49318, "seed_ids": "[232]" }
0.520941
Data_Structure_49318
I
[ "__choose_state", "simulate_markov_chain" ]
2
[ [ "simulate_markov_chain", "__choose_state" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4ed666a738000c5c19c4d7f8b15aa4b9476ea326
4a0a2c0a96b17247660432ec681db589eff3d009
v1.0
instruct
Data_Structure
Data_Structure_49431_I
You have been hired to enhance the security protocol of a messaging service by implementing a robust encryption system. Your task is to implement functions to generate RSA keys and use them for encrypting and decrypting messages. RSA (Rivest-Shamir-Adleman) is an asymmetric cryptographic algorithm that relies on gener...
import random from sympy import isprime, mod_inverse, gcd def generate_prime_candidate(length): """Generate an odd integer randomly.""" p = random.getrandbits(length) # apply a mask to set MSB and LSB to 1 p |= (1 << length - 1) | 1 return p def generate_prime_number(length=1024): """Generate ...
from solution import generate_key, encrypt, decrypt def test_generate_key(): n, e, d = generate_key(16) assert isinstance(n, int) assert isinstance(e, int) assert isinstance(d, int) # Ensure n is 16 bits length roughly (2^15 <= n < 2^16) assert 2**15 <= n < 2**16 # Ensure e and d are positi...
[ { "docstring": "Generate an odd integer randomly.", "function_declaration": "def generate_prime_candidate(length):", "function_name": "generate_prime_candidate", "parameter_list": "(length)" }, { "docstring": "Generate a prime number of specified bit length.", "function_declaration": "de...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, randprime, mod_inverse, gcd\n\ndef generate_key(k):\n \"\"\"\n Generate RSA keys.\n :param k: Number of bit...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049431", "row_id": 49431, "seed_ids": "[154]" }
0.60086
Data_Structure_49431
I
[ "generate_prime_candidate", "generate_prime_number", "generate_key", "encrypt", "decrypt" ]
5
[ [ "generate_key", "generate_prime_number" ], [ "generate_prime_number", "generate_prime_candidate" ] ]
2
[]
false
[]
false
pytest
true
[ "sympy" ]
false
bbef6de00bb1115067b1aee634c162bec2239e7f
5a72840c2b30629dd9b7e8b3b7e4b81d16d6ecfa
v1.0
instruct
Data_Structure
Data_Structure_49467_I
### Question: Implement the Function to Sort an Array Using Iterative Quick Sort #### Context: You are tasked with implementing a more efficient sorting algorithm to handle larger datasets more efficiently than Exchange Sort. Quick Sort offers better average-case performance with O(n log n) time complexity. Given the ...
def iterative_quick_sort(arr): """ Sorts the array using the iterative version of Quick Sort. """ if len(arr) == 0: return arr stack = [(0, len(arr) - 1)] while stack: low, high = stack.pop() if low < high: pivot_index = partition(arr, low, high) ...
from solution import iterative_quick_sort def test_iterative_quick_sort_empty(): assert iterative_quick_sort([]) == [] def test_iterative_quick_sort_single_element(): assert iterative_quick_sort([1]) == [1] def test_iterative_quick_sort_sorted(): assert iterative_quick_sort([1, 2, 3, 4, 5]) == [1, 2,...
[ { "docstring": "Sorts the array using the iterative version of Quick Sort.", "function_declaration": "def iterative_quick_sort(arr):", "function_name": "iterative_quick_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def partition(arr, low, high):", ...
[ 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 iterative_quick_sort(arr):\n \"\"\"\n Sorts a list using an iterative implementation of the quicksort algorithm.\n \"\"\"\n if len(arr) < 2:\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049467", "row_id": 49467, "seed_ids": "[28]" }
0.555038
Data_Structure_49467
I
[ "iterative_quick_sort", "partition" ]
2
[ [ "iterative_quick_sort", "partition" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d80866a0a2d1b15d510881ecd77847b987a73f87
6ec9ef05958384babd2f1456342bd6f3dabeccb6
v1.0
instruct
Data_Structure
Data_Structure_49561_I
### Question: Determining Safe Prime Numbers and Their Primitive Roots #### Problem Statement A prime number `p` is called a **safe prime** if `(p-1)/2` is also a prime number. Safe primes are notable in cryptography for their resistance to certain attacks. Your task is to write a function that determines whether a g...
from typing import List, Union import math def is_prime(n: int) -> bool: if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 re...
from solution import is_safe_prime_with_primitive_roots def test_prime_is_safe(): assert is_safe_prime_with_primitive_roots(7) == [3, 5] assert is_safe_prime_with_primitive_roots(11) == [2, 6, 7, 8] assert is_safe_prime_with_primitive_roots(23) == [5, 7, 10, 11, 14, 15, 17, 19, 20, 21] def test_prime_not_...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def is_safe_prime_with_primitive_roots(p):", "function_name": "is_safe_prime_with_primitive_roots", "parameter_li...
[ 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, Union\n\ndef is_safe_prime_with_primitive_roots(p: int) -> Union[List[int], str]:\n def is_prime(n):\n \"\"\"Helper functio...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00049561", "row_id": 49561, "seed_ids": "[160]" }
0.613954
Data_Structure_49561
I
[ "is_prime", "is_safe_prime_with_primitive_roots" ]
2
[ [ "is_safe_prime_with_primitive_roots", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
23af3aaa2746576fe27c6eb8e3398c73dda7caee
44362e88bc50236f49e283d4b1abce00e44cab2e
v1.0
instruct
Data_Structure
Data_Structure_49586_I
You are given a task to implement a function that inverts an n x n matrix if possible. Your function needs to handle matrices of arbitrary size (greater than 1x1) and provide correct results for matrices that are invertible. In case a matrix is non-invertible or invalid, your function should handle these cases graceful...
from typing import List def determinant(matrix: List[List[float]]) -> float: if len(matrix) == 1: return matrix[0][0] if len(matrix) == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] det = 0 for c in range(len(matrix)): submatrix = [row[:c] + row[c + 1:] for...
from solution import invert_matrix def test_invert_matrix_valid_2x2(): matrix = [ [4, 7], [2, 6] ] expected = [ [0.6, -0.7], [-0.2, 0.4] ] result = invert_matrix(matrix) for a, b in zip(result, expected): assert all(round(a_i, 1) == round(b_i, 1) for a_i,...
[ { "docstring": null, "function_declaration": "def determinant(matrix):", "function_name": "determinant", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def get_matrix_minor(matrix, i, j):", "function_name": "get_matrix_minor", "parameter_list": "(ma...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef invert_matrix(matrix: List[List[float]]) -> List[List[float]]:\n if not isinstance(matrix, list) or not all(isinstance(row, ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049586", "row_id": 49586, "seed_ids": "[347]" }
0.59568
Data_Structure_49586
I
[ "determinant", "get_matrix_minor", "invert_matrix" ]
3
[ [ "invert_matrix", "determinant" ], [ "invert_matrix", "get_matrix_minor" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e0cc0fc38d0e7ae5f3ed7d368cd89416ff02c01b
43084200ec54b24ef4e21659e17dbde852e1a3bc
v1.0
instruct
Data_Structure
Data_Structure_49592_I
You are part of a development team creating a basic machine learning library. You need to implement a core classification feature using the Nearest Neighbor algorithm. Your task is to write a function to classify an input vector based on the closest vectors in a given training set. ### Function Signature ```python def...
from typing import Tuple, Dict, Any import math def calculate_distance(v1: Tuple[int, ...], v2: Tuple[int, ...]) -> float: """ Calculates the Euclidean distance between two vectors. """ return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2))) def classify_vector(input_vector: Tuple[int, ...], train...
from solution import classify_vector def test_classify_vector_single_element(): training_set = { (1,): 'A', (2,): 'B', (3,): 'C' } input_vector = (2,) assert classify_vector(input_vector, training_set) == 'B' def test_classify_vector_two_elements(): training_set = { ...
[ { "docstring": "Calculates the Euclidean distance between two vectors.", "function_declaration": "def calculate_distance(v1, v2):", "function_name": "calculate_distance", "parameter_list": "(v1, v2)" }, { "docstring": "Classifies the input vector based on the nearest neighbor principle.\n\nP...
[ 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 Tuple, Dict, Any\nimport math\n\ndef classify_vector(input_vector: Tuple[int, ...], training_set: Dict[Tuple[int, ...], Any]) -> Any:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049592", "row_id": 49592, "seed_ids": "[260]" }
0.590345
Data_Structure_49592
I
[ "calculate_distance", "classify_vector" ]
2
[ [ "classify_vector", "calculate_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7ca3a4576709bfc319d8e47f5835283f45e759b3
a341309c7773140fde4987d78d5e1131c2ea21f4
v1.0
instruct
Data_Structure
Data_Structure_49598_I
### RSA Encryption Algorithm Implementation and Performance Verification As part of understanding the RSA encryption algorithm and its efficiency, you need to extend the current RSA implementation to include: 1. Verification of prime generation speed using probabilistic methods. 2. An optimized method for calculating ...
import random import time def miller_rabin_test(n, k): """ Perform the Miller-Rabin primality test. """ if n == 2 or n == 3: return True if n <= 1 or n % 2 == 0: return False r, s = 0, n - 1 while s % 2 == 0: r += 1 s //= 2 for _ in range(k): a = random.r...
from solution import gen_prime_optimized, modinv_optimized, analyze_performance def test_gen_prime_optimized(): # Testing prime generation with 16 bits prime = gen_prime_optimized(16, seed=123) assert isinstance(prime, int), "Prime number generation failed" assert len(bin(prime)) == 18, "Generated prim...
[ { "docstring": "Perform the Miller-Rabin primality test. ", "function_declaration": "def miller_rabin_test(n, k):", "function_name": "miller_rabin_test", "parameter_list": "(n, k)" }, { "docstring": "Generate a k-bit prime number using a probabilistic method. ", "function_declaration": "...
[ 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\nimport time\n\ndef miller_rabin_test(n, k):\n \"\"\" Perform the Miller-Rabin primality test. \"\"\"\n if n == 2 or n == 3:\n retu...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00049598", "row_id": 49598, "seed_ids": "[154]" }
0.49992
Data_Structure_49598
I
[ "miller_rabin_test", "gen_prime_optimized", "extended_euclidean_algorithm", "modinv_optimized", "rsa_key_generation", "analyze_performance" ]
6
[ [ "analyze_performance", "rsa_key_generation" ], [ "gen_prime_optimized", "miller_rabin_test" ], [ "modinv_optimized", "extended_euclidean_algorithm" ], [ "rsa_key_generation", "gen_prime_optimized" ], [ "rsa_key_generation", "modinv_optimized" ] ]
5
[]
false
[]
false
pytest
true
[]
true
8bfd9808d28f3aacabccee02dbb08e757b6c9a27
6054767cec2b9b293787e6d0345a7b9ac651dad4
v1.0
instruct
Data_Structure
Data_Structure_49669_I
## Problem Description You are given a universe of elements \( U \) and a collection of subsets that together cover all elements of \( U \). Each subset has an associated cost. Your task is to write a function that finds a subcollection of subsets whose union is \( U \), such that the total cost is minimized. You shou...
from itertools import combinations def optimal_set_cover(universe, subsets, costs): subset_list = list(subsets.keys()) N = len(subset_list) optimal_solution = None optimal_cost = float('inf') for r in range(1, N + 1): for combo in combinations(subset_list, r): union_set = set()...
import pytest from solution import set_cover def test_set_cover_example(): universe = {1, 2, 3, 4, 5} subsets = {'S1': {4, 1, 3}, 'S2': {2, 5}, 'S3': {1, 4, 3, 2}} costs = {'S1': 5, 'S2': 10, 'S3': 3} optimal, greedy = set_cover(universe, subsets, costs) assert sorted(optimal) == sorted([...
[ { "docstring": null, "function_declaration": "def optimal_set_cover(universe, subsets, costs):", "function_name": "optimal_set_cover", "parameter_list": "(universe, subsets, costs)" }, { "docstring": null, "function_declaration": "def greedy_set_cover(universe, subsets, costs):", "fu...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from itertools import chain, combinations\n\ndef set_cover(universe, subsets, costs):\n def optimal_set_cover(universe, subsets, costs):\n # Generat...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00049669", "row_id": 49669, "seed_ids": "[130]" }
0.577992
Data_Structure_49669
I
[ "optimal_set_cover", "greedy_set_cover", "set_cover" ]
3
[ [ "set_cover", "greedy_set_cover" ], [ "set_cover", "optimal_set_cover" ] ]
2
[]
false
[]
false
pytest
true
[]
true
eb0c84a5a6d4b1163585fd6025fcc2dcaa0fb81c
f0e90382d6063b85a5a994269172aae3f634eedb
v1.0
instruct
Data_Structure
Data_Structure_49698_I
#### Problem Description You are given two non-negative integers, `a` and `b`. Your task is to write a function that calculates their greatest common divisor (GCD), least common multiple (LCM), and the number of trailing zeros in each integer. #### Requirements: 1. **Function 1: Greatest Common Divisor** - **Functi...
def compute_gcd(a, b): """ Returns the greatest common divisor (GCD) of a and b using Euclidean algorithm. """ while b: a, b = b, a % b return a def compute_lcm(a, b): """ Returns the least common multiple (LCM) of a and b. LCM is computed using the formula: LCM(a, b) = abs(a*b)...
from solution import compute_gcd, compute_lcm, count_trailing_zeros def test_compute_gcd(): assert compute_gcd(48, 18) == 6 assert compute_gcd(0, 10) == 10 assert compute_gcd(25, 0) == 25 assert compute_gcd(17, 13) == 1 # co-primes assert compute_gcd(101, 103) == 1 # co-primes assert compute_...
[ { "docstring": "Returns the greatest common divisor (GCD) of a and b using Euclidean algorithm.", "function_declaration": "def compute_gcd(a, b):", "function_name": "compute_gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the least common multiple (LCM) of a and b.\nLCM is comput...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def compute_gcd(a, b):\n \"\"\"\n Returns the greatest common divisor of a and b.\n \"\"\"\n while b:\n a, b = b, a % b\n return a\n\nde...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049698", "row_id": 49698, "seed_ids": "[166]" }
0.606533
Data_Structure_49698
I
[ "compute_gcd", "compute_lcm", "count_trailing_zeros" ]
3
[ [ "compute_lcm", "compute_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c32dff44dae252c191f3d323a4184b08d0c88455
3b0bf6ee153802b8f1e446435cf308b0a17656d7
v1.0
instruct
Data_Structure
Data_Structure_49770_I
### Prime Digit Sum **Scenario**: Imagine you're designing a system that filters out certain numbers based on their mathematical properties. One specific feature is to detect numbers whose digit sum is a prime number. This is useful in contexts like cryptography, random number generation, or special number sequences. ...
def prime_check(n: int) -> bool: """Returns True if n is a prime number, False otherwise.""" 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 Fals...
from solution import is_prime_digit_sum def test_prime_digit_sum_for_prime_digit_sum(): assert is_prime_digit_sum(58) == True # 5 + 8 = 13 -> True assert is_prime_digit_sum(29) == True # 2 + 9 = 11 -> True assert is_prime_digit_sum(23) == True # 2 + 3 = 5 -> True def test_non_prime_digit_sum(): ass...
[ { "docstring": "Returns True if n is a prime number, False otherwise.", "function_declaration": "def prime_check(n):", "function_name": "prime_check", "parameter_list": "(n)" }, { "docstring": "Returns True if the sum of the digits of n is a prime number, False otherwise.", "function_dec...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime_digit_sum(n: int) -> bool:\n def prime_check(x: int) -> bool:\n if x < 2:\n return False\n for i in range(2, int(x **...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00049770", "row_id": 49770, "seed_ids": "[143]" }
0.727851
Data_Structure_49770
I
[ "prime_check", "is_prime_digit_sum" ]
2
[ [ "is_prime_digit_sum", "prime_check" ] ]
1
[]
false
[]
false
pytest
true
[]
true
523994069d732d6461a3081af277c2bc09a9a9eb
bfe633e8ba64b5a334fcc925d0361e8a8d8d20a7
v1.0
instruct
Data_Structure
Data_Structure_49811_I
### Objective: Implement the heap sort algorithm for an array of integers. Your implementation should allow sorting in both ascending and descending order. Create functions for both max-heap sort and min-heap sort. Your solutions should be efficient with a time complexity of O(n log n) and should sort in-place. ### Fu...
from typing import List def max_heapify(arr: List[int], n: int, i: int): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: largest = right if largest != i: ...
from solution import max_heap_sort, min_heap_sort def test_max_heap_sort(): assert max_heap_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] assert max_heap_sort([5, 7, 3, 1, 2, 8, 6, 4]) == [1, 2, 3, 4, 5, 6, 7, 8] assert max_heap_sort([1]) == [1] assert max_heap_sort([]) =...
[ { "docstring": null, "function_declaration": "def max_heapify(arr, n, i):", "function_name": "max_heapify", "parameter_list": "(arr, n, i)" }, { "docstring": null, "function_declaration": "def min_heapify(arr, n, i):", "function_name": "min_heapify", "parameter_list": "(arr, n, i...
[ 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 max_heapify(arr: List[int], n: int, i: int):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n \n if left <...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00049811", "row_id": 49811, "seed_ids": "[8]" }
0.703607
Data_Structure_49811
I
[ "max_heapify", "min_heapify", "max_heap_sort", "min_heap_sort" ]
4
[ [ "max_heap_sort", "max_heapify" ], [ "min_heap_sort", "min_heapify" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b7e528be71966f7e7e01514b2dde4ba73c398ae8
6acf14e23babbf76de155607f51a1be23af0afb1
v1.0
instruct
Data_Structure
Data_Structure_49814_I
### Polynomial Manipulation Challenge You are given a Monomial and Polynomial class that can perform various arithmetic operations such as addition, subtraction, multiplication, and division. Your task is to implement a function `simplify_polynomial` which takes a polynomial represented as a list of coefficient-varia...
from fractions import Fraction def format_monomial(monomial): """ Returns a string representation of a single monomial. """ parts = [] coeff = monomial["coeff"] if isinstance(coeff, Fraction): coeff_str = f'{coeff}' elif isinstance(coeff, float): if coeff.is_integer(): ...
from solution import simplify_polynomial from fractions import Fraction def test_simplify_polynomial_basic(): monomials = [ {"variables": {1: 1}, "coeff": 2}, {"variables": {2: 3, 1: -1}, "coeff": -1}, {"variables": {}, "coeff": 3.14}, {"variables": {}, "coeff": Fraction(-1, 4)} ...
[ { "docstring": "Returns a string representation of a single monomial.", "function_declaration": "def format_monomial(monomial):", "function_name": "format_monomial", "parameter_list": "(monomial)" }, { "docstring": "Simplifies the given polynomial and returns a string representation.", "...
[ 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 fractions import Fraction\n\ndef monomial_to_string(variables, coeff):\n if isinstance(coeff, Fraction):\n coeff_str = f\"{coeff.numerator}/{co...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00049814", "row_id": 49814, "seed_ids": "[157]" }
0.560817
Data_Structure_49814
I
[ "format_monomial", "simplify_polynomial" ]
2
[ [ "simplify_polynomial", "format_monomial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6dcb4321908b1415b91b6c4da2feaf383e2c32f5
28f59e61ef37c2358fcdbd1cac87328526275d7b
v1.0
instruct
Data_Structure
Data_Structure_49843_I
### Question: Implement an Enhanced Bucket Sort with Median Selection #### Description You have been given the task to implement an enhanced version of bucket sort. This version will improve upon the basic bucket sort by dynamically determining the bucket size and using a quicksort implementation instead of insertion ...
from typing import List def quicksort(arr: List[int]) -> List[int]: if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(righ...
from solution import enhanced_bucket_sort def test_example_case(): assert enhanced_bucket_sort([4, 2, 7, 1, 3, 2]) == [1, 2, 2, 3, 4, 7] def test_all_elements_same(): assert enhanced_bucket_sort([5, 5, 5, 5]) == [5, 5, 5, 5] def test_already_sorted(): assert enhanced_bucket_sort([1, 2, 3, 4, 5]) == [1, 2...
[ { "docstring": null, "function_declaration": "def quicksort(arr):", "function_name": "quicksort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def median_of_medians(arr, k):", "function_name": "median_of_medians", "parameter_list": "(arr, k)" }, ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef quicksort(arr):\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < p...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049843", "row_id": 49843, "seed_ids": "[26]" }
0.60855
Data_Structure_49843
I
[ "quicksort", "median_of_medians", "enhanced_bucket_sort" ]
3
[ [ "enhanced_bucket_sort", "median_of_medians" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a45c2bb409d5e9c49ad285c2f7315040a1330c82
903eeb92029facf2319348c3c11417086484187b
v1.0
instruct
Data_Structure
Data_Structure_49844_I
Least Common Multiple Finder #### Objective Write a Python function `find_lcm_multiple(numbers: List[int]) -> int` that computes the least common multiple (LCM) of a list of integers. This function should internally use the GCD algorithm implemented with bitwise operations for optimal performance. #### Input * `numbe...
from typing import List from functools import reduce def gcd_bit(a: int, b: int) -> int: if a == 0: return b if b == 0: return a # Finding common factors of 2 shift = 0 while ((a | b) & 1) == 0: a >>= 1 b >>= 1 shift += 1 while (a & 1) == 0: a >>=...
from solution import find_lcm_multiple def test_find_lcm_multiple_simple(): assert find_lcm_multiple([4, 6]) == 12 def test_find_lcm_multiple_three_numbers(): assert find_lcm_multiple([12, 15, 20]) == 60 def test_find_lcm_multiple_large_numbers(): assert find_lcm_multiple([1000000000, 999999999]) == 9999...
[ { "docstring": null, "function_declaration": "def gcd_bit(a, b):", "function_name": "gcd_bit", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": null, "func...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nfrom functools import reduce\n\ndef gcd_bit(a: int, b: int) -> int:\n if a == 0:\n return b\n if b == 0:\n return...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00049844", "row_id": 49844, "seed_ids": "[166]" }
0.675003
Data_Structure_49844
I
[ "gcd_bit", "lcm", "find_lcm_multiple" ]
3
[ [ "find_lcm_multiple", "lcm" ], [ "lcm", "gcd_bit" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e1b0e71ff99e2d3cea6c3797db0908916e6c78df
cbfa444dd4edfdc6c401b396898fad986347811a
v1.0
instruct
Data_Structure
Data_Structure_49865_I
#### Context: You are tasked with developing a feature for a text editor that highlights all occurrences of a given search word in the editor's content. To efficiently find and highlight the search word, you decide to use the Knuth-Morris-Pratt (KMP) algorithm. #### Problem: Implement the `highlight_occurrences` funct...
from typing import List def build_lps(pattern: str) -> List[int]: """ Builds the longest prefix which is also suffix (lps) array for the KMP algorithm. """ length = 0 lps = [0] * len(pattern) i = 1 while i < len(pattern): if pattern[i] == pattern[length]: length += ...
from solution import highlight_occurrences def test_highlight_occurrences_basic(): assert highlight_occurrences("hello there hero!", "he") == [0, 7, 12] assert highlight_occurrences("aabcaabxaaaz", "aab") == [0, 4] assert highlight_occurrences("mississippi", "iss") == [1, 4] def test_highlight_occurrences...
[ { "docstring": "Builds the longest prefix which is also suffix (lps) array for the KMP algorithm.", "function_declaration": "def build_lps(pattern):", "function_name": "build_lps", "parameter_list": "(pattern)" }, { "docstring": "Returns the starting indices of all occurrences of the pattern...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef compute_lps(pattern: str) -> List[int]:\n lps = [0] * len(pattern)\n length = 0\n i = 1\n while i < len(pattern):\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049865", "row_id": 49865, "seed_ids": "[93]" }
0.535496
Data_Structure_49865
I
[ "build_lps", "highlight_occurrences" ]
2
[ [ "highlight_occurrences", "build_lps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b5c690dc4fa21171103f3e2af25e6b7954a01a9d
17b69a55afab95251d0f5c285ed1f8bfe3bffbdf
v1.0
instruct
Data_Structure
Data_Structure_49884_I
### Scenario Alice and Bob want to communicate securely over an insecure network. To achieve this, they decide to use the Diffie-Hellman key exchange algorithm to generate a shared secret key. ### Objective Write a function `secure_communication(a: int, p: int) -> str` that: 1. Verifies if \( p \) is a prime numbe...
import random def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def power(x, y, p): res = 1...
def test_prime_check(): assert is_prime(23) == True assert is_prime(24) == False assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False def test_primitive_root_finding(): assert find_primitive_root(23) == 5 assert find_primitive_root(29) == 2 assert find_primi...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def power(x, y, p):", "function_name": "power", "parameter_list": "(x, y, p)" }, { "docstring": null, ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00049884", "row_id": 49884, "seed_ids": "[146]" }
0.512239
Data_Structure_49884
I
[ "is_prime", "power", "find_primitive_root", "diffie_hellman_key_exchange", "secure_communication" ]
5
[ [ "diffie_hellman_key_exchange", "power" ], [ "find_primitive_root", "power" ], [ "secure_communication", "diffie_hellman_key_exchange" ], [ "secure_communication", "find_primitive_root" ], [ "secure_communication", "is_prime" ] ]
5
[]
false
[]
false
pytest
false
[]
true
79be1a771d653886fd84745aff024dd5553f0f81
3679f3356f515d9548f9cf76f428be4a8fd53e3f
v1.0
instruct
Data_Structure
Data_Structure_49897_I
### Closest Points to Origin #### Scenario You are working on a GPS-based application that frequently needs to find the k closest POIs (Points of Interest) to the user's current location, referred to as the origin. Given this requirement, your task is to write a function that efficiently determines these k closest po...
import heapq from typing import List, Tuple def squared_euclidean_distance(point: Tuple[int, int], origin: Tuple[int, int]) -> int: """ Return the squared Euclidean distance between point and origin. Squared distance is used to avoid the computational cost of the square root. """ return (point[0] -...
from solution import find_k_closest_points def test_find_k_closest_points_basic(): points = [(1, 3), (-2, 2), (5, 8), (0, 1)] k = 2 origin = (0, 0) result = find_k_closest_points(points, k, origin) expected = [(0, 1), (-2, 2)] assert set(result) == set(expected) def test_find_k_closest_points_...
[ { "docstring": "Return the squared Euclidean distance between point and origin.\nSquared distance is used to avoid the computational cost of the square root.", "function_declaration": "def squared_euclidean_distance(point, origin):", "function_name": "squared_euclidean_distance", "parameter_list": "...
[ 0, 0, 0, 1, 1, 1, 0, 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": "import heapq\nfrom typing import List, Tuple\nimport math\n\ndef find_k_closest_points(points: List[Tuple[int, int]], k: int, origin: Tuple[int, int] = (0, 0)...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00049897", "row_id": 49897, "seed_ids": "[266]" }
0.675583
Data_Structure_49897
I
[ "squared_euclidean_distance", "find_k_closest_points" ]
2
[ [ "find_k_closest_points", "squared_euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f0fbede5e87c5a0a339be4c0a2f9b2113cb629b9
93585664d660483c74c85e1156b5bc82e54672e9
v1.0
instruct
Docs
Docs: Scikit_3_I
You are tasked with building an out-of-core learning system to classify a large dataset that cannot fit into memory. The dataset is in CSV format and is stored on disk. Implement a solution that uses out-of-core learning to read the data in chunks, process it, and train an incremental classifier. Utilize the scikit-lea...
import pandas as pd from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(file_path, chunk_size): """ A generator function to read the CSV file in chunks of size `chunk_size`. """ for chunk...
import pandas as pd import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score from io import StringIO import pytest def stream_data(file_path, chunk_size): for chunk in pd.read_csv(file_path, chunksize=...
[ { "docstring": "A generator function to read the CSV file in chunks of size `chunk_size`.", "function_declaration": "def stream_data(file_path, chunk_size):", "function_name": "stream_data", "parameter_list": "(file_path, chunk_size)" }, { "docstring": "Train the classifier incrementally on ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00000003", "row_id": 3, "seed_ids": "[63]" }
0.470481
Docs: Scikit_3
I
[ "stream_data", "train_incremental_classifier" ]
2
[ [ "train_incremental_classifier", "stream_data" ] ]
1
[]
false
[]
false
pytest
false
[ "numpy", "pandas", "sklearn" ]
false
528ba092ac1b9b65729abdb883057f346ef3a6ba
cc93e301243f184da0ea8e491730cfae07cf577a
v1.0
instruct
Docs
Docs: Python310_63_I
**Advanced Memory Profiling with `tracemalloc`** ### Objective: Use Python's `tracemalloc` module to profile memory usage in a Python script and identify potential memory leaks or inefficiencies. ### Problem Statement: You are given a Python script `memory_hog.py` which you suspect to contain memory leaks or ineffici...
import tracemalloc import linecache import runpy def display_top(snapshot, key_type='lineno', limit=10): snapshot = snapshot.filter_traces(( tracemalloc.Filter(False, "<frozen importlib._bootstrap>"), tracemalloc.Filter(False, "<unknown>"), )) top_stats = snapshot.statistics(key_type) ...
import pytest import os def test_profile_memory_output(): # Create a sample script for testing script_content = """\ def main(): some_variable = [i for i in range(1000000)] another_variable = [j for j in range(500000)] if __name__ == "__main__": main() """ script_path = "memory_hog_test.py...
[ { "docstring": null, "function_declaration": "def display_top(snapshot, key_type='lineno', limit=10):", "function_name": "display_top", "parameter_list": "(snapshot, key_type='lineno', limit=10)" }, { "docstring": null, "function_declaration": "def profile_memory(file_path):", "funct...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import tracemalloc\nimport runpy\n\ndef profile_memory(file_path: str) -> None:\n tracemalloc.start(10)\n \n # Snapshot before running the script\n snapshot...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00000063", "row_id": 63, "seed_ids": "[404]" }
0.556707
Docs: Python310_63
I
[ "display_top", "profile_memory" ]
2
[ [ "profile_memory", "display_top" ] ]
1
[]
false
[]
false
pytest
false
[]
true
5e86edb2dde3b6f211c26eda00be0f2ffea9c31d
1a63d104c6d122e4d87ac1159156c45deabfd1ee
v1.0
instruct
Docs
Docs: Python310_86_I
### Command-Line Data Analysis Tool In this task, you are required to implement a command-line data analysis tool using Python. Your task is to use the `argparse` module to create a script that accepts several command-line arguments to perform basic data analysis on a dataset of numbers provided by the user. #### Req...
import argparse import sys def read_numbers(filename): try: with open(filename, 'r') as file: numbers = [float(line.strip()) for line in file.readlines()] return numbers except FileNotFoundError: print(f"Error: File {filename} not found.") sys.exit(1) except Valu...
import pytest from solution import * def test_calculate_mean(): numbers = [1, 2, 3, 4, 5] assert calculate_mean(numbers) == 3.0 def test_calculate_median(): numbers = [1, 2, 3, 4, 5] assert calculate_median(numbers) == 3.0 numbers = [1, 2, 3, 4, 5, 6] assert calculate_median(numbers) == 3.5 d...
[ { "docstring": null, "function_declaration": "def read_numbers(filename):", "function_name": "read_numbers", "parameter_list": "(filename)" }, { "docstring": null, "function_declaration": "def calculate_mean(numbers):", "function_name": "calculate_mean", "parameter_list": "(numbe...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import argparse\nimport sys\n\ndef read_numbers(filename):\n try:\n with open(filename, 'r') as file:\n numbers = [float(line.strip()) for line in ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00000086", "row_id": 86, "seed_ids": "[73]" }
0.70009
Docs: Python310_86
I
[ "read_numbers", "calculate_mean", "calculate_median", "calculate_mode", "calculate_variance", "main" ]
6
[ [ "calculate_variance", "calculate_mean" ] ]
1
[]
false
[]
false
pytest
true
[]
true
370bc12b8997171879798a03b1c1cc5f844ba30d
d265bb999de9c026fe6a2e1ca4272dd3fc071efe
v1.0
instruct
Docs
Docs: Python310_127_I
### Question: Multi-Threaded Task Manager using Python `queue` Module You are tasked to create a multi-threaded task manager simulation using the `queue` module. The task manager will handle tasks with different priorities and ensure they are processed correctly by worker threads. You will implement three main functio...
import threading import queue from typing import List, Tuple, Any def enqueue_tasks(task_data: List[Tuple[int, Any]], task_queue: queue.PriorityQueue) -> None: """ Enqueues all tasks from task_data into task_queue. """ for task in task_data: task_queue.put(task) def worker(task_queue: queue.Pr...
import queue import threading from solution import enqueue_tasks, worker, start_task_manager def test_enqueue_tasks(): task_data = [(1, "Task 1"), (3, "Task 3"), (2, "Task 2")] task_queue = queue.PriorityQueue() enqueue_tasks(task_data, task_queue) assert not task_queue.empty() assert task_que...
[ { "docstring": "Enqueues all tasks from task_data into task_queue.", "function_declaration": "def enqueue_tasks(task_data, task_queue):", "function_name": "enqueue_tasks", "parameter_list": "(task_data, task_queue)" }, { "docstring": "Worker thread function that processes tasks from task_que...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\nimport queue\nfrom typing import List, Tuple, Any\n\ndef enqueue_tasks(task_data: List[Tuple[int, Any]], task_queue: queue.PriorityQueue) -> None:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00000127", "row_id": 127, "seed_ids": "[332]" }
0.632798
Docs: Python310_127
I
[ "enqueue_tasks", "worker", "start_task_manager" ]
3
[ [ "start_task_manager", "enqueue_tasks" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6fe22e690dd758aa06c1308ced3e4387651352a6
000eb4e8558b399a6f8401f2854c9add4f075e8c
v1.0
instruct
Docs
Docs: Seaborn_142_I
#### Objective: Demonstrate your understanding of seaborn color palettes and plot customization using the `sns.mpl_palette` function. #### Task: 1. Write a function `generate_custom_palette` that generates and returns a matplotlib colormap based on the parameters given. 2. Create a scatter plot using seaborn, applying...
import seaborn as sns import matplotlib.pyplot as plt from sklearn.datasets import load_iris import matplotlib as mpl def generate_custom_palette(cmap_name: str, n_colors: int, as_cmap: bool) -> any: """ Generates and returns a matplotlib colormap or a list of colors based on the given parameters. Par...
from solution import generate_custom_palette import seaborn as sns import matplotlib as mpl def test_generate_custom_palette_as_list(): palette = generate_custom_palette("viridis", 5, False) assert isinstance(palette, list) assert len(palette) == 5 def test_generate_custom_palette_as_cmap(): colormap ...
[ { "docstring": "Generates and returns a matplotlib colormap or a list of colors based on the given parameters.\n\nParameters:\n- cmap_name (str): Name of the colormap.\n- n_colors (int): Number of colors to sample from the colormap.\n- as_cmap (bool): If True, return the colormap as a continuous colormap, other...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef generate_custom_palette(cmap_name: str, n_colors: int, as_cmap: bool):\n \"\"\"\n Generates a custom...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00000142", "row_id": 142, "seed_ids": "[87]" }
0.718785
Docs: Seaborn_142
I
[ "generate_custom_palette", "plot_with_custom_palette" ]
2
[ [ "plot_with_custom_palette", "generate_custom_palette" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn", "sklearn" ]
false
c19ed180122c75234a70aec6edef20941274872b
5b8934f45549302c851e796c672993df5ae8bc94
v1.0
instruct
Docs
Docs: Python310_143_I
You are tasked with creating a custom error-handling and logging system using Python's `traceback` module. The goal is to capture exceptions, format the stack trace, and log the formatted trace to a file for later analysis. #### Requirements 1. **Function Implementation**: - Implement a function `log_exception(fi...
import traceback import sys def log_exception(file_path: str, limit: int = None) -> None: """ Logs the current exception's stack trace and details to the specified file. Parameters: file_path (str): The path to the log file where the exception details will be written. limit (int, optional): The ma...
import os import pytest from solution import log_exception, exception_logger def test_log_exception(): log_file = 'test_log_exception.txt' try: 1 / 0 except ZeroDivisionError: log_exception(log_file) with open(log_file, 'r') as f: log_contents = f.read() assert "ZeroDi...
[ { "docstring": "Logs the current exception's stack trace and details to the specified file.\n\nParameters:\nfile_path (str): The path to the log file where the exception details will be written.\nlimit (int, optional): The maximum number of stack trace entries to include.", "function_declaration": "def log_...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import traceback\nimport sys\n\ndef log_exception(file_path: str, limit: int = None) -> None:\n \"\"\"\n Logs the current exception to the specified file path.\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00000143", "row_id": 143, "seed_ids": "[335]" }
0.554277
Docs: Python310_143
I
[ "log_exception", "exception_logger" ]
2
[ [ "exception_logger", "log_exception" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2b074d041a2375853465b266036f27330399ace5
42efd5beb30c67b4ff9cdd98460bcb8fa48be836
v1.0
instruct
Docs
Docs: Python310_162_I
### Advanced Python Coding Assessment: `asyncio` Platform Compatibility **Objective:** To evaluate your understanding of the `asyncio` package and its platform-specific limitations. You are required to write code demonstrating comprehension and handling of these constraints. #### Problem Statement Your task is to wr...
import asyncio import sys async def cross_platform_asyncio_support(host: str, port: int) -> str: # Check the platform and set the appropriate event loop policy if sys.platform.startswith('win'): loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) else: loop = asyncio.get...
import asyncio import pytest import sys from solution import cross_platform_asyncio_support @pytest.mark.asyncio async def test_cross_platform_asyncio_support_success(): result = await cross_platform_asyncio_support('example.com', 80) assert "Successfully performed network operation." in result or "Operation f...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport sys\n\nasync def cross_platform_asyncio_support(host: str, port: int) -> str:\n try:\n # Handle platform-specific event loop policy\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00000162", "row_id": 162, "seed_ids": "[370]" }
0.552632
Docs: Python310_162
I
[ "cross_platform_asyncio_support", "main_test" ]
2
[ [ "main_test", "cross_platform_asyncio_support" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d8602e673eb94967bc270bf6387a6527164343fb
45f559ebc6da52cd0b4d66f51bc53e0d4bea101a
v1.0
instruct
Docs
Docs: Pytorch_215_I
### PyTorch Function Transforms Challenge #### Objective: Utilize PyTorch's torch.func library to implement a custom neural network function including advanced function transformations and validate its gradient computation and batching. #### Problem Statement: 1. **Function Implementation: Custom Neural Network** ...
import torch import torch.nn.functional as F from torch.func import grad, vmap, jacrev, hessian def custom_model(weights, feature_vec): """ Custom Neural Network model with single hidden layer and ReLU activation. """ W1, W2 = weights hidden = F.relu(torch.matmul(feature_vec, W1)) output = torc...
import torch from solution import custom_model, mse_loss, compute_gradients, batch_gradients, compute_jacobian, compute_hessian def test_custom_model(): weights = (torch.randn(4, 10), torch.randn(10, 2)) feature_vec = torch.randn(4) output = custom_model(weights, feature_vec) assert output.shape == (2,...
[ { "docstring": "Custom Neural Network model with single hidden layer and ReLU activation.", "function_declaration": "def custom_model(weights, feature_vec):", "function_name": "custom_model", "parameter_list": "(weights, feature_vec)" }, { "docstring": "MSE loss function.", "function_dec...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn.functional as F\nfrom torch.func import grad, vmap, jacrev, hessian\n\ndef custom_model(weights, feature_vec):\n \"\"\"\n Custom neu...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00000215", "row_id": 215, "seed_ids": "[69]" }
0.603975
Docs: Pytorch_215
I
[ "custom_model", "mse_loss", "compute_gradients", "batch_gradients", "compute_jacobian", "compute_hessian" ]
6
[ [ "batch_gradients", "mse_loss" ], [ "compute_gradients", "mse_loss" ], [ "compute_hessian", "custom_model" ], [ "compute_jacobian", "custom_model" ], [ "mse_loss", "custom_model" ] ]
5
[]
false
[]
false
pytest
true
[ "torch" ]
false
1795d5c3f664b75a17a6d2e3e3215c20af293bd8
6ceb04e120c579ce7b8a95df91428a59cb937865
v1.0
instruct
Docs
Docs: Python310_247_I
## Coding Assessment Question ### Objective Create a Python program using the `tkinter` package to develop a GUI application that allows the user to: 1. Select a directory. 2. Input a string value. 3. Save the input string to a text file within the selected directory. ### Requirements - Implement a function `create_g...
import tkinter as tk from tkinter import filedialog, simpledialog, messagebox import os def save_string_to_file(directory, input_string): """ Saves the given input string to a text file within the specified directory. """ if not directory or not input_string: raise ValueError("Both directory an...
import pytest import os import tempfile from solution import save_string_to_file def test_save_string_to_file_success(): # Create a temporary directory with tempfile.TemporaryDirectory() as tempdir: # Test data input_string = "Hello, World!" file_path = save_string_to_file(tempdir, inpu...
[ { "docstring": "Saves the given input string to a text file within the specified directory.", "function_declaration": "def save_string_to_file(directory, input_string):", "function_name": "save_string_to_file", "parameter_list": "(directory, input_string)" }, { "docstring": "Initializes the ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import tkinter as tk\nfrom tkinter import filedialog, simpledialog, messagebox\n\ndef save_input_to_file(directory, input_string):\n \"\"\"\n Saves the input stri...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00000247", "row_id": 247, "seed_ids": "[271]" }
0.465931
Docs: Python310_247
I
[ "save_string_to_file", "create_gui" ]
2
[ [ "create_gui", "save_string_to_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a13435ab0aa7861d8f72f552837317e4b8543ff2
086a9bc3a48e0b944b409c1532aa9c86b6ffaf5e