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_5548_I | ### Radix Sort Implementation Challenge
**Scenario**:
You are provided with a list of non-negative integers that need to be sorted efficiently. One of the algorithms that excel in this scenario is Radix Sort.
**Task**:
Implement a function that takes a list of non-negative integers and returns a sorted list using the... | def counting_sort(arr, exp, simulation=False):
n = len(arr)
output = [0] * n
count = [0] * 10
# Count occurrences of digits
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
# Convert count to position array
for i in range(1, 10):
count[i] += c... | 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]
def test_radix_sort_single_element():
assert radix_sort([1]) == [1]
def test_radix_sort_sorted():
assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
d... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation=False):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation=False)"
},
{
"docstring": "Function to perform radix sort on a list of non-negative integers.\n\nParameters:\narr (list of... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp, simulation=False):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \n # Count occurrences of digits\n for... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00005548",
"row_id": 5548,
"seed_ids": "[15]"
} | 0.628431 | Data_Structure_5548 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dae43154502ebb7b05495935b834bc477cab3506 | edf79a8fd5d055529d7c2b8defead2c4352dc115 | |||
v1.0 | instruct | Data_Structure | Data_Structure_5577_I | ### Question: Enhanced Separate Chaining Hash Table
#### Scenario
You have been provided with an implementation of a separate chaining hash table. While it works, it lacks some important features, such as dynamic resizing and more robust error handling.
#### Task
Enhance the provided `SeparateChainingHashTable` class... | import itertools
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
ret... | from solution import SeparateChainingHashTable
def test_put_and_get():
table = SeparateChainingHashTable()
table.put('key1', 'value1')
assert table.get('key1') == 'value1'
table.put('key1', 'value2')
assert table.get('key1') == 'value2'
def test_remove():
table = SeparateChainingHashTable(... | [] | [
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 itertools\n\ndef is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00005577",
"row_id": 5577,
"seed_ids": "[119]"
} | 0.426293 | Data_Structure_5577 | I | [
"is_prime",
"next_prime"
] | 2 | [
[
"next_prime",
"is_prime"
]
] | 1 | [] | false | [
"SeparateChainingHashTable"
] | true | pytest | true | [] | true | 6a993a2296d7a40b89a975060c3a87077a7b0040 | 2979b2ef0b748c171360ffa292333e871f4c07fb | |||
v1.0 | instruct | Data_Structure | Data_Structure_5586_I | ### Scenario
You are working on implementing a secure communication system where two parties need to establish a shared secret key over an insecure network. Your task is to implement the core phases of the Diffie-Hellman key exchange protocol.
### Objective
Write functions to carry out key steps in the Diffie-Hellman ... | import math
import random
def prime_check(num):
"""
Returns True if num is a prime number, otherwise False.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or n... | import pytest
from solution import (prime_check, euler_totient, find_primitive_root,
alice_private_key, alice_public_key, bob_private_key,
bob_public_key, alice_shared_key, bob_shared_key,
diffie_hellman_key_exchange)
def test_prime_check():
assert... | [
{
"docstring": "Returns True if num is a prime number, otherwise False.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Returns the Euler's totient function value of n.",
"function_declaration": "def euler_to... | [
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\nimport math\n\ndef prime_check(num):\n \"\"\"\n Returns True if the number is prime, False otherwise.\n \"\"\"\n if num < 2:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00005586",
"row_id": 5586,
"seed_ids": "[146]"
} | 0.40531 | Data_Structure_5586 | I | [
"prime_check",
"euler_totient",
"find_primitive_root",
"alice_private_key",
"alice_public_key",
"bob_private_key",
"bob_public_key",
"alice_shared_key",
"bob_shared_key",
"diffie_hellman_key_exchange"
] | 10 | [
[
"diffie_hellman_key_exchange",
"alice_private_key"
],
[
"diffie_hellman_key_exchange",
"alice_public_key"
],
[
"diffie_hellman_key_exchange",
"alice_shared_key"
],
[
"diffie_hellman_key_exchange",
"bob_private_key"
],
[
"diffie_hellman_key_exchange",
"bob_pu... | 10 | [] | false | [] | false | pytest | true | [] | true | 05f7ceedcbcd1226a64a09396e1b17b456224f8c | 6182e8907cd96254a8e172b7b66e088022820a0e | |||
v1.0 | instruct | Data_Structure | Data_Structure_5590_I | Given the implementation of inorder traversal of a binary tree in both iterative and recursive styles, your task is to write a function that performs "K-th smallest element in a Binary Search Tree".
### Problem Statement
You are provided with a binary search tree (BST) and an integer `k`. Write a function `kth_smalle... | class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_traversal(node, result):
if node:
inorder_traversal(node.left, result)
result.append(node.val)
inorder_traversal(node.right, resul... | import pytest
from solution import Node, kth_smallest
def test_kth_smallest():
n1 = Node(100)
n2 = Node(50)
n3 = Node(150)
n4 = Node(25)
n5 = Node(75)
n6 = Node(125)
n7 = Node(175)
n1.left, n1.right = n2, n3
n2.left, n2.right = n4, n5
n3.left, n3.right = n6, n7
assert kth_s... | [] | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.ri... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00005590",
"row_id": 5590,
"seed_ids": "[310]"
} | 0.517672 | Data_Structure_5590 | I | [
"inorder_traversal",
"kth_smallest"
] | 2 | [
[
"kth_smallest",
"inorder_traversal"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 7ec62b839077833bbf720342409428d42f8d0e24 | ea2ae7a9a851d6869144f95d83d77d84c8818ad4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_5643_I | ### Task: Implement a Hybrid Heap Sort Algorithm
#### Objective
Using the principles of both Max Heap Sort and Min Heap Sort, develop a hybrid heap sort algorithm that can dynamically switch between Max Heap and Min Heap based on certain conditions, optimizing the overall sorting process.
#### Problem Statement
Write... | def max_heapify(arr, n, i):
"""
Helper function to maintain the max heap property for the given subtree.
"""
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[largest] < arr[left]:
largest = left
if right < n and arr[largest] < arr[right]:
largest = righ... | from solution import hybrid_heap_sort
def test_hybrid_heap_sort_basic():
arr = [4, 10, 3, 5, 1, 7, 9, 6]
assert hybrid_heap_sort(arr) == [1, 3, 4, 5, 6, 7, 9, 10]
def test_hybrid_heap_sort_single_element():
arr = [1]
assert hybrid_heap_sort(arr) == [1]
def test_hybrid_heap_sort_sorted_array():
ar... | [
{
"docstring": "Helper function to maintain the max heap property for the given subtree.",
"function_declaration": "def max_heapify(arr, n, i):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Helper function to maintain the min heap property for the given... | [
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 heapify(arr, n, i, max_heap=True):\n largest_smallest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if max_heap:\n if left < n and arr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00005643",
"row_id": 5643,
"seed_ids": "[8]"
} | 0.638633 | Data_Structure_5643 | I | [
"max_heapify",
"min_heapify",
"max_heap_sort",
"min_heap_sort",
"hybrid_heap_sort"
] | 5 | [
[
"hybrid_heap_sort",
"max_heap_sort"
],
[
"hybrid_heap_sort",
"min_heap_sort"
],
[
"max_heap_sort",
"max_heapify"
],
[
"min_heap_sort",
"min_heapify"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | ed93b7df27e2c2c85b48a2b302b3c9ec207c62e1 | f065f2e8bee75ce9248c1615502942168dc7a139 | |||
v1.0 | instruct | Data_Structure | Data_Structure_5701_I | ### Question: Check Prime Intervals
You have been tasked with developing a function that checks the number of prime numbers in a given range \([a, b]\) inclusively.
#### Task:
Write a Python function `count_primes(a: int, b: int) -> int` that returns the count of prime numbers between two given integers \(a\) and \(b... | import math
def is_prime(n):
"""
Check if a number is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import count_primes
def test_primes_in_small_range():
assert count_primes(1, 10) == 4 # Primes: 2, 3, 5, 7
def test_primes_in_mid_range():
assert count_primes(10, 20) == 4 # Primes: 11, 13, 17, 19
def test_primes_in_negative_to_positive_range():
assert count_primes(-10, 10) == 4 # Primes... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Count the number of prime numbers in the range [a, b] (inclusive).",
"function_declaration": "def count_primes(a, b):... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00005701",
"row_id": 5701,
"seed_ids": "[143]"
} | 0.726178 | Data_Structure_5701 | I | [
"is_prime",
"count_primes"
] | 2 | [
[
"count_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ae45a0672fb84dfb71bb9a43bc1ca21cb9641266 | 4c957aad977951508dc71c5f0e9477ed7aa31a51 | |||
v1.0 | instruct | Data_Structure | Data_Structure_5714_I | ### Scenario
You are working on a problem that requires identifying numbers within a specific range where each digit raised to the power of its position and summed equals the number itself. These numbers are often referred to as digit power sum numbers or "Eureka" numbers.
### Problem
Write a function `find_eureka_nu... | def find_eureka_numbers(start, end):
"""
Returns a list of "Eureka" numbers within the range [start, end] inclusive.
A Eureka number is a number that can be represented as the sum of its digits raised
to their respective positions.
"""
eureka_numbers = []
for num in range(start, end + 1):
... | from solution import find_eureka_numbers, is_eureka_number
def test_find_eureka_numbers_basic():
assert find_eureka_numbers(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_find_eureka_numbers_up_to_100():
assert find_eureka_numbers(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
def test_find_eureka_numbers_large_... | [
{
"docstring": "Returns a list of \"Eureka\" numbers within the range [start, end] inclusive.\nA Eureka number is a number that can be represented as the sum of its digits raised \nto their respective positions.",
"function_declaration": "def find_eureka_numbers(start, end):",
"function_name": "find_eur... | [
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 find_eureka_numbers(start, end):\n def is_eureka_number(n):\n digits = list(map(int, str(n)))\n return n == sum(d ** (idx + 1) for idx, d... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00005714",
"row_id": 5714,
"seed_ids": "[135]"
} | 0.571552 | Data_Structure_5714 | I | [
"find_eureka_numbers",
"is_eureka_number"
] | 2 | [
[
"find_eureka_numbers",
"is_eureka_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4561abf6e2791b38b572725dc4cda4792acd3e58 | 0a0b17e6aafe91a91b0b3b4773bb123e37aa4c9b | |||
v1.0 | instruct | Data_Structure | Data_Structure_5725_I | ## Question: Cycle Detection in a Directed Graph
### Objective
Write a function to determine whether a given directed graph contains a cycle.
### Input
- A dictionary representing the directed graph. Each key-value pair represents a vertex and its list of adjacent vertices (the outgoing edges).
### Output
- A boolea... | from enum import Enum
class TraversalState(Enum):
WHITE = 0
GRAY = 1
BLACK = 2
def is_in_cycle(graph, traversal_states, vertex):
if traversal_states[vertex] == TraversalState.GRAY:
return True
traversal_states[vertex] = TraversalState.GRAY
for neighbor in graph[vertex]:
if trav... | def test_contains_cycle_true():
graph = {
'A': ['B'],
'B': ['C'],
'C': ['A']
}
assert contains_cycle(graph) == True
def test_contains_cycle_false():
graph = {
'A': ['B'],
'B': ['C'],
'C': ['D'],
'D': []
}
assert contains_cycle(graph) == Fa... | [] | [
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 enum import Enum\n\nclass TraversalState(Enum):\n WHITE = 0\n GRAY = 1\n BLACK = 2\n\ndef is_in_cycle(graph, traversal_states, vertex):\n if ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00005725",
"row_id": 5725,
"seed_ids": "[237]"
} | 0.623696 | Data_Structure_5725 | I | [
"is_in_cycle",
"contains_cycle"
] | 2 | [
[
"contains_cycle",
"is_in_cycle"
]
] | 1 | [] | false | [
"TraversalState"
] | true | pytest | false | [] | true | 5be5cfcffcc533aa9205ca4273a8af6812bcf60d | 0846e71549ddda7812839ab7fb64b6f0adeeb4f9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_5793_I | ### Question: Advanced GCD Calculation with Constraints
In this question, you are tasked to implement a function that computes the greatest common divisor (GCD) of a list of integers. Your implementation should consider both positive and negative integers and leverage bitwise operations for optimization. Additionally,... | from typing import List
def gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor using the bitwise Stein's algorithm.
"""
if a == 0:
return b
if b == 0:
return a
# both a and b are nonzero
if a < 0:
a = -a
if b < 0:
b = -b
# find com... | from solution import optimized_gcd
def test_positive_numbers():
assert optimized_gcd([54, 24, 36]) == 6
def test_mixed_sign_numbers():
assert optimized_gcd([48, -180, 640]) == 4
def test_with_zeros():
assert optimized_gcd([0, 24, 36]) == 12 # any list will contain non-zero elements
def test_single_eleme... | [
{
"docstring": "Computes the greatest common divisor using the bitwise Stein's algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the greatest common divisor of a list of integers using bitwise operations.",
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom functools import reduce\n\ndef gcd(a: int, b: int) -> int:\n \"\"\"\n Calculate the greatest common divisor (GCD) of two i... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00005793",
"row_id": 5793,
"seed_ids": "[166]"
} | 0.667987 | Data_Structure_5793 | I | [
"gcd",
"optimized_gcd"
] | 2 | [
[
"optimized_gcd",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b013ceee2d64052cca81490893407458da6aec27 | f51c7cec910151c06ad767375d1a7406b211d1ef | |||
v1.0 | instruct | Data_Structure | Data_Structure_5800_I | ### Question: Implement Enhanced Bucket Sort
You have been provided with the bucket sort algorithm, a technique suitable for sorting an array of numbers by dividing them into several buckets, sorting each bucket, and then combining the sorted buckets.
However, the provided implementation uses insertion sort for sort... | from typing import List
def quicksort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
else:
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(l... | from solution import bucket_sort
def test_bucket_sort():
assert bucket_sort([29, 25, 3, 49, 37, 21, 43, 31, 33]) == [3, 21, 25, 29, 31, 33, 37, 43, 49]
assert bucket_sort([]) == []
assert bucket_sort([1, 1, 1, 1]) == [1, 1, 1, 1]
assert bucket_sort([3, 3, 3, 1, 1, 1, 2, 2, 2]) == [1, 1, 1, 2, 2, 2, 3, ... | [
{
"docstring": null,
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def bucket_sort(arr):",
"function_name": "bucket_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef bucket_sort(arr: List[int]) -> List[int]:\n if not arr:\n return []\n\n # Determine maximum value to identify numb... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00005800",
"row_id": 5800,
"seed_ids": "[26]"
} | 0.538879 | Data_Structure_5800 | I | [
"quicksort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 076f0cf6537fd392691fff6339464f3771bfe5fb | eade34341f1c60f26613e0d19f0496aa4314ac7c | |||
v1.0 | instruct | Data_Structure | Data_Structure_5835_I | ### Question
You have been provided with an implementation of Bogo Sort, a highly inefficient sorting algorithm. Your task is to implement a new sorting function to simulate and visualize each step of the sorting process. However, given the impracticality of Bogo Sort for real-world scenarios, your solution should ens... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def visual_bogo_sort(arr, max_iterations):
"""
Performs a Bogo Sort on the array while visualizing e... | from solution import visual_bogo_sort
import io
import sys
def test_visual_bogo_sort_sorted():
arr = [1, 2, 3, 4, 5]
max_iterations = 1000
captured_output = io.StringIO()
sys.stdout = captured_output
visual_bogo_sort(arr, max_iterations)
sys.stdout = sys.__stdout__
assert "Sorted after... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Performs a Bogo Sort on the array while visualizing each iteration.\n\nArgs:\narr (list of int): The ar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Utility function to check if the array is sorted.\n \"\"\"\n for i in range(len(arr) - 1):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00005835",
"row_id": 5835,
"seed_ids": "[16]"
} | 0.485172 | Data_Structure_5835 | I | [
"is_sorted",
"visual_bogo_sort"
] | 2 | [
[
"visual_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 70932dcb053f4e2b301232e0e5f7f487498195fc | 1558547a00b212419f0b1fdd3f78ac2c0f84b7a5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_5870_I | ### Insertion Sort Enhancement
As a software developer at an e-commerce company, you've been tasked to optimize the sorting algorithm for various data-intensive reporting features. The current implementation of the Insertion Sort works fine; however, it struggles with large datasets.
The data you'll work with is pri... | from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
"""
Simple insertion sort algorithm for reasonably small arrays.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
... | from solution import optimized_insertion_sort
def test_example_case_1():
arr = [5, 2, 9, 1, 5, 6]
threshold = 10
assert optimized_insertion_sort(arr, threshold) == [1, 2, 5, 5, 6, 9]
def test_example_case_2():
arr = [50, 23, 93, 17, 77, 31, 44, 55, 20, 27]
threshold = 5
assert optimized_insert... | [
{
"docstring": "Simple insertion sort algorithm for reasonably small arrays.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Quicksort algorithm for larger arrays.",
"function_declaration": "def quickso... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_insertion_sort(arr, threshold):\n def insertion_sort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00005870",
"row_id": 5870,
"seed_ids": "[7]"
} | 0.554449 | Data_Structure_5870 | I | [
"insertion_sort",
"quicksort",
"optimized_insertion_sort"
] | 3 | [
[
"optimized_insertion_sort",
"insertion_sort"
],
[
"optimized_insertion_sort",
"quicksort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b5970736aee59076973dbb0694e70aebe19ad694 | f2e3bb823f86b47ee6caf59d669353e023d759c5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_5907_I | ### Problem: Enhanced Kruskal's Algorithm to calculate number of connected components
Implement a function that not only computes the Minimum Spanning Tree (MST) of an undirected graph using Kruskal’s algorithm but also returns the number of connected components in the graph.
### Function Signature
```python
def krus... | from typing import List, Tuple
class Edge:
def __init__(self, u: int, v: int, weight: int):
self.u = u
self.v = v
self.weight = weight
def find(subsets, node):
if subsets[node] != node:
subsets[node] = find(subsets, subsets[node])
return subsets[node]
def union(subsets, ra... | def test_kruskal_with_components_single_component():
edges = [
Edge(0, 1, 3),
Edge(0, 2, 8),
Edge(1, 3, 5),
Edge(2, 3, 2),
Edge(2, 4, 4),
Edge(3, 4, 6),
]
assert kruskal_with_components(5, edges) == (14, 1)
def test_kruskal_with_components_disconnected():
... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\nclass Edge:\n def __init__(self, u: int, v: int, w: int):\n self.u = u\n self.v = v\n self.w = w\n\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00005907",
"row_id": 5907,
"seed_ids": "[230]"
} | 0.727208 | Data_Structure_5907 | I | [
"find",
"union",
"kruskal_with_components"
] | 3 | [
[
"kruskal_with_components",
"find"
],
[
"kruskal_with_components",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [
"Edge"
] | true | pytest | false | [] | true | 65092ccdf9467a6d53bf27125007c11df724ef00 | 8ff8af8def25eaf5a43670737347ca66199aa189 | |||
v1.0 | instruct | Data_Structure | Data_Structure_5924_I | In this coding task, you are required to implement the bitonic sort algorithm as per the given constraints and further enhance it to handle a broader range of input scenarios.
### Task:
1. **Implement Bitonic Sort**:
Modify the existing `bitonic_sort` function to sort an array of integers in both increasing and de... | import math
from typing import List
def bitonic_sort(arr: List[int], low: int, cnt: int, order: bool):
""" Helper function to perform bitonic sort on a subarray """
if cnt > 1:
k = cnt // 2
bitonic_sort(arr, low, k, True) # First half in ascending order
bitonic_sort(arr, low + k, k, Fa... | from solution import generalized_bitonic_sort
def test_empty_array():
assert generalized_bitonic_sort([]) == []
def test_single_element():
assert generalized_bitonic_sort([1]) == [1]
def test_power_of_two_length_array():
assert generalized_bitonic_sort([3, 7, 2, 5], reverse=False) == [2, 3, 5, 7]
ass... | [
{
"docstring": "Helper function to perform bitonic sort on a subarray ",
"function_declaration": "def bitonic_sort(arr, low, cnt, order):",
"function_name": "bitonic_sort",
"parameter_list": "(arr, low, cnt, order)"
},
{
"docstring": "Helper function to merge bitonically sorted subarrays ",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import List\n\ndef bitonic_sort(arr: List[int], low: int, cnt: int, order: bool):\n \"\"\" Helper function to perform bitonic sort... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00005924",
"row_id": 5924,
"seed_ids": "[17]"
} | 0.678924 | Data_Structure_5924 | I | [
"bitonic_sort",
"bitonic_merge",
"generalized_bitonic_sort"
] | 3 | [
[
"bitonic_sort",
"bitonic_merge"
],
[
"generalized_bitonic_sort",
"bitonic_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7ee6b2b5d9ef62df50fc9b72c0945460ed0b190d | d7028e5e657aaf6d5d2a2216c7b1b9b29ce4f1b6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_5935_I | #### Context
You've recently learned about various sorting algorithms and their efficiency. One of the most inefficient sorts is the Bogo Sort, which relies on random shuffling until the array is sorted. Despite its inefficiency, Bogo Sort can be a valuable educational tool for understanding the importance of algorithm... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def bogo_sort(arr: list, simulation: bool = False) -> list:
"""
Sorts the array using the Bogo Sort algorithm.
"""
if len(arr) <= 1:
... | from solution import bogo_sort
def test_empty_array():
assert bogo_sort([]) == []
def test_single_element_array():
assert bogo_sort([1]) == [1]
def test_already_sorted_array():
assert bogo_sort([1, 2, 3]) == [1, 2, 3]
def test_reverse_sorted_array():
assert bogo_sort([3, 2, 1]) == [1, 2, 3]
def tes... | [
{
"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 array using the Bogo Sort algorithm.",
"function_declaration": "def bogo_sort(arr, simula... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef bogo_sort(arr: list, simulation: bool = False) -> list:\n def is_sorted(arr):\n for i in range(len(arr) - 1):\n if a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00005935",
"row_id": 5935,
"seed_ids": "[16]"
} | 0.56724 | Data_Structure_5935 | I | [
"is_sorted",
"bogo_sort"
] | 2 | [
[
"bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 732c067e605033e4bc229739e95857b66d6f8687 | a833b00eab8342c6d20c426da88f5e168cb71a4d | |||
v1.0 | instruct | Data_Structure | Data_Structure_5936_I | ### Scenario
You are working as a software engineer at a logistics company that is optimizing its network of delivery routes. They need to ensure that they can handle maximum traffic flow through their delivery network efficiently. The delivery routes can be represented as a directed graph where nodes represent warehou... | from typing import List
from collections import deque
def bfs_level_graph(capacity: List[List[int]], source: int, sink: int, level: List[int]) -> bool:
"""
Uses BFS to build level graph and store level of each node in level[] array.
Returns True if there is a path from source to sink, else False.
"""
... | from solution import calculate_max_delivery_flow
def test_example_case():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert calculate_... | [
{
"docstring": "Uses BFS to build level graph and store level of each node in level[] array.\nReturns True if there is a path from source to sink, else False.",
"function_declaration": "def bfs_level_graph(capacity, source, sink, level):",
"function_name": "bfs_level_graph",
"parameter_list": "(capa... | [
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\nfrom collections import deque\n\ndef bfs(level: List[int], capacity: List[List[int]], source: int, sink: int, n: int) -> bool:\n q... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00005936",
"row_id": 5936,
"seed_ids": "[240]"
} | 0.619797 | Data_Structure_5936 | I | [
"bfs_level_graph",
"dfs_flow",
"calculate_max_delivery_flow"
] | 3 | [
[
"calculate_max_delivery_flow",
"bfs_level_graph"
],
[
"calculate_max_delivery_flow",
"dfs_flow"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 62e4fcb82b69ca5876c5ab281ecae71fe3ad4cea | e993698dace36cdd010276a02ccd83f23100b9ba | |||
v1.0 | instruct | Data_Structure | Data_Structure_5978_I | You are implementing a system that requires modular arithmetic for handling large prime numbers. Given two numbers `a` and `m`, you need to find the modular inverse of `a` modulo `m`.
### Task
Implement a function `find_modular_inverse(a: int, m: int) -> int` that returns the modular inverse of `a` modulo `m`. If the ... | def extended_gcd(a, b):
if a == 0:
return b, 0, 1
gcd, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y
def find_modular_inverse(a: int, m: int) -> int:
gcd, x, y = extended_gcd(a, m)
if gcd != 1:
raise ValueError("Modular inverse doesn't exist ... | from solution import find_modular_inverse
import pytest
def test_modular_inverse_common_case():
assert find_modular_inverse(3, 11) == 4
def test_modular_inverse_large_numbers():
assert find_modular_inverse(17, 3120) == 2753
def test_modular_inverse_not_coprime():
with pytest.raises(ValueError):
f... | [
{
"docstring": null,
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def find_modular_inverse(a, m):",
"function_name": "find_modular_inverse",
"parameter_list": "(a, m... | [
0,
0,
0,
0,
0,
1,
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 gcd_extended(a, b):\n if a == 0:\n return b, 0, 1\n gcd, x1, y1 = gcd_extended(b % a, a)\n x = y1 - (b // a) * x1\n y = x1\n return ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00005978",
"row_id": 5978,
"seed_ids": "[161]"
} | 0.602212 | Data_Structure_5978 | I | [
"extended_gcd",
"find_modular_inverse"
] | 2 | [
[
"find_modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a2991d4fbe57d5da616ede1591b800aea06c7091 | ccb1d8af29c0cae24f211e62c3f86957a9dd98c8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_5991_I | ### Question: Bit Manipulation for Custom Permission System
You are tasked with developing a simple but efficient permission system using bit manipulation. Each user in your system will have an integer representing their permissions. Each bit in this integer corresponds to a specific permission:
- Bit 0: Read (1 if a... | def has_permission(permissions: int, position: int) -> bool:
"""
Check if a specific permission (given by position) is set in the permissions.
"""
return (permissions & (1 << position)) != 0
def grant_permission(permissions: int, position: int) -> int:
"""
Grant a specific permission (set the b... | from solution import has_permission, grant_permission, revoke_permission, set_permission
def test_has_permission():
permissions = 0b0001
assert has_permission(permissions, 0) == True
assert has_permission(permissions, 1) == False
def test_grant_permission():
permissions = 0b0000
permissions = gran... | [
{
"docstring": "Check if a specific permission (given by position) is set in the permissions.",
"function_declaration": "def has_permission(permissions, position):",
"function_name": "has_permission",
"parameter_list": "(permissions, position)"
},
{
"docstring": "Grant a specific permission ... | [
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 has_permission(permissions: int, position: int) -> bool:\n \"\"\"\n Check if a specific permission (given by position) is set.\n Args:\n - per... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00005991",
"row_id": 5991,
"seed_ids": "[212]"
} | 0.570098 | Data_Structure_5991 | I | [
"has_permission",
"grant_permission",
"revoke_permission",
"set_permission"
] | 4 | [
[
"set_permission",
"grant_permission"
],
[
"set_permission",
"revoke_permission"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e4463815ac254f94a7e4a62b53c2ee3a893fce8f | 1452423fb87e885101193a1cd4f5f132c13add7d | |||
v1.0 | instruct | Data_Structure | Data_Structure_6013_I | Efficient Sorting Function
#### Scenario
You have been provided with a legacy sorting function in a project, called Stooge Sort, which is seen to be highly inefficient for practical use due to its very high time complexity. Your task is to implement a more efficient sorting algorithm to replace Stooge Sort while maint... | def quick_sort(arr, left, right):
"""
Sorts the array in-place from index 'left' to index 'right' using Quick Sort algorithm.
Parameters:
arr: list - list of elements to be sorted.
left: int - starting index of the segment of the list to be sorted.
right: int - ending index of the segment o... | from solution import quick_sort
def test_sorted_array():
arr = [1, 2, 3, 4, 5]
quick_sort(arr, 0, len(arr) - 1)
assert arr == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
arr = [5, 4, 3, 2, 1]
quick_sort(arr, 0, len(arr) - 1)
assert arr == [1, 2, 3, 4, 5]
def test_unsorted_array():
ar... | [
{
"docstring": "Sorts the array in-place from index 'left' to index 'right' using Quick Sort algorithm.\n\nParameters:\narr: list - list of elements to be sorted.\nleft: int - starting index of the segment of the list to be sorted.\nright: int - ending index of the segment of the list to be sorted.",
"funct... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def quick_sort(arr: list, left: int, right: int) -> None:\n \"\"\"\n Sorts the array in-place from index 'left' to index 'right' using Quick Sort algori... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006013",
"row_id": 6013,
"seed_ids": "[10]"
} | 0.614291 | Data_Structure_6013 | I | [
"quick_sort",
"partition"
] | 2 | [
[
"quick_sort",
"partition"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 13b00759de55e895b6be8da93614202a95c6197b | 9ff7b72c5ddda5952217e44867bd7fb4914339f0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6135_I | You are given a class `Interval` with methods to manage intervals of real numbers. The class can determine if a number is included within an interval, merge overlapping intervals, and more. Your task is to enhance this class to include additional functionalities that handle more sophisticated interval operations.
### ... | class Interval:
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return f"Interval({self.start}, {self.end})"
def __eq__(self, other):
return self.start == other.start and self.end == other.end
def fuse_intervals(intervals):
if not ... | from solution import Interval, fuse_intervals, find_gaps
def test_fuse_intervals_no_intervals():
assert fuse_intervals([]) == []
def test_fuse_intervals_touching_intervals():
intervals = [Interval(1, 5), Interval(5, 10)]
expected = [Interval(1, 10)]
assert fuse_intervals(intervals) == expected
def te... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Interval:\n def __init__(self, start, end):\n assert start <= end, \"Start should be less or equal to end\"\n self.start = start\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006135",
"row_id": 6135,
"seed_ids": "[285]"
} | 0.6673 | Data_Structure_6135 | I | [
"fuse_intervals",
"find_gaps"
] | 2 | [
[
"find_gaps",
"fuse_intervals"
]
] | 1 | [] | false | [
"Interval"
] | true | pytest | true | [] | true | 4a61a52e1ce294e39f7fe76550942e1baf2d0861 | e5ebbd9a5d211ca6a9c736c5293dd7173b723859 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6168_I | ### Euler's Totient Function and GCD Sum Calculation
#### Problem Statement
Euler's Totient function, denoted as ϕ(n), counts the number of positive integers up to `n` that are coprime with `n`. Implement the function `euler_totient()` that calculates ϕ(n) as follows:
```python
def euler_totient(n: int) -> int:
"... | def gcd(a, b):
while b:
a, b = b, a % b
return a
def euler_totient(n: int) -> int:
count = 0
for i in range(1, n + 1):
if gcd(n, i) == 1:
count += 1
return count
def gcd_sum(N: int) -> int:
total = 0
for i in range(1, N + 1):
total += euler_totient(i)
... | from solution import euler_totient, gcd_sum
def test_euler_totient():
assert euler_totient(1) == 1
assert euler_totient(2) == 1
assert euler_totient(3) == 2
assert euler_totient(4) == 2
assert euler_totient(5) == 4
assert euler_totient(6) == 2
assert euler_totient(7) == 6
assert euler_t... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def euler_totient(n):",
"function_name": "euler_totient",
"parameter_list": "(n)"
},
{
"docstring": null,
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def euler_totient(n: int) -> int:\n \"\"\"\n Calculates Euler's Totient function value for a given integer n.\n This counts the number of positive in... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006168",
"row_id": 6168,
"seed_ids": "[141]"
} | 0.621328 | Data_Structure_6168 | I | [
"gcd",
"euler_totient",
"gcd_sum"
] | 3 | [
[
"euler_totient",
"gcd"
],
[
"gcd_sum",
"euler_totient"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 32962159cb6d0184d61061ec27aa31705486ef88 | a358eb92085dfaffdb642236e8c0a679a1abb34f | |||
v1.0 | instruct | Data_Structure | Data_Structure_6213_I | **Scenario**:
Imagine you are working on a software tool that requires efficiently managing a sorted list of user ratings. Users frequently add new ratings, and these ratings need to be inserted into the current sorted list quickly without re-sorting the entire list. Your task is to implement a function that can handl... | from typing import List
def search_insert(sorted_ratings: List[int], new_rating: int) -> int:
"""
Helper function to find the correct insertion position for new_rating
in the sorted list sorted_ratings.
"""
left, right = 0, len(sorted_ratings)
while left < right:
mid = (left + rig... | from solution import insert_and_sort
def test_insert_and_sort():
# Test inserting into the middle of the list
sorted_ratings = [1, 3, 5, 6]
new_rating = 2
assert insert_and_sort(sorted_ratings, new_rating) == [1, 2, 3, 5, 6]
# Test inserting at the end of the list
sorted_ratings = [1, 3, 5, 6]... | [
{
"docstring": "Helper function to find the correct insertion position for new_rating \nin the sorted list sorted_ratings.",
"function_declaration": "def search_insert(sorted_ratings, new_rating):",
"function_name": "search_insert",
"parameter_list": "(sorted_ratings, new_rating)"
},
{
"docs... | [
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 search_insert(arr: List[int], target: int) -> int:\n \"\"\"\n Helper function to find the index where the target should b... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006213",
"row_id": 6213,
"seed_ids": "[199]"
} | 0.575717 | Data_Structure_6213 | I | [
"search_insert",
"insert_and_sort"
] | 2 | [
[
"insert_and_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6651a161493522f90c1a7bf0818a313f73b2cdc7 | d3e9deea384d74fb29129ea2c22b5f22a0b747a4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6276_I | **Coding Challenge: Implementing Improved Jump Search**
**Scenario**:
You are given a sorted list of unique integers representing recorded temperatures over several days. Your goal is to find a particular temperature in the list using a modified version of the jump search algorithm.
Instead of a fixed block size, yo... | from math import sqrt
from typing import List
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def improved_jump_search(arr: List[int], target: int) -> int:
n = len(arr)
if n == 0:
return -1
fib_gen = fibonacci()
fib_m = next(fib_gen) # Fibonacci[m-1]
... | def test_improved_jump_search():
# Test case: target found in the middle
arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
target = 7
assert improved_jump_search(arr, target) == 3
# Test case: target found at the beginning
arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
target = 1
assert improved... | [
{
"docstring": null,
"function_declaration": "def fibonacci():",
"function_name": "fibonacci",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def improved_jump_search(arr, target):",
"function_name": "improved_jump_search",
"parameter_list": "(arr, target... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import sqrt\nfrom typing import List\n\ndef fibonacci_numbers(limit):\n fibs = [1, 2]\n while fibs[-1] <= limit:\n fibs.append(fibs[-1]... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006276",
"row_id": 6276,
"seed_ids": "[196]"
} | 0.618298 | Data_Structure_6276 | I | [
"fibonacci",
"improved_jump_search"
] | 2 | [
[
"improved_jump_search",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | c105d015f126c3cdc2ff3b131a3ec546acef740d | bef101c79c08952a4da83b8543cc4f7e723260d0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6278_I | ### Coding Challenge: Subtree Check
You are given two binary trees, `s` and `t`. Your task is to write a function to determine if `t` is a subtree of `s`. A subtree of `s` is a node in `s` and all of its descendants that form a tree equivalent to `t`.
### Your Function
Implement the function `is_subtree(big, small)` ... | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(big, small):
if not small:
return True # An empty tree is always a subtree
if not big:
return Fal... | from solution import TreeNode, is_subtree
def test_subtree_found_case_1():
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.left.right = TreeNode(2)
t = TreeNode(4)
t.left = TreeNode(1)
t.right = TreeNode(2)
assert is_subtree(s, t) == True... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006278",
"row_id": 6278,
"seed_ids": "[288]"
} | 0.599321 | Data_Structure_6278 | I | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 820430c0ee9017a597457f65100e4216d9a697a3 | 98a169ab80aa7c9dcd1eb0ff5b6f3a001c7f6dcc | |||
v1.0 | instruct | Data_Structure | Data_Structure_6359_I | ### Problem: Advanced Number Operations
You are tasked with implementing a series of functions that perform advanced number operations. These functions will require you to handle integer properties efficiently. Your implementation must account for edge cases carefully and optimize performance as much as possible.
**1.... | def gcd_bitwise(a: int, b: int) -> int:
"""
Calculates the greatest common divisor (GCD) of two non-negative integers using bitwise operations.
"""
if a == 0:
return b
if b == 0:
return a
# Finding common factors of 2
shift = 0
while ((a | b) & 1) == 0:
a >>= 1
... | from solution import gcd_bitwise, lcm_with_gcd, count_trailing_zeros
def test_gcd_bitwise():
assert gcd_bitwise(48, 18) == 6
assert gcd_bitwise(0, 5) == 5
assert gcd_bitwise(7, 0) == 7
assert gcd_bitwise(0, 0) == 0
assert gcd_bitwise(101, 103) == 1
def test_lcm_with_gcd():
assert lcm_with_gcd(... | [
{
"docstring": "Calculates the greatest common divisor (GCD) of two non-negative integers using bitwise operations.",
"function_declaration": "def gcd_bitwise(a, b):",
"function_name": "gcd_bitwise",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculates the least common multiple (LCM) of ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd_bitwise(a: int, b: int) -> int:\n \"\"\"\n Calculate the greatest common divisor (GCD) of two non-negative integers using bitwise operations.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006359",
"row_id": 6359,
"seed_ids": "[166]"
} | 0.65962 | Data_Structure_6359 | I | [
"gcd_bitwise",
"lcm_with_gcd",
"count_trailing_zeros"
] | 3 | [
[
"lcm_with_gcd",
"gcd_bitwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8b5c2f745bf18086a1c9c63b3098828660ee74ee | 9302da40571ea33b04f4b1d19e9f701ca33b6483 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6399_I | ### Question: Verify Linked List Palindrome Without Space Overhead
Given a singly linked list of integers, implement a function to determine if it reads the same backwards as forwards without using additional data structures (such as stacks or dictionaries). You should do this in \(O(n)\) time and \(O(1)\) space.
###... | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def find_middle(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def reverse_list(head):
prev = None
current = head
... | from solution import is_palindrome_efficient, ListNode
def create_linked_list(values):
if not values:
return None
head = ListNode(values[0])
current = head
for value in values[1:]:
current.next = ListNode(value)
current = current.next
return head
def test_empty_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": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef is_palindrome_efficient(head: ListNode) ->... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006399",
"row_id": 6399,
"seed_ids": "[246]"
} | 0.598035 | Data_Structure_6399 | I | [
"find_middle",
"reverse_list",
"is_palindrome_efficient"
] | 3 | [
[
"is_palindrome_efficient",
"find_middle"
],
[
"is_palindrome_efficient",
"reverse_list"
]
] | 2 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | 29f0b38aea11738789e4a94bf3000a1a7246e840 | 5af681ab5e097ecf97b96ce2865ba6bb20de86c5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6423_I | You are provided with a list of non-negative integers. Your task is to implement the `radix_sort` function. This function will sort the integers using the radix sort algorithm and return the sorted list.
### Function Signature
```python
def radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
pass
``... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool, iteration: int) -> None:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i] += count[i - ... | from solution import radix_sort
def test_radix_sort_unsorted():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_partially_sorted():
assert radix_sort([3, 0, 2, 5, 4, 1]) == [0, 1, 2, 3, 4, 5]
def test_radix_sort_empty():
assert radix_s... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation, iteration):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation, iteration)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"funct... | [
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, iteration: int) -> None:\n n = len(arr)\n output = [0] * n\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006423",
"row_id": 6423,
"seed_ids": "[15]"
} | 0.662887 | Data_Structure_6423 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4fe145c455fb4596b78696d5a0b18bb56a62f2d8 | fb30b3c9b40c5d6bef4670bb3d79e0e4ae3ee4bd | |||
v1.0 | instruct | Data_Structure | Data_Structure_6461_I | ### Matrix Inversion Enhancement
#### Objective
You are tasked with enhancing the provided matrix inversion function to handle larger matrices more efficiently and accurately. Your solution should aim to reduce the computational overhead and manage error scenarios robustly.
#### Problem Statement
Write a function `en... | from typing import List
def get_matrix_minor(matrix, i, j):
return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]
def get_matrix_determinant(matrix):
# Base case for 2x2 matrix
if len(matrix) == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
determinant = 0
... | from solution import enhanced_invert_matrix
def test_invert_matrix_2x2():
matrix = [
[4, 7],
[2, 6]
]
expected = [
[0.6, -0.7],
[-0.2, 0.4]
]
assert enhanced_invert_matrix(matrix) == expected
def test_invert_matrix_3x3():
matrix = [
[1, 2, 3],
[0... | [
{
"docstring": null,
"function_declaration": "def get_matrix_minor(matrix, i, j):",
"function_name": "get_matrix_minor",
"parameter_list": "(matrix, i, j)"
},
{
"docstring": null,
"function_declaration": "def get_matrix_determinant(matrix):",
"function_name": "get_matrix_determinant"... | [
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, Optional\n\ndef enhanced_invert_matrix(matrix: List[List[int]]) -> Optional[List[List[float]]]:\n def determinant(matrix, cache={}... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006461",
"row_id": 6461,
"seed_ids": "[347]"
} | 0.567433 | Data_Structure_6461 | I | [
"get_matrix_minor",
"get_matrix_determinant",
"get_matrix_inverse",
"enhanced_invert_matrix"
] | 4 | [
[
"enhanced_invert_matrix",
"get_matrix_inverse"
],
[
"get_matrix_determinant",
"get_matrix_minor"
],
[
"get_matrix_inverse",
"get_matrix_determinant"
],
[
"get_matrix_inverse",
"get_matrix_minor"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 52e6d5f5658f2cb0eef7be3ca5037ec1df031f20 | 13844fa1beec4e6a19a3d72968f01d8757668cdb | |||
v1.0 | instruct | Data_Structure | Data_Structure_6490_I | ### Radix Sort Function Implementation
#### Context
You are given a list of non-negative integers, and your task is to implement the Radix Sort algorithm to sort this list in ascending order. The algorithm should use the least significant digit (LSD) approach.
#### Function Signature
```python
def radix_sort(arr: lis... | def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[(index) % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] // exp
output[count[... | 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]
def test_radix_sort_single_element():
assert radix_sort([5]) == [5]
def test_radix_sort_empty():
assert radix_sort([]) == []
def test_radix_sort_with_zer... | [
{
"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, simulation=False):",
"function_name": "radix_sort",
"parameter_list":... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp, simulation):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # Counting occurrences of digits\n for i in r... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006490",
"row_id": 6490,
"seed_ids": "[15]"
} | 0.627104 | Data_Structure_6490 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b31a872d0abbbb501a71c26f8483caa4e3b0846d | 9662f45528bc86c3bb54bed75078361f2deb83bb | |||
v1.0 | instruct | Data_Structure | Data_Structure_6520_I | ## Problem:
You are given a list of `N` vectors, each consisting of `M` elements (comparable to a matrix of size `N x M`). Your task is to compute the cosine similarity between every pair of vectors and store the results in an `N x N` matrix. Each element (i, j) in this matrix should represent the cosine similarity bet... | import math
def cosine_similarity(u, v):
"""
Computes the cosine similarity between two vectors u and v.
"""
dot_product = sum(ui * vi for ui, vi in zip(u, v))
magnitude_u = math.sqrt(sum(ui**2 for ui in u))
magnitude_v = math.sqrt(sum(vi**2 for vi in v))
if magnitude_u == 0 or magnitude_v ... | def test_cosine_similarity():
vector1 = [1, 0, 0]
vector2 = [0, 1, 0]
vector3 = [1, 1, 0]
assert math.isclose(cosine_similarity(vector1, vector1), 1.0, rel_tol=1e-4)
assert math.isclose(cosine_similarity(vector1, vector2), 0.0, rel_tol=1e-4)
assert math.isclose(cosine_similarity(vector1, ve... | [
{
"docstring": "Computes the cosine similarity between two vectors u and v.",
"function_declaration": "def cosine_similarity(u, v):",
"function_name": "cosine_similarity",
"parameter_list": "(u, v)"
},
{
"docstring": "Computes the cosine similarity matrix for given list of vectors.",
"fu... | [
0,
0,
0,
1,
0,
1,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef cosine_similarity(vec1, vec2):\n \"\"\"\n Calculate the cosine similarity between two vectors.\n \"\"\"\n dot_product = sum(a *... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00006520",
"row_id": 6520,
"seed_ids": "[149]"
} | 0.571713 | Data_Structure_6520 | I | [
"cosine_similarity",
"cosine_similarity_matrix"
] | 2 | [
[
"cosine_similarity_matrix",
"cosine_similarity"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 104fcc667b18cad99f4f8f941a88b4e62daa5977 | 63447e39ee6c9ebea0afc6bd1fd481fe9e599672 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6532_I | ### Context
A library search function needs optimizing. Users commonly search for a list of keywords within large texts such as books and articles. Using an efficient pattern matching algorithm can significantly reduce search times and improve user satisfaction.
### Problem Statement
You are required to implement an o... | from typing import List, Dict
def compute_kmp_table(pattern: str) -> List[int]:
"""
This function computes the partial match table (also known as the "next" table or "failure function")
used in KMP algorithm.
"""
m = len(pattern)
kmp_table = [0] * m
length = 0 # length of the previous long... | from solution import search_patterns
def test_single_pattern():
text = 'the quick brown fox jumps over the lazy dog'
patterns = ['the']
expected = {'the': [0, 31]}
assert search_patterns(text, patterns) == expected
def test_multiple_patterns():
text = 'the quick brown fox jumps over the lazy dog'
... | [
{
"docstring": "This function computes the partial match table (also known as the \"next\" table or \"failure function\")\nused in KMP algorithm.",
"function_declaration": "def compute_kmp_table(pattern):",
"function_name": "compute_kmp_table",
"parameter_list": "(pattern)"
},
{
"docstring":... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict\n\ndef search_patterns(text: str, patterns: List[str]) -> Dict[str, List[int]]:\n def compute_lps(pattern):\n lps = [0... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006532",
"row_id": 6532,
"seed_ids": "[93]"
} | 0.614576 | Data_Structure_6532 | I | [
"compute_kmp_table",
"kmp_search",
"search_patterns"
] | 3 | [
[
"kmp_search",
"compute_kmp_table"
],
[
"search_patterns",
"kmp_search"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 590a28e236045b3e7844be8de7cf2b26069756ce | 6e9bff61ab7c0473a74b02a203123d9b4969636a | |||
v1.0 | instruct | Data_Structure | Data_Structure_6570_I | You are required to implement a function that computes the transitive closure of a directed graph using Depth-First Search (DFS). The transitive closure of a graph is a reachability matrix where each entry (i, j) is True if there is a path from node i to node j (including itself), and False otherwise.
### Function Sig... | from typing import List, Tuple
def dfs(node: int, graph: List[List[int]], reachable: List[List[bool]], visited: List[bool], start: int):
"""
Perform DFS to mark all reachable nodes from the starting node.
"""
reachable[start][node] = True
visited[node] = True
for neighbor in graph[node]:
... | from solution import transitive_closure
def test_transitive_closure():
num_nodes = 4
edges = [(0, 1), (1, 2), (2, 3)]
expected_result = [
[True, True, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, False, True],
]
assert transitive... | [
{
"docstring": "Perform DFS to mark all reachable nodes from the starting node.",
"function_declaration": "def dfs(node, graph, reachable, visited, start):",
"function_name": "dfs",
"parameter_list": "(node, graph, reachable, visited, start)"
},
{
"docstring": "Computes the transitive closur... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef transitive_closure(num_nodes: int, edges: List[Tuple[int, int]]) -> List[List[bool]]:\n # Initialize the reachability... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006570",
"row_id": 6570,
"seed_ids": "[228]"
} | 0.558286 | Data_Structure_6570 | I | [
"dfs",
"transitive_closure"
] | 2 | [
[
"transitive_closure",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 591730eb72c844b4b01c506a87f5dd13027f9398 | 5f8d0964e45f999744bbb8911372ef7c5ad18566 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6572_I | ### Problem: Implementation of a Safe Bogo Sort
Bogo Sort is a highly impractical sorting algorithm due to its reliance on sheer luck to sort the array. Your task is to write a function that partially utilizes Bogo Sort principles but safely handles large datasets by allowing a maximum number of iterations. If the sort... | import random
def is_sorted(arr):
"""
Helper function to check if an array is sorted.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def safe_bogo_sort(arr, max_iterations, simulation=False):
"""
Partially utilizes Bogo Sort principle... | from solution import safe_bogo_sort
def test_safe_bogo_sort_sorted_array():
assert safe_bogo_sort([1, 2, 3, 4, 5], 1000) == [1, 2, 3, 4, 5]
def test_safe_bogo_sort_single_iteration():
# Known sorted array should return as is in first iteration
assert safe_bogo_sort([1, 2, 3, 4, 5], 1) == [1, 2, 3, 4, 5]
... | [
{
"docstring": "Helper function to check if an array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Partially utilizes Bogo Sort principles but safely handles large datasets by\nallowing a maximum number ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if an array is sorted.\n \"\"\"\n for i in range(len(arr) - 1):\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006572",
"row_id": 6572,
"seed_ids": "[16]"
} | 0.524588 | Data_Structure_6572 | I | [
"is_sorted",
"safe_bogo_sort"
] | 2 | [
[
"safe_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 97f373ba5914c5747971c7a9ab6d581b29b6a65d | 1983267d6dff54005344975dec3e82118b381d37 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6574_I | ### Context
You are developing a transportation network that requires ensuring maximum throughput from a starting point to a destination. By interpreting the capacity limits between multiple transportation hubs (nodes) represented by an adjacency matrix, your task is to calculate the maximum flow from the source node ... | 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 = [source]
visited[source] = True
while queue:
u = queue.pop(0)
for ind, val in enumerate(residual_graph[u]):
... | from solution import calculate_maximum_flow
def test_simple_case():
graph = [[0, 1], [0, 0]]
assert calculate_maximum_flow(graph) == 1
def test_sample_case():
graph = [[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
... | [
{
"docstring": null,
"function_declaration": "def bfs(residual_graph, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_graph, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def calculate_maximum_flow(adjacency_matrix):",
"function... | [
0,
0,
0,
1,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef calculate_maximum_flow(adjacency_matrix: List[List[int]]) -> int:\n \"\"\"\n Uses the Ford-Fulkerson method and BFS for f... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00006574",
"row_id": 6574,
"seed_ids": "[229]"
} | 0.628029 | Data_Structure_6574 | I | [
"bfs",
"calculate_maximum_flow"
] | 2 | [
[
"calculate_maximum_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bdb8bb6cf95cd955631cc62ef7366a561daa779f | 88750abbb1c464761f49710a13d64a359d02a07b | |||
v1.0 | instruct | Data_Structure | Data_Structure_6585_I | ### Question
You are given a training dataset of labeled N-dimensional points, and a single query point. Implement a function to classify the query point using the nearest neighbor algorithm as described above. Your implementation should read an input of N-dimensional points, compute the Euclidean distance, and return... | import math
def euclidean_distance(point1, point2):
"""
Calculates the Euclidean distance between two N-dimensional points.
Arguments:
point1 (tuple): The first point.
point2 (tuple): The second point.
Returns:
float: The Euclidean distance between the points.
"""
return m... | from solution import classify_query_point
def test_single_point_training_set():
query_point = (2, 3)
training_set = {(1, 2): 'ClassA'}
assert classify_query_point(query_point, training_set) == 'ClassA'
def test_multiple_points_training_set():
query_point = (2, 3)
training_set = {
(1, 2): '... | [
{
"docstring": "Calculates the Euclidean distance between two N-dimensional points.\n\nArguments:\npoint1 (tuple): The first point.\npoint2 (tuple): The second point.\n\nReturns:\nfloat: The Euclidean distance between the points.",
"function_declaration": "def euclidean_distance(point1, point2):",
"func... | [
0,
0,
0,
0,
1,
1,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Computes the Euclidean distance between two N-dimensional points.\n \"\"\"\n ret... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00006585",
"row_id": 6585,
"seed_ids": "[260]"
} | 0.675461 | Data_Structure_6585 | I | [
"euclidean_distance",
"classify_query_point"
] | 2 | [
[
"classify_query_point",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 73a9dc19ba88815b2d6a4a1a91fcea81ff2a5df7 | 3d31361d7a9f09f376cac53f4e1871c3fe8588ea | |||
v1.0 | instruct | Data_Structure | Data_Structure_6597_I | ### Question: Radix Sort Implementation Challenge
**Problem Statement**:
You are required to implement the Radix Sort algorithm from scratch. Radix Sort is an efficient, non-comparative sorting algorithm that sorts numbers based on individual digits. The algorithm uses a positional processing approach where it starts ... | def radix_sort(arr):
"""
Perform Radix Sort on a list of non-negative integers.
:param arr: List[int] - a list of non-negative integers
:return: List[int] - the sorted list
"""
if not arr:
return arr
# Find the maximum number to know the number of digits
max_num = max(arr)
e... | 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]
def test_radix_sort_with_duplicates():
assert radix_sort([3, 3, 1, 2]) == [1, 2, 3, 3]
def test_radix_sort_single_element():
assert radix_sort([42]) == [4... | [
{
"docstring": "Perform Radix Sort on a list of non-negative integers.\n:param arr: List[int] - a list of non-negative integers\n:return: List[int] - the sorted list",
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
},
{
"docstring": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def radix_sort(arr):\n \"\"\"\n Perform radix sort on a list of non-negative integers.\n \n Parameters:\n arr (List[int]): The list of non-nega... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006597",
"row_id": 6597,
"seed_ids": "[15]"
} | 0.625801 | Data_Structure_6597 | I | [
"radix_sort",
"counting_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6448047a4da9af12543f02ce1b4c929a27133cfe | fbcbb0e690608fd51769bd4f88ef4ce30130d6ed | |||
v1.0 | instruct | Data_Structure | Data_Structure_6606_I | ### Maximum Flow Problem in Social Network Connections
You are working on a project for a social media application where users can send messages to each other. The application server must handle the maximum possible flow of messages between users. Given the following algorithms to solve network flow problems and their... | from collections import deque
from typing import List
def bfs_level_graph(capacity: List[List[int]], source: int, sink: int, level: List[int]) -> bool:
n = len(capacity)
for i in range(n):
level[i] = -1
level[source] = 0
q = deque([source])
while q:
u = q.popleft()
for ... | from solution import compute_max_flow
def test_compute_max_flow_example1():
capacity = [
[0, 10, 0, 10, 0, 0],
[0, 0, 4, 2, 8, 0],
[0, 0, 0, 0, 0, 10],
[0, 0, 0, 0, 9, 0],
[0, 0, 6, 0, 0, 10],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert compute_ma... | [
{
"docstring": null,
"function_declaration": "def bfs_level_graph(capacity, source, sink, level):",
"function_name": "bfs_level_graph",
"parameter_list": "(capacity, source, sink, level)"
},
{
"docstring": null,
"function_declaration": "def dfs_flow(u, flow, sink, capacity, level, start)... | [
0,
0,
0,
1,
0,
1,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List\n\ndef bfs_level_graph(capacity, flow, source, sink):\n level = [-1] * len(capacity)\n level[sour... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00006606",
"row_id": 6606,
"seed_ids": "[240]"
} | 0.594783 | Data_Structure_6606 | I | [
"bfs_level_graph",
"dfs_flow",
"compute_max_flow"
] | 3 | [
[
"compute_max_flow",
"bfs_level_graph"
],
[
"compute_max_flow",
"dfs_flow"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 37208eb62e6ef1455c16d7f7eb6a2d2b9ae90971 | 695107837e579067108eb0e9ba344ba667892d9a | |||
v1.0 | instruct | Data_Structure | Data_Structure_6611_I | ### Problem: Enhanced Substring Search Using KMP
You are working on a text processing tool that requires efficient substring matching. To accomplish this, you will implement an optimized substring search algorithm using the Knuth-Morris-Pratt (KMP) algorithm. The task is to write a function that takes a text and a pat... | from typing import List
def kmp_prefix_function(pattern: str) -> List[int]:
"""
Computes the prefix function for KMP algorithm.
"""
prefix = [0] * len(pattern)
j = 0 # length of previous longest prefix suffix
i = 1
while i < len(pattern):
if pattern[i] == pattern[j]:
j ... | from solution import enhanced_kmp_search
def test_pattern_found_multiple_places():
assert enhanced_kmp_search("hello there hero!", "he") == [0, 7, 12]
def test_pattern_not_found():
assert enhanced_kmp_search("abcdef", "gh") == []
def test_empty_text_or_pattern():
assert enhanced_kmp_search("", "hi") == [... | [
{
"docstring": "Computes the prefix function for KMP algorithm.",
"function_declaration": "def kmp_prefix_function(pattern):",
"function_name": "kmp_prefix_function",
"parameter_list": "(pattern)"
},
{
"docstring": "Searches for all occurrences of the pattern in the text using KMP algorithm.... | [
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 kmp_prefix_function(pattern: str) -> List[int]:\n \"\"\"\n Computes the prefix function for KMP algorithm.\n \"\"\"\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006611",
"row_id": 6611,
"seed_ids": "[93]"
} | 0.609335 | Data_Structure_6611 | I | [
"kmp_prefix_function",
"enhanced_kmp_search"
] | 2 | [
[
"enhanced_kmp_search",
"kmp_prefix_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 97ed61fd4b3c92c86fbaa19fc3935ee163b436e0 | 62f804d912ff3465a2c7cbc2a4d0bafa44e93a03 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6621_I | Sum of Digit Lengths of an Array
You are given an array of integers, and your task is to write a function that returns the sum of the number of digits of all the integers in the array.
#### Function Signature
```python
def sum_digit_lengths(arr: List[int]) -> int:
```
#### Input
- `arr`: A list of integers. Example:... | from typing import List
def num_digits(n: int) -> int:
"""
Returns the number of digits in an integer n.
For negative numbers, the '-' sign is not counted.
"""
return len(str(abs(n)))
def sum_digit_lengths(arr: List[int]) -> int:
"""
Returns the sum of the number of digits of all the inte... | from solution import sum_digit_lengths
def test_positive_numbers():
assert sum_digit_lengths([123, 4, 56789]) == 9 # 3 + 1 + 5 = 9
def test_negative_numbers():
assert sum_digit_lengths([-123, -4, -56789]) == 9 # 3 + 1 + 5 = 9 (negative sign ignored)
def test_mixed_numbers():
assert sum_digit_lengths([1... | [
{
"docstring": "Returns the number of digits in an integer n. \nFor negative numbers, the '-' sign is not counted.",
"function_declaration": "def num_digits(n):",
"function_name": "num_digits",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of the number of digits of all the inte... | [
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 num_digits(n: int) -> int:\n \"\"\"\n Returns the number of digits in an integer n. \n For negative numbers, the '-' s... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006621",
"row_id": 6621,
"seed_ids": "[144]"
} | 0.762606 | Data_Structure_6621 | I | [
"num_digits",
"sum_digit_lengths"
] | 2 | [
[
"sum_digit_lengths",
"num_digits"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 39d1257457b4db3adc9b3b37aa6f347e6e005a44 | 86cd3905a3dff36565ece900ddb07a6b7a26c8a4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6624_I | Given two binary trees, `big` and `small`, write a function that checks if `small` is a subtree of `big`. A subtree of a tree `T` is a tree consisting of a node in `T` and all of its descendants in `T`.
#### Function Signature
```python
def is_subtree(big: TreeNode, small: TreeNode) -> bool:
```
### Input Format
* `b... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_subtree(big: TreeNode, small: TreeNode) -> bool:
if not small:
return True
if not big:
return False
if is_identical(big, small):
return True
return... | import pytest
from solution import TreeNode, is_subtree
def test_case_1():
"""
big:
3
/ \
4 5
/ \
1 2
small:
4
/ \
1 2
Output should be True
"""
big = TreeNode(3)
big.left = TreeNode(4)
big.right = TreeNode(5)
big.left.le... | [] | [
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 is_subtree(big: TreeNode... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006624",
"row_id": 6624,
"seed_ids": "[288]"
} | 0.514057 | Data_Structure_6624 | I | [
"is_subtree",
"is_identical"
] | 2 | [
[
"is_subtree",
"is_identical"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 43740d4e6f4563c7418606e18c9bece25ebe8c04 | 3678e1cd3a53cf75cacf8152e861abfee8b5f595 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6661_I | ### Advanced Matrix Question
You are required to implement matrix multiplication and matrix exponentiation efficiently for solving a problem in computer graphics transformations.
#### Problem Statement:
You are given two essential functions:
1. `multiply(matA: list, matB: list) -> list`: Multiplies two matrices A an... | def multiply(matA, matB):
"""
Multiplies two 2x2 matrices.
"""
return [
[
matA[0][0] * matB[0][0] + matA[0][1] * matB[1][0],
matA[0][0] * matB[0][1] + matA[0][1] * matB[1][1]
],
[
matA[1][0] * matB[0][0] + matA[1][1] * matB[1][0],
m... | def test_multiply():
matA = [[1, 2], [3, 4]]
matB = [[2, 0], [1, 2]]
expected = [[4, 4], [10, 8]]
assert multiply(matA, matB) == expected
def test_identity():
expected = [[1, 0], [0, 1]]
assert identity(2) == expected
def test_matrix_exponentiation():
mat = [[2, 0], [0, 2]]
power = 3
... | [
{
"docstring": "Multiplies two 2x2 matrices.",
"function_declaration": "def multiply(matA, matB):",
"function_name": "multiply",
"parameter_list": "(matA, matB)"
},
{
"docstring": "Creates an identity matrix of size n x n.",
"function_declaration": "def identity(n):",
"function_name"... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply(matA, matB):\n \"\"\"\n Multiplies two 2x2 matrices.\n \"\"\"\n return [\n [matA[0][0]*matB[0][0] + matA[0][1]*matB[1][0], mat... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006661",
"row_id": 6661,
"seed_ids": "[340]"
} | 0.506113 | Data_Structure_6661 | I | [
"multiply",
"identity",
"matrix_exponentiation",
"transform_point"
] | 4 | [
[
"matrix_exponentiation",
"identity"
],
[
"matrix_exponentiation",
"multiply"
],
[
"transform_point",
"matrix_exponentiation"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 56bd74d6c7195e273104f177f3af9cd778163a87 | e4c58c320178ec7e21d6a4714b48466169b01d44 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6702_I | ### Question: Refactored Insertion Sort with Binary Insertion
You are asked to optimize the insertion sort algorithm by reducing the number of comparisons while finding the position to insert the current element. Implement this by using binary search to determine the correct insertion position.
#### Function Signatur... | def binary_search(arr, val, start, end):
"""
Helper function to perform binary search on the sorted part of the array.
"""
if start == end:
if arr[start] > val:
return start
else:
return start + 1
elif start > end:
return start
mid = (start + end)... | from solution import binary_insertion_sort
def test_binary_insertion_sort_with_integers():
assert binary_insertion_sort([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13]
def test_binary_insertion_sort_with_strings():
assert binary_insertion_sort(['banana', 'apple', 'cherry', 'date']) == ['apple', 'banana', 'cherry', ... | [
{
"docstring": "Helper function to perform binary search on the sorted part of the array.",
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "Sorts the input list using an optimi... | [
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 index at which val should be inserted.\n \"\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006702",
"row_id": 6702,
"seed_ids": "[7]"
} | 0.551673 | Data_Structure_6702 | I | [
"binary_search",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 603ad1758deaf64708ae54aa11ee17e988b8392a | b5d79a7200b57cb10bb216351ddf78e11c6f8111 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6706_I | **Scenario**:
You are working for a company that provides search functionality for a large text repository. Your task is to optimize the search operations by implementing the Knuth-Morris-Pratt (KMP) algorithm. Your solution should efficiently find all occurrences of a given pattern in a text, regardless of its size.
... | from typing import List
def kmp_prefix_function(pattern: str) -> List[int]:
"""
Builds the prefix function for the KMP algorithm.
"""
m = len(pattern)
prefix = [0] * m
j = 0
for i in range(1, m):
while j > 0 and pattern[i] != pattern[j]:
j = prefix[j - 1]
if... | from solution import search_pattern
def test_search_pattern_basic():
assert search_pattern("hello there hero!", "he") == [0, 7, 12]
assert search_pattern("aaaaa", "aa") == [0, 1, 2, 3]
assert search_pattern("abcdef", "gh") == []
def test_search_pattern_empty_text():
assert search_pattern("", "pat") ==... | [
{
"docstring": "Builds the prefix function for the KMP algorithm.",
"function_declaration": "def kmp_prefix_function(pattern):",
"function_name": "kmp_prefix_function",
"parameter_list": "(pattern)"
},
{
"docstring": "Uses the KMP algorithm to find all occurrences of the pattern in the text.... | [
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 kmp_partial_match_table(pattern: str) -> List[int]:\n \"\"\"\n Generate the partial match table (also known as the \"pref... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006706",
"row_id": 6706,
"seed_ids": "[93]"
} | 0.534613 | Data_Structure_6706 | I | [
"kmp_prefix_function",
"search_pattern"
] | 2 | [
[
"search_pattern",
"kmp_prefix_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ca02093886f50d91885dd7185c278863fecd880b | db30e454004d9b95225558a3b2a2a84679faa7a0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6720_I | Implement a Secure Communication Setup Using Diffie-Hellman Key Exchange
As a cybersecurity student, you are tasked with implementing a secure communication setup using the Diffie-Hellman key exchange protocol. This will involve several steps where you incorporate checks and additional functionalities to ensure a robu... | import math
from typing import List
def is_prime(num: int) -> bool:
"""
Check if a number is a prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (... | from solution import is_prime, find_order, euler_totient, find_primitive_root, diffie_hellman_key_exchange
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(29) == True
assert is_prime(30) == False
def test_find_order():
asse... | [
{
"docstring": "Check if a number is a prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Find the order of a number 'a' modulo 'n'.",
"function_declaration": "def find_order(a, n):",
"function_name": "find... | [
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": "import math\nfrom typing import List\n\ndef is_prime(num: int) -> bool:\n \"\"\" Check if the input number is a prime number. \"\"\"\n if num <= 1:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00006720",
"row_id": 6720,
"seed_ids": "[146]"
} | 0.523895 | Data_Structure_6720 | I | [
"is_prime",
"find_order",
"euler_totient",
"find_primitive_root",
"diffie_hellman_key_exchange"
] | 5 | [
[
"diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"diffie_hellman_key_exchange",
"is_prime"
],
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"is_prime"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 4a92b2e586ffc9d5f83d2e555ae836553fb1dbdf | e1179a8527d161095a4415b188c8a4410851ac30 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6746_I | Enhanced GCD Function with Improved Error Handling
As a programmer, you are asked to implement an enhanced version of the `gcd` and `lcm` functions that not only compute the greatest common divisor and least common multiple of two integers but also handle various edge cases and error scenarios gracefully.
### Problem... | def enhanced_gcd(a, b):
"""
Compute the greatest common divisor of integers a and b using the Euclidean Algorithm.
Raises a ValueError for invalid inputs.
Parameters:
a (int): First integer
b (int): Second integer
Returns:
int: GCD of a and b
"""
if not isinstance(a, in... | from solution import enhanced_gcd, enhanced_lcm
import pytest
def test_enhanced_gcd_positive():
assert enhanced_gcd(54, 24) == 6
def test_enhanced_gcd_negative():
assert enhanced_gcd(-54, 24) == 6
assert enhanced_gcd(54, -24) == 6
assert enhanced_gcd(-54, -24) == 6
def test_enhanced_gcd_prime_numbers... | [
{
"docstring": "Compute the greatest common divisor of integers a and b using the Euclidean Algorithm.\nRaises a ValueError for invalid inputs.\n\nParameters:\na (int): First integer\nb (int): Second integer\n\nReturns:\nint: GCD of a and b",
"function_declaration": "def enhanced_gcd(a, b):",
"function_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_gcd(a, b):\n \"\"\"\n Computes the greatest common divisor of integers `a` and `b` using the Euclidean Algorithm.\n Raises a ValueError ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006746",
"row_id": 6746,
"seed_ids": "[166]"
} | 0.70481 | Data_Structure_6746 | I | [
"enhanced_gcd",
"enhanced_lcm"
] | 2 | [
[
"enhanced_lcm",
"enhanced_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b9d47f79fa59f92df42610170c188b86dc336bf3 | 10e9b42bb7b6c5e779c92136541af0f06811c3da | |||
v1.0 | instruct | Data_Structure | Data_Structure_6760_I | ### Context:
In cryptographic protocols, secure key exchange over a public network is essential. The Diffie-Hellman key exchange method enables two parties to securely share a common secret key even if they don't know each other. This shared secret can then be used to encrypt subsequent communications.
As part of this... | def is_prime(n):
"""
Determines if n is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
retu... | from solution import is_prime, order, euler_totient, primitive_roots, diffie_hellman
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
def test_order():
assert order(2, 7) == 3
ass... | [
{
"docstring": "Determines if n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Computes the order of a modulo n.",
"function_declaration": "def order(a, n):",
"function_name": "order",
"para... | [
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 functools import reduce\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Determine if n is a prime number.\n \"\"\"\n if n <= 1:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006760",
"row_id": 6760,
"seed_ids": "[146]"
} | 0.470619 | Data_Structure_6760 | I | [
"is_prime",
"order",
"euler_totient",
"primitive_roots",
"diffie_hellman"
] | 5 | [
[
"diffie_hellman",
"is_prime"
],
[
"diffie_hellman",
"primitive_roots"
],
[
"order",
"is_prime"
],
[
"primitive_roots",
"euler_totient"
],
[
"primitive_roots",
"is_prime"
],
[
"primitive_roots",
"order"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | 8360a315e65fecba459d1ab54e7a6b75c105669f | 7962237a6098d56622dd9de5b02b49bd66a3399d | |||
v1.0 | instruct | Data_Structure | Data_Structure_6843_I | ### Diffie-Hellman Key Exchange Implementation
In this assessment, you will implement the Diffie-Hellman Key Exchange algorithm to demonstrate your understanding of both cryptographic principles and Python programming.
### Task
1. Implement a function `generate_prime_candidates(start, end)` that generates a list of p... | def prime_check(n):
""" Returns True if n is a prime number, otherwise False """
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 ... | from solution import generate_prime_candidates, key_exchange, prime_check
def test_prime_check():
assert prime_check(2) == True
assert prime_check(3) == True
assert prime_check(4) == False
assert prime_check(29) == True
assert prime_check(30) == False
def test_generate_prime_candidates():
asse... | [
{
"docstring": "Returns True if n is a prime number, otherwise False ",
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": "Generates a list of prime numbers within a given range [start, end).",
"function_declaration":... | [
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 prime_check(num):\n \"\"\"\n Given a number, return True if it's prime, else False.\n \"\"\"\n if num <= 1:\n return False\n if num ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006843",
"row_id": 6843,
"seed_ids": "[146]"
} | 0.573405 | Data_Structure_6843 | I | [
"prime_check",
"generate_prime_candidates",
"key_exchange"
] | 3 | [
[
"generate_prime_candidates",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | de601d496a92c193d87b5076c69f7f86d286f270 | 6f6968229317cba07f1b770f0fb96bd0d48d635b | |||
v1.0 | instruct | Data_Structure | Data_Structure_6862_I | ### Question
Implement a function `enhanced_euler_totient(n)` which computes the Euler's Totient Function in an optimized manner. Specifically, your solution should preprocess prime numbers up to √n to speed up the multiple calls to the function.
#### Function Signature
```python
def enhanced_euler_totient(n: int) -> ... | def enhanced_euler_totient(n: int) -> int:
"""
Computes Euler's Totient Function in an optimized manner.
"""
if n == 1:
return 1
# Initialize result as n
result = n
# Create a list to store prime numbers up to √n
primes = sieve(int(n**0.5) + 1)
# Check divisibility by pri... | from solution import enhanced_euler_totient
def test_enhanced_euler_totient_basic():
assert enhanced_euler_totient(9) == 6
assert enhanced_euler_totient(1) == 1
assert enhanced_euler_totient(6) == 2
def test_enhanced_euler_totient_large():
assert enhanced_euler_totient(10**7) > 0 # Ensure it does not... | [
{
"docstring": "Computes Euler's Totient Function in an optimized manner.",
"function_declaration": "def enhanced_euler_totient(n):",
"function_name": "enhanced_euler_totient",
"parameter_list": "(n)"
},
{
"docstring": "Helper function to create a list of primes up to limit using Sieve of Er... | [
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 sieve_of_eratosthenes(max_value):\n is_prime = [True] * (max_value + 1)\n is_prime[0] = is_prime[1] = False\n prime_list = []\n\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006862",
"row_id": 6862,
"seed_ids": "[141]"
} | 0.533148 | Data_Structure_6862 | I | [
"enhanced_euler_totient",
"sieve"
] | 2 | [
[
"enhanced_euler_totient",
"sieve"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 92182a0e458b67914adb4c2a6bc9dc3afcf06656 | 2e3d6e303b957788cfffc92e8651456d12b767b0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6870_I | You are given the task of implementing a search feature for a large corpus of text documents. The feature should efficiently find all occurrences of a specified pattern within a given text and return the starting indices of each match.
### Objective
Write a function `search_pattern` that implements the Knuth-Morris-P... | from typing import List
def compute_lps(pattern: str) -> List[int]:
"""
Computes the Longest Prefix Suffix (LPS) array using the given pattern.
The LPS array is used to skip characters while matching the pattern in the text.
"""
lps = [0] * len(pattern)
length = 0
i = 1
while i < l... | from solution import search_pattern
def test_search_pattern_example1():
assert search_pattern('abracadabra', 'abra') == [0, 7]
def test_search_pattern_example2():
assert search_pattern('aabaaabaaac', 'aabaaac') == [4]
def test_search_pattern_example3():
assert search_pattern('hello', 'world') == []
def ... | [
{
"docstring": "Computes the Longest Prefix Suffix (LPS) array using the given pattern.\nThe LPS array is used to skip characters while matching the pattern in the text.",
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
... | [
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef compute_lps(pattern: str) -> List[int]:\n \"\"\"\n Helper function to preprocess the pattern by ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00006870",
"row_id": 6870,
"seed_ids": "[93]"
} | 0.539243 | Data_Structure_6870 | I | [
"compute_lps",
"search_pattern"
] | 2 | [
[
"search_pattern",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a0c2da0c75e8ec606b11288059f5bf55d199f741 | ba9c610552120bdeabdd4669e1e05177727f588c | |||
v1.0 | instruct | Data_Structure | Data_Structure_6882_I | You are tasked with simulating a Markov chain using the provided Probabilistic Model implementation. Given a Markov chain represented as a dictionary and an initial state, you are to extend the current implementation to include methods for:
1. **Validating the Markov Chain**: Ensure that the provided chain is valid, i... | import random
def validate_markov_chain(chain):
"""
Validates the given Markov chain dictionary.
Parameters:
- chain (dict): A dictionary representing the Markov chain.
Returns:
- bool: True if the chain is valid, False otherwise.
"""
for state, transitions in chain.items():
... | import pytest
from solution import validate_markov_chain, generate_sequence
def test_validate_markov_chain():
chain_valid = {
'A': {'A': 0.6, 'E': 0.4},
'E': {'A': 0.7, 'E': 0.3}
}
chain_invalid = {
'A': {'A': 0.5, 'E': 0.4},
'E': {'A': 0.7, 'E': 0.3}
}
ass... | [
{
"docstring": "Validates the given Markov chain dictionary.\n\nParameters:\n- chain (dict): A dictionary representing the Markov chain.\n\nReturns:\n- bool: True if the chain is valid, False otherwise.",
"function_declaration": "def validate_markov_chain(chain):",
"function_name": "validate_markov_chai... | [
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 validate_markov_chain(chain):\n \"\"\"\n Validates the given Markov chain.\n \n Parameters:\n chain (dict): A dictionary r... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006882",
"row_id": 6882,
"seed_ids": "[232]"
} | 0.436022 | Data_Structure_6882 | I | [
"validate_markov_chain",
"generate_sequence",
"next_state",
"__choose_state"
] | 4 | [
[
"generate_sequence",
"next_state"
],
[
"next_state",
"__choose_state"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 18c9ea9f1df4c8e6f6ac23bcc136ca0a0db6b113 | ae7fd3b672590310ec9adb38dddbd389b4fc479a | |||
v1.0 | instruct | Data_Structure | Data_Structure_6915_I | ### Bucket Sort Implementation and Optimization
#### Context:
You are given an array of non-negative integers. Your task is to implement the bucket sort algorithm to sort the array. Bucket sort works by distributing the elements of an array into several buckets. Each bucket is then sorted individually using another so... | def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
def bucket_sort(arr):
if len(arr) == 0... | from solution import bucket_sort
def test_bucket_sort_empty_array():
assert bucket_sort([]) == []
def test_bucket_sort_single_element_array():
assert bucket_sort([1]) == [1]
def test_bucket_sort_all_same_elements():
assert bucket_sort([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5]
def test_bucket_sort_already_sort... | [
{
"docstring": null,
"function_declaration": "def quick_sort(arr):",
"function_name": "quick_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def bucket_sort(arr):",
"function_name": "bucket_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) > 1:\n mid = len(arr) // 2\n left_half = arr[:mid]\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006915",
"row_id": 6915,
"seed_ids": "[26]"
} | 0.579846 | Data_Structure_6915 | I | [
"quick_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"quick_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b414cf4ad93b5511a5ac107c1b99a887c3b17740 | 46aa15bd8c94bdecd1d13c9265db5ec40bd90455 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6946_I | <|Analysis Begin|>
### Algorithm Analysis
#### Core Identification
- **Algorithm/Data Structure**:
- **Algorithm 1**: GCD (Greatest Common Divisor) using Euclid’s Algorithm.
- **Algorithm 2**: LCM (Least Common Multiple).
- **Algorithm 3**: Counting Trailing Zeroes in Integer’s Binary Representation.
- **Alg... | def gcd(a, b):
"""
Helper function to calculate the greatest common divisor (GCD) using Euclid's Algorithm.
"""
while b:
a, b = b, a % b
return abs(a)
def efficient_lcm(a, b):
"""
Calculate and return the Least Common Multiple (LCM) of two non-zero integers a and b.
"""
# Ca... | from solution import efficient_lcm
def test_lcm_positive_numbers():
assert efficient_lcm(12, 18) == 36
assert efficient_lcm(4, 5) == 20
def test_lcm_negative_positive_numbers():
assert efficient_lcm(-4, 5) == 20
assert efficient_lcm(6, -8) == 24
def test_lcm_both_negative_numbers():
assert effici... | [
{
"docstring": "Helper function to calculate the greatest common divisor (GCD) using Euclid's Algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate and return the Least Common Multiple (LCM) of two non-zero inte... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef efficient_lcm(a: int, b: int) -> int:\n \"\"\"\n Returns the Least Common Multiple (LCM) of two non-zero integers.\n \"\"\"\n r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006946",
"row_id": 6946,
"seed_ids": "[166]"
} | 0.55547 | Data_Structure_6946 | I | [
"gcd",
"efficient_lcm"
] | 2 | [
[
"efficient_lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2130cd72063d16e3a80b748d1a7253a5597e0a90 | 187b317df66441eca45569471bb6f0228c96dbe3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_6993_I | You are given an array of integers, and you must implement a sorting algorithm using heap sort in Python. You need to implement both Max Heap Sort and Min Heap Sort functions that sort the array in ascending order.
### Function Signature:
```python
def max_heap_sort(arr: List[int], simulation: bool=False) -> List[int]... | from typing import List
def max_heapify(arr, n, i, simulation):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[i] < arr[left]:
largest = left
if right < n and arr[largest] < arr[right]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[la... | from solution import max_heap_sort, min_heap_sort
def test_max_heap_sort():
assert max_heap_sort([3, 2, 1, 5, 4]) == [1, 2, 3, 4, 5]
assert max_heap_sort([0, -1, 3, 2, 4]) == [-1, 0, 2, 3, 4]
assert max_heap_sort([]) == []
assert max_heap_sort([5]) == [5]
assert max_heap_sort([5, 5, 5, 5, 5]) == [5... | [
{
"docstring": null,
"function_declaration": "def max_heapify(arr, n, i, simulation):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i, simulation)"
},
{
"docstring": null,
"function_declaration": "def max_heap_sort(arr, simulation=False):",
"function_name": "max_heap_... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef max_heapify(arr, n, i, simulation):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n and arr[le... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00006993",
"row_id": 6993,
"seed_ids": "[8]"
} | 0.706261 | Data_Structure_6993 | I | [
"max_heapify",
"max_heap_sort",
"min_heapify",
"min_heap_sort"
] | 4 | [
[
"max_heap_sort",
"max_heapify"
],
[
"min_heap_sort",
"min_heapify"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ba36a2f142f83071ad21bda2921540a5ea39b4a9 | 02796a14857c2e2fe3bb23b97b66efd05bc6a05e | |||
v1.0 | instruct | Data_Structure | Data_Structure_6994_I | ### Question Description
You are given two binary trees, s and t, represented as instances of a TreeNode class. Your task is to implement a function `is_subtree(s: TreeNode, t: TreeNode) -> bool` that checks if t is a subtree of s. A subtree of a tree t is defined as a tree consisting of a node in t and all of its desc... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
if not t:
return True # An empty tree t is always a subtree
if not s:
return False # If s is empty, t cannot be a subtree of s
... | from solution import TreeNode, is_subtree
def test_is_subtree_true():
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.left.right = TreeNode(2)
t = TreeNode(4)
t.left = TreeNode(1)
t.right = TreeNode(2)
assert is_subtree(s, t) == True
... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef is_same_tree(s: TreeNode, t: Tre... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006994",
"row_id": 6994,
"seed_ids": "[288]"
} | 0.568672 | Data_Structure_6994 | I | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | c0fd90e8d064e8bd1bc465a6f178582989820650 | 04614b15c64de8d3852724e99de90fb43400fcf2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7011_I | ### Merging Intervals and Finding Non-overlapping Intervals
**Objective:**
Design a Python function to merge overlapping intervals and another to find intervals that do not overlap with any in a given list of intervals.
**Background:**
In calendar systems, reservation platforms, or any scheduling software, overlapp... | def interval_merge(intervals):
"""
Merges overlapping intervals.
"""
if not intervals:
return []
# Sort intervals based on the start time
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
# if merged list is empty or last interval in merged d... | from solution import interval_merge, non_overlapping_intervals
def test_interval_merge():
assert interval_merge([]) == []
assert interval_merge([(1, 3)]) == [(1, 3)]
assert interval_merge([(1, 3), (2, 4), (5, 7)]) == [(1, 4), (5, 7)]
assert interval_merge([(1, 5), (2, 3), (3, 4)]) == [(1, 5)]
asser... | [
{
"docstring": "Merges overlapping intervals.",
"function_declaration": "def interval_merge(intervals):",
"function_name": "interval_merge",
"parameter_list": "(intervals)"
},
{
"docstring": "Finds candidate intervals that do not overlap with any of the main intervals.",
"function_declar... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef interval_merge(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]] :\n if not intervals:\n return []\n\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007011",
"row_id": 7011,
"seed_ids": "[285]"
} | 0.6669 | Data_Structure_7011 | I | [
"interval_merge",
"non_overlapping_intervals"
] | 2 | [
[
"non_overlapping_intervals",
"interval_merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2636c9170a434ecbcf1d82fc9d5d31ae483db6b5 | 5648d57dafa5c3fdb8725fe38cc183396554e614 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7023_I | You are given two integers `a` and `b`. Your task is to implement the extended Euclidean algorithm to find integers `s` and `t` such that `a * s + b * t = GCD(a, b)`, and also to find the modular inverse of `a` under modulus `b` when they are co-prime.
### Function Signature
```python
def extended_gcd(a: int, b: int) ... | def extended_gcd(a: int, b: int) -> (int, int, int):
"""
Extended Euclidean Algorithm to find integers s and t such that:
a * s + b * t = gcd(a, b)
"""
if b == 0:
return (1, 0, a)
else:
x1, y1, g = extended_gcd(b, a % b)
return (y1, x1 - (a // b) * y1, g)
def modular_inv... | from solution import extended_gcd, modular_inverse
def test_extended_gcd():
assert extended_gcd(30, 20) == (1, -1, 10)
assert extended_gcd(10, 15) == (-1, 1, 5)
assert extended_gcd(101, 10) == (1, -10, 1)
assert extended_gcd(0, 5) == (0, 1, 5)
assert extended_gcd(5, 0) == (1, 0, 5)
def test_modula... | [
{
"docstring": "Extended Euclidean Algorithm to find integers s and t such that:\na * s + b * t = gcd(a, b)",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Find the modular inverse of a under modulus b, assum... | [
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 Greatest Common Divisor of a and b, along with\n coefficients for the equation a * s + b * t = gcd(a,... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007023",
"row_id": 7023,
"seed_ids": "[161]"
} | 0.654461 | Data_Structure_7023 | I | [
"extended_gcd",
"modular_inverse"
] | 2 | [
[
"modular_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7e5108745f7cc0ac8870ff954d703e8654b99cdf | a256f840c13dcdf2cfb1176faaa55d113d951918 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7050_I | ## Prime Sequence Analysis
In this coding challenge, you will implement a function that checks a sequence of numbers and identifies ranges where all the numbers are prime. This test assesses your ability to work with the prime checking algorithm and apply it to sequences of numbers.
### Problem Statement
Write a fun... | from typing import List, Tuple
def is_prime(n: int) -> bool:
"""
Determines if a given number n is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i... | import pytest
from solution import find_prime_ranges
def test_find_prime_ranges_single_prime():
assert find_prime_ranges([11]) == [(11, 12)]
def test_find_prime_ranges_mixed_primes_and_non_primes():
assert find_prime_ranges([11, 4, 7, 15, 2, 3]) == [(11, 12), (7, 8), (2, 3), (3, 4)]
def test_find_prime_range... | [
{
"docstring": "Determines if a given number n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Finds and returns ranges of consecutive prime numbers in the given sequence.",
"function_declaration": "... | [
0,
0,
0,
0,
0,
0,
1,
1,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport math\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Checks if a number is prime.\n \"\"\"\n if n <= 1:\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00007050",
"row_id": 7050,
"seed_ids": "[143]"
} | 0.640659 | Data_Structure_7050 | I | [
"is_prime",
"find_prime_ranges"
] | 2 | [
[
"find_prime_ranges",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c16db2b12534fe68c205f2b4ecb1ff8bda9e5059 | 178011082326767f12d718e12153eb6b00f661db | |||
v1.0 | instruct | Data_Structure | Data_Structure_7051_I | Substring Search Enhancement
In this task, you are required to enhance the performance of the given substring search algorithm. The existing algorithm uses a simple linear search that results in an O(n*m) time complexity, which can be inefficient for larger texts and patterns. Your objective is to implement the Knuth-... | def compute_prefix_function(needle):
m = len(needle)
lps = [0] * m
length = 0
i = 1
while i < m:
if needle[i] == needle[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
... | from solution import contain_string_kmp
def test_haystack_contains_needle():
assert contain_string_kmp("hello", "ll") == 2
def test_haystack_does_not_contain_needle():
assert contain_string_kmp("aaaaa", "bba") == -1
def test_empty_haystack_and_needle():
assert contain_string_kmp("", "") == 0
def test_ha... | [
{
"docstring": null,
"function_declaration": "def compute_prefix_function(needle):",
"function_name": "compute_prefix_function",
"parameter_list": "(needle)"
},
{
"docstring": null,
"function_declaration": "def contain_string_kmp(haystack, needle):",
"function_name": "contain_string_... | [
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 create_prefix_table(pattern):\n \"\"\"\n Create prefix table for the given pattern.\n \"\"\"\n prefix_table = [0] * len(pattern)\n j = 0\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007051",
"row_id": 7051,
"seed_ids": "[86]"
} | 0.66036 | Data_Structure_7051 | I | [
"compute_prefix_function",
"contain_string_kmp"
] | 2 | [
[
"contain_string_kmp",
"compute_prefix_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9bdae3a207ff148ea3b9a469dd9e06befba62b3f | ac4b60bad06211c3bc0a0a40c60fc18c6dcab008 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7057_I | You are provided with functions `max_heap_sort` and `min_heap_sort` that sort an array in ascending order using heap sort with a max-heap and min-heap, respectively.
You need to implement a function `smart_heap_sort` that dynamically selects between `max_heap_sort` and `min_heap_sort` based on the characteristics of t... | import statistics
def max_heap_sort(arr: list[int]) -> list[int]:
"""
Sorts a list in ascending order using heap sort with a max-heap.
Placeholder function.
"""
import heapq
# Convert array to a max heap by negating all values and using heapq which is a min-heap.
neg_arr = [-a for a in arr]... | from solution import smart_heap_sort, max_heap_sort, min_heap_sort
def test_smart_heap_sort_empty():
assert smart_heap_sort([]) == []
def test_smart_heap_sort_same_elements():
assert smart_heap_sort([5, 5, 5, 5]) == [5, 5, 5, 5]
def test_smart_heap_sort_max_heap_selection():
assert smart_heap_sort([4, 1,... | [
{
"docstring": "Sorts a list in ascending order using heap sort with a max-heap.\nPlaceholder function.",
"function_declaration": "def max_heap_sort(arr):",
"function_name": "max_heap_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts a list in ascending order using heap sort with a m... | [
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 heapq\nfrom statistics import median, mean\n\ndef max_heap_sort(arr):\n # Sort using a max heap\n arr = [-x for x in arr]\n heapq.heapify(arr)... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007057",
"row_id": 7057,
"seed_ids": "[8]"
} | 0.615205 | Data_Structure_7057 | I | [
"max_heap_sort",
"min_heap_sort",
"smart_heap_sort"
] | 3 | [
[
"smart_heap_sort",
"max_heap_sort"
],
[
"smart_heap_sort",
"min_heap_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 84de618da04a652058fac6b74a7d1c8b4dfbf21c | 6b781a1bfdcfcbc14135beb4d8d1b110feefcd60 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7098_I | You are given two algorithms: one that computes the Euler's Totient Function (ϕ(n)) and another that finds all primitive roots of a given integer \( n \). Your task is to extend this functionality by writing a function that integrates both algorithms to solve the following problem:
#### Problem Statement
Write a funct... | def gcd(a, b):
"""
Helper function to calculate the greatest common divisor (GCD) of two numbers.
"""
while b:
a, b = b, a % b
return a
def euler_totient(n):
"""
Function to compute Euler's Totient function, φ(n).
"""
result = n # Initialize result as n
p = 2
while... | from solution import is_primitive_root
def test_is_primitive_root_example1():
assert is_primitive_root(2, 5) == True
def test_is_primitive_root_example2():
assert is_primitive_root(3, 7) == True
def test_is_primitive_root_example3():
assert is_primitive_root(2, 8) == False
def test_is_primitive_root_cop... | [
{
"docstring": "Helper function to calculate the greatest common divisor (GCD) of two numbers.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Function to compute Euler's Totient function, φ(n).",
"function_declaration": "... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef euler_totient(n):\n result = n\n p = 2\n while p * p <= n:\n if n %... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00007098",
"row_id": 7098,
"seed_ids": "[160]"
} | 0.489265 | Data_Structure_7098 | I | [
"gcd",
"euler_totient",
"is_primitive_root"
] | 3 | [
[
"is_primitive_root",
"euler_totient"
],
[
"is_primitive_root",
"gcd"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4d558ff901ae87dc399d1643b4e1daab93595732 | 951aa3ff38326061c90a3265b42052d19c04624e | |||
v1.0 | instruct | Data_Structure | Data_Structure_7188_I | Sparse Vector Representation and Operations
#### Scenario
You are given a large dataset represented by high-dimensional vectors. Most elements in these vectors are zeros, making direct computation costly in terms of space and time. To optimize performance, you would use sparse representations.
#### Task
Write a Pytho... | import math
def vector_to_index_value_list(vector):
"""
Convert a full vector to its sparse representation using an index-value list.
"""
return [(index, value) for index, value in enumerate(vector) if value != 0]
def dot_product(iv_list1, iv_list2):
"""
Compute the dot product between two spa... | from solution import vector_to_index_value_list, dot_product, magnitude, cosine_similarity
def test_vector_to_index_value_list():
assert vector_to_index_value_list([0.0, 1.0, 0.0, 2.0]) == [(1, 1.0), (3, 2.0)]
assert vector_to_index_value_list([0.0, 0.0, 0.0, 0.0]) == []
assert vector_to_index_value_list([... | [
{
"docstring": "Convert a full vector to its sparse representation using an index-value list.",
"function_declaration": "def vector_to_index_value_list(vector):",
"function_name": "vector_to_index_value_list",
"parameter_list": "(vector)"
},
{
"docstring": "Compute the dot product between tw... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef vector_to_index_value_list(vector):\n \"\"\"\n Converts a full vector to its sparse representation in the form of an index-value list... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007188",
"row_id": 7188,
"seed_ids": "[341]"
} | 0.498321 | Data_Structure_7188 | I | [
"vector_to_index_value_list",
"dot_product",
"magnitude",
"cosine_similarity"
] | 4 | [
[
"cosine_similarity",
"dot_product"
],
[
"cosine_similarity",
"magnitude"
],
[
"cosine_similarity",
"vector_to_index_value_list"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 8c4d91eb8ef26e56142013e10741e868299f15c8 | 3c82a8325aea8f4116301b51a9e8cfb1fc485290 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7199_I | ### Full Binary Tree Reconstruction
Given two arrays representing the preorder and postorder traversal of a full binary tree, your task is to construct the full binary tree and print the inorder traversal of that tree.
#### Instructions:
1. You should implement a function `construct_tree(pre: List[int], post: List[i... | from typing import List
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(pre, pre_start, post, post_start, size):
if size == 0:
return None
root = TreeNode(pre[pre_start])
if size == 1:
... | from solution import construct_tree
def test_construct_tree_example():
pre = [1, 2, 4, 5, 3, 6, 7]
post = [4, 5, 2, 6, 7, 3, 1]
size = 7
assert construct_tree(pre, post, size) == [4, 2, 5, 1, 6, 3, 7]
def test_construct_tree_single_node():
pre = [1]
post = [1]
size = 1
assert construct... | [] | [
0,
0,
0,
1,
1,
0,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef cons... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00007199",
"row_id": 7199,
"seed_ids": "[300]"
} | 0.561677 | Data_Structure_7199 | I | [
"build_tree",
"print_inorder",
"construct_tree"
] | 3 | [
[
"construct_tree",
"build_tree"
],
[
"construct_tree",
"print_inorder"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | d8dea41c4005d05f61717a642a40e8f824d9d8e2 | 6731e3aa1cfa355268e8ab885b72beb1e37099dc | |||
v1.0 | instruct | Data_Structure | Data_Structure_7201_I | ## Question
### Context:
You are provided with a helper function, `search_insert`, which performs binary search to find the correct position to insert an element into a sorted list. Your task is to use this helper function to implement the full Insertion Sort algorithm.
### Task:
Implement a function `insertion_sort_... | def search_insert(array, val):
"""
Helper function that performs a binary search to find the correct insertion index for val in array.
"""
left, right = 0, len(array)
while left < right:
mid = (left + right) // 2
if array[mid] < val:
left = mid + 1
else:
... | from solution import insertion_sort_with_binary_search
def test_insertion_sort_with_binary_search_case1():
assert insertion_sort_with_binary_search([3, 4, 2, 1]) == [1, 2, 3, 4]
def test_insertion_sort_with_binary_search_case2():
assert insertion_sort_with_binary_search([10, -1, 2, 5, 20, -5]) == [-5, -1, 2, ... | [
{
"docstring": "Helper function that performs a binary search to find the correct insertion index for val in array.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "Sorts an array using insertion... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(array, val):\n \"\"\"\n Helper function to find the index where 'val' should be inserted in order to maintain sorted order.\n Uses ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007201",
"row_id": 7201,
"seed_ids": "[199]"
} | 0.600852 | Data_Structure_7201 | I | [
"search_insert",
"insertion_sort_with_binary_search"
] | 2 | [
[
"insertion_sort_with_binary_search",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 755e9cf8254478407dc07812e604669e7231bf0e | 8fb53e15a18272a806a79c56fdc83ce26b12b431 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7218_I | ### Question
You are given a B-Tree data structure implementation that supports insertion, deletion, searching, and traversal. Your task is to implement a function that merges two B-Trees of the same degree into one B-Tree, maintaining the B-Tree properties. The merged B-Tree should contain all the elements from both ... | class BTreeNode:
def __init__(self, t, leaf=False):
self.t = t # Minimum degree (defines the range for number of keys)
self.leaf = leaf # True if leaf node
self.keys = [] # List of keys in the node
self.children = [] # List of child BTreeNode objects
class BTree:
def __init_... | from solution import BTree, merge_btrees
def test_merge_with_empty_trees():
btree1 = BTree(2)
btree2 = BTree(2)
merged_btree = merge_btrees(btree1, btree2)
assert merged_btree.traverse() == []
def test_merge_with_one_empty_tree():
btree1 = BTree(2)
btree1.insert(10)
btree2 = BTree(2)
m... | [] | [
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 BTreeNode:\n def __init__(self, leaf=False):\n self.leaf = leaf\n self.keys = []\n self.children = []\n\nclass BTree:\n def _... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007218",
"row_id": 7218,
"seed_ids": "[296]"
} | 0.463221 | Data_Structure_7218 | I | [
"merge_sorted_lists",
"merge_btrees"
] | 2 | [
[
"merge_btrees",
"merge_sorted_lists"
]
] | 1 | [] | false | [
"BTreeNode",
"BTree"
] | true | pytest | true | [] | true | 743215b5a92d96ef1d2d2de492a6b5cf36b6cac2 | d4824809f547f4b78d484f289ea0a44395bfdc44 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7255_I | ### Extended Euclidean Algorithm Application
You are provided with an implementation of the extended Euclidean algorithm. The goal is to further comprehend the versatility of this fundamental algorithm by applying it to solve a slightly more complex problem. Your task is to use the extended GCD to determine if a Linea... | def extended_gcd(a, b):
"""
Computes the extended GCD of a and b.
Returns a tuple (g, x, y) where g is the GCD of a and b,
and x and y are the coefficients such that a*x + b*y = g.
"""
if b == 0:
return (a, 1, 0)
else:
g, x1, y1 = extended_gcd(b, a % b)
x = y1
... | from solution import solve_diophantine
def test_solve_diophantine_positive_solution():
result = solve_diophantine(30, 20, 10)
assert result is not None
assert 30 * result[0] + 20 * result[1] == 10
def test_solve_diophantine_no_solution():
assert solve_diophantine(35, 15, 1) == None
def test_solve_dio... | [
{
"docstring": "Computes the extended GCD of a and b.\nReturns a tuple (g, x, y) where g is the GCD of a and b, \nand x and y are the coefficients such that a*x + b*y = g.",
"function_declaration": "def extended_gcd(a, b):",
"function_name": "extended_gcd",
"parameter_list": "(a, b)"
},
{
"d... | [
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 \"\"\"\n Returns a tuple (g, x, y) where g is the greatest common divisor of a and b, \n and x, y are the coefficients of B... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007255",
"row_id": 7255,
"seed_ids": "[156]"
} | 0.620095 | Data_Structure_7255 | I | [
"extended_gcd",
"solve_diophantine"
] | 2 | [
[
"solve_diophantine",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4fba5141d0040f19f2f34eeb3d1b62a3b4373a6f | 68c4879f8defaf536f4443c3873d26cea24eb1b1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7267_I | ### Coding Challenge: Adaptive Heap Sort
**Context**: While the typical heap sort algorithm performs well under normal conditions (O(n log(n))), certain input patterns can still cause unnecessary overhead. To improve performance, you are tasked to implement an adaptive heap sort that reduces unnecessary operations for... | from typing import List
def insertion_sort(arr: List[int], start: int, end: int) -> None:
"""Utility function to perform insertion sort on subarray arr[start:end+1]."""
for i in range(start + 1, end + 1):
key = arr[i]
j = i - 1
while j >= start and key < arr[j]:
arr[j + 1] =... | def test_insertion_sort():
arr = [5, 2, 9, 1, 5, 6]
insertion_sort(arr, 0, len(arr) - 1)
assert arr == [1, 2, 5, 5, 6, 9]
def test_heap_sort():
arr = [12, 11, 13, 5, 6, 7]
heap_sort(arr)
assert arr == [5, 6, 7, 11, 12, 13]
def test_adaptive_heap_sort_empty():
assert adaptive_heap_sort([]) ... | [
{
"docstring": "Utility function to perform insertion sort on subarray arr[start:end+1].",
"function_declaration": "def insertion_sort(arr, start, end):",
"function_name": "insertion_sort",
"parameter_list": "(arr, start, end)"
},
{
"docstring": "Utility function to heapify a subtree rooted ... | [
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 adaptive_heap_sort(arr):\n \"\"\"\n Sorts an array in ascending order using an adaptive combination \n of heap sort and insertion sort.\n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007267",
"row_id": 7267,
"seed_ids": "[8]"
} | 0.607178 | Data_Structure_7267 | I | [
"insertion_sort",
"heapify",
"heap_sort",
"adaptive_heap_sort"
] | 4 | [
[
"adaptive_heap_sort",
"insertion_sort"
],
[
"heap_sort",
"heapify"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 37b2823998c26725f98a3b5eebc1354038749de8 | 5b43aa587b2a151d8f968857fb872313ee7db8f9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7288_I | ### Question:
You are provided with a training dataset represented as a dictionary where keys are tuples representing data points, and their corresponding values are the labels associated with them. Implement the `nearest_neighbor` function that takes a query vector and the training dataset to classify the query point ... | import math
def distance(v1, v2):
"""
Computes the Euclidean distance between two vectors v1 and v2.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
def nearest_neighbor(x: tuple, tSet: dict) -> str:
"""
Finds the nearest neighbor of the query vector 'x' in the training set 'tS... | from solution import nearest_neighbor
def test_nearest_neighbor_single_point():
tSet = {(1.0, 1.0): "ClassA"}
query_vector = (1.0, 1.0)
assert nearest_neighbor(query_vector, tSet) == "ClassA"
def test_nearest_neighbor_multiple_points():
tSet = {
(1.0, 2.0): "ClassA",
(2.0, 3.0): "Class... | [] | [
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(a: tuple, b: tuple) -> float:\n \"\"\"\n Compute the Euclidean distance between two points a and b.\n \"\"\"\n return ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00007288",
"row_id": 7288,
"seed_ids": "[260]"
} | 0.633264 | Data_Structure_7288 | I | [
"distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 32be427f6790b0bb33f265a3fdf3bbcf67a4be8e | 08354e5d961f4ee7c71be2472cde469b46f958cc | |||
v1.0 | instruct | Data_Structure | Data_Structure_7328_I | Implement a function `insertion_sort_with_helper` that sorts an array of integers using the insertion sort algorithm. The function should use the provided `search_insert` method to determine the correct insertion index for each element effectively.
#### Input
- A list of integers `arr`.
#### Output
- A list of intege... | from typing import List
def search_insert(arr: List[int], target: int) -> int:
"""
A helper function that finds the index where the target should be inserted in the sorted subarray.
Assuming `arr` is sorted in non-decreasing order up to the point of insertion.
"""
left, right = 0, len(arr)
whil... | from solution import insertion_sort_with_helper
def test_insertion_sort_basic():
assert insertion_sort_with_helper([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
assert insertion_sort_with_helper([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12]
def test_insertion_sort_empty():
assert insertion_sort_wi... | [
{
"docstring": "A helper function that finds the index where the target should be inserted in the sorted subarray.\nAssuming `arr` is sorted in non-decreasing order up to the point of insertion.",
"function_declaration": "def search_insert(arr, target):",
"function_name": "search_insert",
"parameter... | [
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 search_insert(arr: List[int], target: int) -> int:\n \"\"\"\n Perform binary search to find the index where target should... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007328",
"row_id": 7328,
"seed_ids": "[199]"
} | 0.62096 | Data_Structure_7328 | I | [
"search_insert",
"insertion_sort_with_helper"
] | 2 | [
[
"insertion_sort_with_helper",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 437927c7fc30b95fe80cf84adc34998756725623 | cdd373356beabc526ea61a83ea2a6e29287f543a | |||
v1.0 | instruct | Data_Structure | Data_Structure_7335_I | You are provided with two functions implementing an algorithm to count the number of '1' bits in the binary representation of an unsigned integer. Your task is to implement another function that compares the performance (execution time) of these two functions for a series of test cases and reports which one is faster a... | import time
def count_ones_recur(n):
if not n:
return 0
return 1 + count_ones_recur(n & (n - 1))
def count_ones_iter(n):
count = 0
while n:
n &= (n - 1)
count += 1
return count
def compare_performance(test_cases):
total_time_recur = 0.0
total_time_iter = 0.... | from solution import compare_performance, count_ones_recur, count_ones_iter
def test_compare_performance_basic():
test_cases = [3, 14, 31, 0, 1023]
faster_func, avg_time = compare_performance(test_cases)
assert faster_func in ['count_ones_recur', 'count_ones_iter']
assert avg_time > 0
def test_compare... | [
{
"docstring": null,
"function_declaration": "def count_ones_recur(n):",
"function_name": "count_ones_recur",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def count_ones_iter(n):",
"function_name": "count_ones_iter",
"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": "import time\n\ndef count_ones_recur(n):\n if not n:\n return 0\n return 1 + count_ones_recur(n & (n-1))\n \ndef count_ones_iter(n):\n c... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007335",
"row_id": 7335,
"seed_ids": "[218]"
} | 0.584181 | Data_Structure_7335 | I | [
"count_ones_recur",
"count_ones_iter",
"compare_performance"
] | 3 | [
[
"compare_performance",
"count_ones_iter"
],
[
"compare_performance",
"count_ones_recur"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8962e19b453e5c78901be81ece64f3e10368e3e8 | 3e0e67559eb18fc8db53bcfdb265f97f977513ff | |||
v1.0 | instruct | Data_Structure | Data_Structure_7384_I | You are tasked with implementing a custom sorting function for a dataset that frequently contains duplicate values and requires the preservation of the original order of those duplicates. This sorting is critical for maintaining the data's integrity in a large-scale distributed system.
**Function Definition**:
```pyth... | def custom_merge_sort(arr):
"""
Sorts an array while maintaining the relative order of equal elements.
This function uses the Merge Sort algorithm.
Args:
arr (List[int]): A list of integers to be sorted.
Returns:
List[int]: The sorted list.
"""
if len(arr) <= 1:
ret... | from solution import custom_merge_sort
def test_custom_merge_sort_basic():
assert custom_merge_sort([3, 2, 1, 4, 2, 3]) == [1, 2, 2, 3, 3, 4]
def test_custom_merge_sort_single_element():
assert custom_merge_sort([1]) == [1]
def test_custom_merge_sort_two_elements():
assert custom_merge_sort([2, 1]) == [1... | [
{
"docstring": "Sorts an array while maintaining the relative order of equal elements.\nThis function uses the Merge Sort algorithm.\n\nArgs:\narr (List[int]): A list of integers to be sorted.\n\nReturns:\nList[int]: The sorted list.",
"function_declaration": "def custom_merge_sort(arr):",
"function_nam... | [
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 custom_merge_sort(arr):\n \"\"\"\n Sorts an array while maintaining the relative order of equal elements.\n This function should use the Merge So... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007384",
"row_id": 7384,
"seed_ids": "[12]"
} | 0.587703 | Data_Structure_7384 | I | [
"custom_merge_sort",
"merge"
] | 2 | [
[
"custom_merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a20bf0284615817b3c6fbb198b5a93654102639b | bc1b3d020fd24a36adbeadd18775992f85dd9b3f | |||
v1.0 | instruct | Data_Structure | Data_Structure_7407_I | ### Strobogrammatic Number Challenge
### Objective
Write a Python function that generates all strobogrammatic numbers of length `n` and another function that counts how many strobogrammatic numbers exist within a given range `[low, high]`.
### Function Specifications
1. `gen_strobogrammatic(n: int) -> List[str]`
-... | def gen_strobogrammatic(n):
"""
Generate all strobogrammatic numbers of length n.
"""
def helper(n, total_length):
if n == 0:
return [""]
if n == 1:
return ["0", "1", "8"]
middles = helper(n - 2, total_length)
result = []
... | from solution import gen_strobogrammatic, strobogrammatic_in_range
def test_gen_strobogrammatic_length_1():
assert set(gen_strobogrammatic(1)) == {"0", "1", "8"}
def test_gen_strobogrammatic_length_2():
expected = {"11", "69", "88", "96"}
assert set(gen_strobogrammatic(2)) == expected
def test_gen_strobo... | [
{
"docstring": "Generate all strobogrammatic numbers of length n.",
"function_declaration": "def gen_strobogrammatic(n):",
"function_name": "gen_strobogrammatic",
"parameter_list": "(n)"
},
{
"docstring": "Count strobogrammatic numbers within the range [low, high].",
"function_declaratio... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gen_strobogrammatic(n):\n \"\"\"\n Generates all strobogrammatic numbers of length n.\n \"\"\"\n def helper(m, is_final):\n if m == 0:\... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00007407",
"row_id": 7407,
"seed_ids": "[140]"
} | 0.533367 | Data_Structure_7407 | I | [
"gen_strobogrammatic",
"strobogrammatic_in_range"
] | 2 | [
[
"strobogrammatic_in_range",
"gen_strobogrammatic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 49a5504e481b4ca489d672cacf6a3fa7151828c8 | 7f33a50108edf24c56df772fd33a0970599541f1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7422_I | ### Question
Given an array of non-negative integers, implement the Radix Sort algorithm to sort the array in ascending order. Your implementation should follow the least significant digit (LSD) radix sort approach. Write a Python function `radix_sort(arr)` which takes an array `arr` as an input and returns the sorted ... | def counting_sort(arr, exp):
"""
Perform a counting sort on arr based on the digit represented by exp.
"""
n = len(arr)
output = [0] * n
count = [0] * 10
# Store the count of occurrences of digits
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
... | 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_empty():
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort([5]) == [5]
def test_radix_sort_identi... | [
{
"docstring": "Perform a counting sort on arr based on the digit represented by exp.",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "Perform LSD Radix Sort on arr.",
"function_declaration": "de... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \n for i in range(n):\n i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007422",
"row_id": 7422,
"seed_ids": "[15]"
} | 0.687376 | Data_Structure_7422 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 16de2b332c099afc0689bc6ea8e4b910d80280bc | 3143592c18928b351067229d24b88df4f0e643ef | |||
v1.0 | instruct | Data_Structure | Data_Structure_7464_I | You are given a sequence of matrices and you are required to find the most efficient way to multiply these matrices together. Your task is to implement the matrix chain multiplication algorithm using dynamic programming.
### Input
* An array of integers `arr` of size `n`, where `arr[i]` represents the dimension of the... | from typing import List
def matrix_chain_multiplication(arr: List[int]) -> None:
n = len(arr) - 1 # Number of matrices
m = [[0] * n for _ in range(n)]
s = [[0] * n for _ in range(n)]
for l in range(2, n + 1):
for i in range(0, n - l + 1):
j = i + l - 1
m[i][j] = fl... | import pytest
from solution import matrix_chain_multiplication
def test_matrix_chain_multiplication_example():
arr = [30, 35, 15, 5, 10, 20, 25]
matrix_chain_multiplication(arr) # Expected to print 15125 and (A1(A2(A3(A4A5))A6))
def test_matrix_chain_multiplication_minimal_case():
arr = [10, 20]
matr... | [
{
"docstring": null,
"function_declaration": "def matrix_chain_multiplication(arr):",
"function_name": "matrix_chain_multiplication",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def _get_optimal_parenthesization(s, i, j):",
"function_name": "_get_optima... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_chain_multiplication(arr):\n n = len(arr)\n # Initialize the matrix for storing minimum scalar multiplications required\n m = [[0 for _ in... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007464",
"row_id": 7464,
"seed_ids": "[45]"
} | 0.430493 | Data_Structure_7464 | I | [
"matrix_chain_multiplication",
"_get_optimal_parenthesization"
] | 2 | [
[
"matrix_chain_multiplication",
"_get_optimal_parenthesization"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | de914bb5b5f765121fdc83daf782b03f993b6bd6 | 400df7e3c7a4554ba01ee686cc7cae35dc016df1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7494_I | ### Problem: Prime Number Verifier
#### Context:
You are working on a piece of software that requires checking the primality of multiple numbers efficiently. Prime numbers have significant applications in fields like cryptography, number theory, and hashing algorithms. Your task is to implement a function that verifie... | from typing import List
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
... | from solution import is_prime_list
def test_prime_list_empty():
assert is_prime_list([]) == []
def test_prime_list_single_elements():
assert is_prime_list([1]) == [False]
assert is_prime_list([2]) == [True]
assert is_prime_list([3]) == [True]
assert is_prime_list([4]) == [False]
def test_prime_li... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def is_prime_list(nums):",
"function_name": "is_prime_list",
"parameter_list": "(nums)"
}
] | [
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 math import isqrt\nfrom typing import List\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n == 2:\n return True\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007494",
"row_id": 7494,
"seed_ids": "[143]"
} | 0.729046 | Data_Structure_7494 | I | [
"is_prime",
"is_prime_list"
] | 2 | [
[
"is_prime_list",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7a1e1933429b01882673d7628ef31a004c55a2ce | 90d9c45a219b523ce7a5ac25c578955d50334243 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7522_I | Implement a function that performs an "augmented insertion sort" on an array but uses binary search (`search_insert`) to find the correct insertion position for each element.
#### Description
You are provided with a function `search_insert(array, val)` that, given a sorted array and a target value, returns the index i... | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
"""
left, right = 0, len(array)
while left < right:
... | from solution import augmented_insertion_sort
def test_augmented_insertion_sort_empty():
assert augmented_insertion_sort([]) == []
def test_augmented_insertion_sort_single_element():
assert augmented_insertion_sort([1]) == [1]
def test_augmented_insertion_sort_sorted_array():
assert augmented_insertion_s... | [
{
"docstring": "Given a sorted array and a target value, return the index if the target is found.\nIf not, return the index where it would be if it were inserted in order.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n Helper function to find the index to insert val in the sorte... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007522",
"row_id": 7522,
"seed_ids": "[199]"
} | 0.613666 | Data_Structure_7522 | I | [
"search_insert",
"augmented_insertion_sort"
] | 2 | [
[
"augmented_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 16067e4a6c4fdadae30666d6f43fd95d4e0568f4 | b17902398c461ea03031e265b923fa88e909bf6a | |||
v1.0 | instruct | Data_Structure | Data_Structure_7561_I | ### Radix Sort Implementation and Simulation
#### Context:
Imagine you are building a data processing system that needs to handle large sets of integer data efficiently. Radix Sort is particularly well-suited for this task as it sorts integers in linear time for small ranges of digit lengths, providing a feasible so... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - ... | from solution import radix_sort
def test_radix_sort_single_element():
arr = [10]
assert radix_sort(arr) == [10]
def test_radix_sort_sorted_array():
arr = [1, 2, 3, 4, 5, 6]
assert radix_sort(arr) == [1, 2, 3, 4, 5, 6]
def test_radix_sort_duplicate_values():
arr = [7, 7, 7, 7, 7]
assert radix_... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name": "radix_sort... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007561",
"row_id": 7561,
"seed_ids": "[15]"
} | 0.616081 | Data_Structure_7561 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9e4145243af2b829256fccdc5c5c9637b1cec27c | 5b44251fdeffdb9f3abac2c43d65a760168996e9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7648_I | ### Question
You are required to implement a **Heap Sort** function that sorts an array in ascending order using a **max heap** approach. To assess your understanding of the algorithm and its properties, you should provide a detailed implementation of the core functions and handle various edge cases effectively.
Impl... | from typing import List
def heapify(arr: List[int], n: int, i: int, simulation: bool) -> None:
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 !=... | from solution import heap_sort
def test_heap_sort():
# Test with an unsorted array
arr = [4, 10, 3, 5, 1]
assert heap_sort(arr, simulation=False) == [1, 3, 4, 5, 10]
# Test with an already sorted array
arr = [1, 2, 3, 4, 5]
assert heap_sort(arr, simulation=False) == [1, 2, 3, 4, 5]
# Test... | [
{
"docstring": null,
"function_declaration": "def heapify(arr, n, i, simulation):",
"function_name": "heapify",
"parameter_list": "(arr, n, i, simulation)"
},
{
"docstring": null,
"function_declaration": "def heap_sort(arr, simulation=False):",
"function_name": "heap_sort",
"para... | [
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 heap_sort(arr: List[int], simulation: bool=False) -> List[int]:\n \n def heapify(arr: List[int], n: int, i: int):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007648",
"row_id": 7648,
"seed_ids": "[8]"
} | 0.754524 | Data_Structure_7648 | I | [
"heapify",
"heap_sort"
] | 2 | [
[
"heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8d187d51f3736ecb7d434779cb868ac57bb6eb65 | b746a11725db38d3603f45d7f3e32ade6914588b | |||
v1.0 | instruct | Data_Structure | Data_Structure_7690_I | ### Question: Implement and Optimize Matrix Operations
You are required to write a Python function that efficiently performs matrix exponentiation for large powers. While the provided snippets of the matrix multiplication, identity matrix generation, and matrix exponentiation do the job, they have substantial scope fo... | def matrix_multiply(A, B):
"""Multiplies two square matrices A and B."""
size = len(A)
result = [[0] * size for _ in range(size)]
for i in range(size):
for j in range(size):
for k in range(size):
result[i][j] += A[i][k] * B[k][j]
return result
def identity_matrix... | def test_matrix_multiply():
A = [
[1, 2],
[3, 4]
]
B = [
[5, 6],
[7, 8]
]
expected = [
[19, 22],
[43, 50]
]
assert matrix_multiply(A, B) == expected
def test_identity_matrix():
assert identity_matrix(3) == [
[1, 0, 0],
[0, ... | [
{
"docstring": "Multiplies two square matrices A and B.",
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": "Creates an identity matrix of given size.",
"function_declaration": "def identity_matrix(size)... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_results_combined.jsonl",
"solution_code": "def optimized_matrix_exponentiation(mat, n):\n def matrix_mult(A, B):\n \"\"\" Multiplies two matrices A and B \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007690",
"row_id": 7690,
"seed_ids": "[340]"
} | 0.508159 | Data_Structure_7690 | I | [
"matrix_multiply",
"identity_matrix",
"matrix_power",
"optimized_matrix_exponentiation"
] | 4 | [
[
"matrix_power",
"identity_matrix"
],
[
"matrix_power",
"matrix_multiply"
],
[
"optimized_matrix_exponentiation",
"identity_matrix"
],
[
"optimized_matrix_exponentiation",
"matrix_power"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 61eae0003de7f7aa3af234ecca99e17c84ddd895 | c57198dd8612b8959477cf457f6bfb575f3de926 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7692_I | **Problem Statement**:
You are implementing a machine learning pipeline, and one of the requirements is to compute the cosine similarity between pairs of document vectors. Given the importance of this measure in evaluating the similarity between documents, your task is to write a function that computes the cosine simi... | import math
def _l2_distance(vec):
"""
Helper function to calculate the L2 norm of a vector.
:param vec: list of integers/floats
:return: float
"""
norm = 0.
for element in vec:
norm += element * element
return math.sqrt(norm)
def cosine_similarity(vec1, vec2):
"""
Func... | from solution import cosine_similarity
def test_cosine_similarity_same_vector():
assert math.isclose(cosine_similarity([1, 1, 1], [1, 1, 1]), 1.0, rel_tol=1e-9)
def test_cosine_similarity_orthogonal_vectors():
assert math.isclose(cosine_similarity([1, 0, 0], [0, 1, 0]), 0.0, rel_tol=1e-9)
def test_cosine_sim... | [
{
"docstring": "Helper function to calculate the L2 norm of a vector.\n:param vec: list of integers/floats\n:return: float",
"function_declaration": "def _l2_distance(vec):",
"function_name": "_l2_distance",
"parameter_list": "(vec)"
},
{
"docstring": "Function to calculate cosine similarity... | [
0,
0,
0,
1,
0,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef _l2_distance(vec):\n \"\"\"\n Helper function to calculate the L2 norm of a vector.\n :param vec: list of integers/floats\n :re... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00007692",
"row_id": 7692,
"seed_ids": "[149]"
} | 0.635963 | Data_Structure_7692 | I | [
"_l2_distance",
"cosine_similarity"
] | 2 | [
[
"cosine_similarity",
"_l2_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 002982a307523072fb172eb34df09207ad573775 | f612d46f3d8ed48aa0f81d5bbbe3bc5adf9e48cd | |||
v1.0 | instruct | Data_Structure | Data_Structure_7722_I | ### Insertion Sort with Efficient Insertion Point Search
**Problem Statement**:
Using the provided `search_insert` helper function, implement an insertion sort algorithm that sorts an array of integers in ascending order. Your implementation should efficiently find the insertion point for each element using the `searc... | from typing import List
def search_insert(sorted_sublist: List[int], x: int) -> int:
"""
Helper function to find the index where x should be inserted in sorted_sublist
to maintain sorted order.
"""
low, high = 0, len(sorted_sublist)
while low < high:
mid = (low + high) // 2
if s... | from solution import insertion_sort
def test_insertion_sort_example_1():
assert insertion_sort([4, 3, 2, 10, 12, 1, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 12]
def test_insertion_sort_example_2():
assert insertion_sort([12, 11, 13, 5, 6]) == [5, 6, 11, 12, 13]
def test_insertion_sort_example_3():
assert inserti... | [
{
"docstring": "Helper function to find the index where x should be inserted in sorted_sublist\nto maintain sorted order.",
"function_declaration": "def search_insert(sorted_sublist, x):",
"function_name": "search_insert",
"parameter_list": "(sorted_sublist, x)"
},
{
"docstring": "Sorts the ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(arr: List[int], x: int) -> int:\n \"\"\"\n Helper function to find the insertion point for x in a sorted ar... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007722",
"row_id": 7722,
"seed_ids": "[199]"
} | 0.588583 | Data_Structure_7722 | I | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b67c492e14eeb89b157fc1315b3d69a21b84309f | 2cd486e71be4d14dec14ce9c4295ede0e7608e68 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7801_I | **Question**:
Implement a function `find_element(arr, target, simulation=False)` that uses Bubble Sort to sort the input array, then performs a binary search to find a target element.
### Input:
- `arr`: A list of integers that may be unsorted.
- `target`: An integer to find in the sorted array.
- `simulation (optio... | def bubble_sort(arr, simulation):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
if simulation:
print(f"Step {i * n + j + 1}: {arr}")
def binary_search(arr, tar... | def test_find_element_sorted_array():
arr = [1, 2, 3, 4, 5]
target = 3
assert find_element(arr, target) == 2
def test_find_element_unsorted_array():
arr = [5, 2, 9, 1, 5, 6]
target = 5
index = find_element(arr, target)
assert arr[index] == 5
def test_find_element_not_present():
arr = [... | [
{
"docstring": null,
"function_declaration": "def bubble_sort(arr, simulation):",
"function_name": "bubble_sort",
"parameter_list": "(arr, simulation)"
},
{
"docstring": null,
"function_declaration": "def binary_search(arr, target):",
"function_name": "binary_search",
"parameter_... | [
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 bubble_sort(arr, simulation):\n n = len(arr)\n for i in range(n):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007801",
"row_id": 7801,
"seed_ids": "[6]"
} | 0.652166 | Data_Structure_7801 | I | [
"bubble_sort",
"binary_search",
"find_element"
] | 3 | [
[
"find_element",
"binary_search"
],
[
"find_element",
"bubble_sort"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | ece7348522acfbe0cb3d3cd6372a1c9abeeaacfc | 14b067aff11c4b0bc3852d6341fa53da4635adff | |||
v1.0 | instruct | Data_Structure | Data_Structure_7878_I | ### Scenario
You have been hired by a large organization to assist in processing significant amounts of data related to their inventory system. A crucial part of this system is determining optimal batch sizes for manufacturing. To achieve this, you need to compute the Greatest Common Divisor (GCD) and Least Common Mul... | def gcd_optimal(a, b):
"""
Computes the GCD of two non-negative integers using bitwise operations.
"""
if a == 0:
return b
if b == 0:
return a
# Both a and b are even
if (a & 1) == 0 and (b & 1) == 0:
return gcd_optimal(a >> 1, b >> 1) << 1
# a is even, b is... | from solution import gcd_optimal, lcm_using_gcd, trailing_zero_bits
def test_gcd_optimal():
assert gcd_optimal(48, 18) == 6
assert gcd_optimal(0, 10) == 10
assert gcd_optimal(10, 0) == 10
assert gcd_optimal(0, 0) == 0
assert gcd_optimal(101, 103) == 1
assert gcd_optimal(56, 98) == 14
def test_... | [
{
"docstring": "Computes the GCD of two non-negative integers using bitwise operations.",
"function_declaration": "def gcd_optimal(a, b):",
"function_name": "gcd_optimal",
"parameter_list": "(a, b)"
},
{
"docstring": "Computes the LCM of two non-negative integers using the GCD calculated fro... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd_optimal(a, b):\n \"\"\"\n Returns the greatest common divisor (GCD) of two non-negative integers using bitwise operations.\n \"\"\"\n if a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007878",
"row_id": 7878,
"seed_ids": "[166]"
} | 0.622824 | Data_Structure_7878 | I | [
"gcd_optimal",
"lcm_using_gcd",
"trailing_zero_bits"
] | 3 | [
[
"lcm_using_gcd",
"gcd_optimal"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c77fca323c38c462be9602d25764ffc73af83303 | 213b5ab7d3299536f033cdea6e34ac1433468fa5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7884_I | ## Problem Statement
You are given a binary tree where each node contains an integer value. Your task is to determine if this tree satisfies the properties of a Binary Search Tree (BST). For a tree to be considered a BST, it must satisfy the following conditions:
1. The left subtree of any node contains only nodes wit... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_bst_helper(node, lower=float('-inf'), upper=float('inf')):
if not node:
return True
val = node.val
if val <= lower or val >= upper:
return ... | from solution import TreeNode, is_bst
def test_empty_tree():
assert is_bst(None) == True
def test_single_node_tree():
root = TreeNode(10)
assert is_bst(root) == True
def test_valid_bst_simple():
root = TreeNode(2)
root.left = TreeNode(1)
root.right = TreeNode(3)
assert is_bst(root) == Tru... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007884",
"row_id": 7884,
"seed_ids": "[327]"
} | 0.662226 | Data_Structure_7884 | I | [
"is_bst_helper",
"is_bst"
] | 2 | [
[
"is_bst",
"is_bst_helper"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 3d63ab09ceac8dc847b8a2305b1ec4457cdda163 | d53eaa1c67c04df6a46e6d97dd8e1c6e5f425b32 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7907_I | ### Scenario
You are developing a software library that includes functions for performing various mathematical computations. Leveraging your understanding of algorithms and bitwise operations, you need to implement an optimized function to calculate the greatest common divisor (GCD) of a list of integers using the prov... | def gcd_bit(a, b):
# Base cases for the bitwise GCD algorithm
if a == 0: return b
if b == 0: return a
# Finding common factors of 2
if a == b: return a
if a == 1 or b == 1: return 1
# Reducing both a and b while both are even
if ~a & 1: # a is even
if ~b & 1: # b is e... | from solution import list_gcd_bitwise
def test_list_gcd_bitwise_basic():
assert list_gcd_bitwise([24, 36, 60]) == 12
assert list_gcd_bitwise([16, 32, 96]) == 16
assert list_gcd_bitwise([7, 14, 21]) == 7
def test_list_gcd_bitwise_with_zeros():
assert list_gcd_bitwise([0, 0, 5]) == 5
assert list_gcd... | [
{
"docstring": null,
"function_declaration": "def gcd_bit(a, b):",
"function_name": "gcd_bit",
"parameter_list": "(a, b)"
},
{
"docstring": "Given a list of non-negative integers, return their greatest common divisor using the bitwise method.",
"function_declaration": "def list_gcd_bitwi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd_bit(x, y):\n \"\"\"\n Compute the GCD of x and y using bitwise operations.\n \"\"\"\n if x == 0:\n return y\n if y == 0:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007907",
"row_id": 7907,
"seed_ids": "[166]"
} | 0.676338 | Data_Structure_7907 | I | [
"gcd_bit",
"list_gcd_bitwise"
] | 2 | [
[
"list_gcd_bitwise",
"gcd_bit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b9e3badad80d59c86fdf735e0694a7d72faf5c8c | 06a5b150a8b452053dabeb43759c5b870b9a619e | |||
v1.0 | instruct | Data_Structure | Data_Structure_7909_I | **Scenario:**
You are working on an inventory management system that handles a large amount of product data. Each product has a unique integer ID. To efficiently sort the product IDs for better access and retrieval, you decided to implement a radix sort.
### Task:
**Function to implement:**
Implement the function `... | from typing import List
def counting_sort(arr: List[int], exp: int, simulation: bool=False) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
# Store count of occurrences in count[]
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
# Change... | import pytest
from solution import radix_sort
def test_radix_sort_empty():
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort([5]) == [5]
def test_radix_sort_already_sorted():
assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_radix_sort_small_list():
ass... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, simulation=False):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=False):",
"function_name":... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool=False) -> List[int]:\n n = len(arr)\n output = [0] * n \n co... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007909",
"row_id": 7909,
"seed_ids": "[15]"
} | 0.531471 | Data_Structure_7909 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2530c8f0fd3a38eecde135d7d95f80e34bfd0d16 | bbcf4afc719a6c6efc358bd161f9435d1e29bf30 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7912_I | ### Ternary Search vs Binary Search: Performance Comparison
#### Objective
Implement a function to perform ternary search and compare its performance with binary search on large sorted arrays. Your task is to write effective search functions for both algorithms and determine which is faster for various array sizes.
#... | from typing import List
import time
def ternary_search(left: int, right: int, key: int, arr: List[int]) -> int:
if right >= left:
mid1 = left + (right - left) // 3
mid2 = right - (right - left) // 3
if arr[mid1] == key:
return mid1
if arr[mid2] == key:
... | from solution import ternary_search, binary_search
import random
def test_ternary_search_exists():
arr = sorted(random.sample(range(1, 10**5), 10**3))
key = arr[500] # Guarantee key exists
assert ternary_search(0, len(arr)-1, key, arr) != -1
def test_ternary_search_not_exists():
arr = sorted(random.s... | [
{
"docstring": null,
"function_declaration": "def ternary_search(left, right, key, arr):",
"function_name": "ternary_search",
"parameter_list": "(left, right, key, arr)"
},
{
"docstring": null,
"function_declaration": "def binary_search(left, right, key, arr):",
"function_name": "bin... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nfrom typing import List\n\ndef ternary_search(left: int, right: int, key: int, arr: List[int]) -> int:\n \"\"\"\n Perform ternary search on... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007912",
"row_id": 7912,
"seed_ids": "[193]"
} | 0.643015 | Data_Structure_7912 | I | [
"ternary_search",
"binary_search",
"compare_search_performance"
] | 3 | [
[
"compare_search_performance",
"binary_search"
],
[
"compare_search_performance",
"ternary_search"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f8a2608dc328c9cdbf98c10a14ff6d67144b7b5c | 71b0996ac2382b8507fa5bcb4ac1a2956c68c646 | |||
v1.0 | instruct | Data_Structure | Data_Structure_7918_I | Enhanced Nearest Neighbor Classification
You are provided with an implementation of the nearest neighbor classification algorithm. The existing implementation computes the nearest neighbor based on Euclidean distance between vectors. Your task is to extend and optimize this implementation by adding a few vital feature... | import numpy as np
from sklearn.neighbors import KDTree
def enhanced_nearest_neighbor(x: tuple, tSet: dict, metric: str = "euclidean") -> any:
"""
Returns the label of the nearest neighbor of the input vector x according to the specified distance metric.
"""
if not tSet:
return None
if len... | from solution import enhanced_nearest_neighbor, build_kd_tree, kd_tree_search
import numpy as np
def test_enhanced_nearest_neighbor_empty_set():
tSet = {}
x = (1, 1)
assert enhanced_nearest_neighbor(x, tSet, metric="euclidean") is None
def test_enhanced_nearest_neighbor_single_element():
tSet = {(2, 3... | [
{
"docstring": "Returns the label of the nearest neighbor of the input vector x according to the specified distance metric.",
"function_declaration": "def enhanced_nearest_neighbor(x, tSet, metric='euclidean'):",
"function_name": "enhanced_nearest_neighbor",
"parameter_list": "(x, tSet, metric='eucl... | [
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\nfrom sklearn.neighbors import KDTree\n\ndef enhanced_nearest_neighbor(x: tuple, tSet: dict, metric: str = \"euclidean\") -> any:\n \"\"... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007918",
"row_id": 7918,
"seed_ids": "[260]"
} | 0.655142 | Data_Structure_7918 | I | [
"enhanced_nearest_neighbor",
"build_kd_tree",
"kd_tree_search"
] | 3 | [
[
"enhanced_nearest_neighbor",
"build_kd_tree"
],
[
"enhanced_nearest_neighbor",
"kd_tree_search"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 0f9f1b6489d7b68e4288feef741ea7f060cac711 | 03f4cc832a562f2429e8ab955b95883491544f7a | |||
v1.0 | instruct | Data_Structure | Data_Structure_7927_I | Design and implement an efficient algorithm for calculating the maximum flow in a given flow network using the Ford-Fulkerson, Edmonds-Karp, or Dinic's algorithm. The input will consist of the capacity matrix, source node, and sink node. You are required to handle edge cases, optimize for performance, and ensure correc... | from collections import deque
def bfs(capacity, source, sink, parent):
"""
Breadth-First Search to find an augmenting path in the residual graph.
"""
visited = [False] * len(capacity)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v,... | from solution import max_flow
def test_example_case():
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert max_flow(capacity, source, si... | [
{
"docstring": "Breadth-First Search to find an augmenting path in the residual graph.",
"function_declaration": "def bfs(capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, source, sink, parent)"
},
{
"docstring": "Function to calculate maximum flow in a... | [
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(capacity, source, sink, parent):\n visited = [False] * len(capacity)\n queue = deque([source])\n visited[sou... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007927",
"row_id": 7927,
"seed_ids": "[240]"
} | 0.527058 | Data_Structure_7927 | I | [
"bfs",
"max_flow"
] | 2 | [
[
"max_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 529bc177bf4856b017437631c0713c4c07ab5729 | c01425e1b585389d547d560c8a788ef3e62d2f4d | |||
v1.0 | instruct | Data_Structure | Data_Structure_7937_I | ### Context
Merge Sort is a fundamental sorting algorithm commonly used in computer science due to its guarantees in time complexity and sorting stability. Your task is to demonstrate your understanding of this algorithm by implementing it with particular attention to efficient merging and handling of edge cases.
### ... | def merge_sort_in_place(arr):
"""
Sorts the array in place using merge sort algorithm.
Parameters:
arr (list): List of integers to be sorted.
Returns:
list: Sorted list.
"""
if len(arr) > 1:
merge_sort_helper(arr, 0, len(arr) - 1)
return arr
def merge_sort_helper(arr,... | from solution import merge_sort_in_place
def test_merge_sort_empty():
arr = []
sorted_arr = merge_sort_in_place(arr)
assert sorted_arr == []
def test_merge_sort_single_element():
arr = [1]
sorted_arr = merge_sort_in_place(arr)
assert sorted_arr == [1]
def test_merge_sort_already_sorted():
... | [
{
"docstring": "Sorts the array in place using merge sort algorithm.\n\nParameters:\narr (list): List of integers to be sorted.\n\nReturns:\nlist: Sorted list.",
"function_declaration": "def merge_sort_in_place(arr):",
"function_name": "merge_sort_in_place",
"parameter_list": "(arr)"
},
{
"d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort_in_place(arr):\n def merge(start, mid, end):\n left = arr[start:mid+1]\n right = arr[mid+1:end+1]\n k = start\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007937",
"row_id": 7937,
"seed_ids": "[12]"
} | 0.697179 | Data_Structure_7937 | I | [
"merge_sort_in_place",
"merge_sort_helper",
"merge"
] | 3 | [
[
"merge_sort_helper",
"merge"
],
[
"merge_sort_in_place",
"merge_sort_helper"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 38ff8c878ed0fd441afc9b9b6e18e9c0a757833d | 50693e717c6e8dec42e2f2070a5ad70cde5c751a | |||
v1.0 | instruct | Data_Structure | Data_Structure_7947_I | ### Objective
You are tasked with implementing a key functionality for a Red-Black Tree data structure. Specifically, you'll focus on adding a feature to find the kth smallest element in the tree.
### Problem Description
Implement the method `find_kth_smallest(tree: RBTree, k: int) -> int` which accepts an instance o... | class RBNode:
def __init__(self, value, color, left=None, right=None, parent=None):
self.value = value
self.color = color
self.left = left
self.right = right
self.parent = parent
class RBTree:
def __init__(self):
self.TNULL = RBNode(0, 0)
self.root = self... | from solution import RBNode, RBTree, find_kth_smallest
def test_find_kth_smallest():
tree = RBTree()
nodes = [7, 3, 18, 10, 22, 8, 11, 26]
for val in nodes:
tree.insert(val)
# Testing kth smallest elements
assert find_kth_smallest(tree, 1) == 3
assert find_kth_smallest(tree, 2) == ... | [] | [
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 RBNode:\n def __init__(self, value, color, left=None, right=None, parent=None):\n self.value = value\n self.color = color\n self... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007947",
"row_id": 7947,
"seed_ids": "[314]"
} | 0.538326 | Data_Structure_7947 | I | [
"inorder_traversal",
"find_kth_smallest"
] | 2 | [
[
"find_kth_smallest",
"inorder_traversal"
]
] | 1 | [] | false | [
"RBNode",
"RBTree"
] | true | pytest | true | [] | true | 4e3894580025131c889e29dd67ad06cd06033dd2 | 21d348d5df89e713dabac94d4f8ac14d3a56afc5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8062_I | ### Prime Number Identification and List Generation
Given an integer `M`, write a function `generate_primes(M)` that generates a list of prime numbers up to a given number `M` (inclusive).
### Function Signature
```python
def generate_primes(M: int) -> list:
pass
```
### Input
* An integer `M` where `M >= 0`.
#... | def is_prime(n):
"""
Check if a number is prime.
Returns True if n is a prime number, otherwise False.
"""
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 generate_primes
def test_generate_primes_zero():
assert generate_primes(0) == []
def test_generate_primes_one():
assert generate_primes(1) == []
def test_generate_primes_two():
assert generate_primes(2) == [2]
def test_generate_primes_ten():
assert generate_primes(10) == [2, 3, ... | [
{
"docstring": "Check if a number is prime.\nReturns True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate a list of all prime numbers up to a given number M (inclusive).",
... | [
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 Check if a number is prime.\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00008062",
"row_id": 8062,
"seed_ids": "[143]"
} | 0.67959 | Data_Structure_8062 | I | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4856b24c12751527265be0b0f44f498fb63581be | 3cbab10cbb60ebc3d15ec777d00f6bb0b1fa42b1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8086_I | ### RSA Encryption Implementation and Analysis
#### Problem Statement
You are tasked with implementing a secure messaging system using the RSA encryption algorithm. Your program will include key generation, encryption, and decryption mechanisms. You must also write tests verifying the correctness of your implementati... | import random
from sympy import isprime, mod_inverse
def generate_prime(bits, seed=None):
if seed is not None:
random.seed(seed)
while True:
p = random.getrandbits(bits)
if isprime(p):
return p
def generate_key(k, seed=None):
p = generate_prime(k // 2, seed)
q = gen... | from solution import generate_key, encrypt, decrypt
def test_key_generation():
n, e, d = generate_key(16, seed=42)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert n > 0
assert e > 0
assert d > 0
def test_encryption_decryption():
n, e, d = generate_k... | [
{
"docstring": null,
"function_declaration": "def generate_prime(bits, seed=None):",
"function_name": "generate_prime",
"parameter_list": "(bits, seed=None)"
},
{
"docstring": null,
"function_declaration": "def generate_key(k, seed=None):",
"function_name": "generate_key",
"param... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_key(k, seed=None):\n \"\"\"\n Generates an RSA key pair with k-bit primes.\n \n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00008086",
"row_id": 8086,
"seed_ids": "[154]"
} | 0.60698 | Data_Structure_8086 | I | [
"generate_prime",
"generate_key",
"encrypt",
"decrypt"
] | 4 | [
[
"generate_key",
"generate_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 6a906703f61a2ac17ba37886577e1525be2339b7 | a96677103b5efef1e6ee207702efb74ebf41ab57 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8137_I | **Problem Statement**: Cholesky Matrix Decomposition Verification
You are provided with a matrix, and your task is to determine whether this matrix can be decomposed using the Cholesky decomposition. If it can be decomposed, you should return the lower triangular matrix \(V\), otherwise return `None`.
A matrix \(A\) ... | from typing import List, Optional
import numpy as np
def is_positive_definite(matrix):
"""Check if the matrix is positive definite."""
try:
np.linalg.cholesky(matrix)
return True
except np.linalg.LinAlgError:
return False
def cholesky_decomposition(A: List[List[float]]) -> Optional... | from solution import cholesky_decomposition
def matrices_are_close(mat1, mat2, tol=1e-9):
"""Helper function to compare if two matrices are nearly equal."""
return all(abs(a - b) < tol for row1, row2 in zip(mat1, mat2) for a, b in zip(row1, row2))
def test_cholesky_decomposition():
A1 = [
[4, 12, ... | [
{
"docstring": "Check if the matrix is positive definite.",
"function_declaration": "def is_positive_definite(matrix):",
"function_name": "is_positive_definite",
"parameter_list": "(matrix)"
},
{
"docstring": "Performs Cholesky decomposition of a given matrix A if possible.\nReturns the lowe... | [
0,
0,
0,
1,
1,
1,
1,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Optional\n\ndef cholesky_decomposition(A: List[List[float]]) -> Optional[List[List[float]]]:\n import math\n \n n = len(A)\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00008137",
"row_id": 8137,
"seed_ids": "[339]"
} | 0.501649 | Data_Structure_8137 | I | [
"is_positive_definite",
"cholesky_decomposition"
] | 2 | [
[
"cholesky_decomposition",
"is_positive_definite"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 4c379cce116e55b92500b353cf7fefe7d4e6c2e3 | 6ef324b946a04fce5c9d3dc920766af498a92bf1 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8171_I | ### Bogo Sort Simulation Challenge
Bogo Sort is a highly inefficient sorting algorithm that generates random permutations of a list until it happens to find one that is sorted. Despite its impracticality, it is a great educational tool to understand sorting and randomness.
#### Task
You are given an input list of int... | import random
def is_sorted(arr):
"""
Check if the array is sorted in ascending order.
"""
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def bogo_sort_simulated(arr):
"""
Simulate the Bogo Sort algorithm. Return the sorted list and the number of iterations it took to sort the array... | from solution import bogo_sort_simulated
def test_bogo_sort_simulated_already_sorted():
arr = [1, 2, 3, 4, 5]
sorted_arr, iterations = bogo_sort_simulated(arr)
assert sorted_arr == [1, 2, 3, 4, 5]
assert iterations == 0 # If already sorted, no shuffle needed
def test_bogo_sort_simulated_reverse_order... | [
{
"docstring": "Check if the array is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Simulate the Bogo Sort algorithm. Return the sorted list and the number of iterations it took to sort t... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\" Helper function to check if the list is sorted \"\"\"\n for i in range(len(arr) - 1):\n if arr[i] >... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00008171",
"row_id": 8171,
"seed_ids": "[16]"
} | 0.600244 | Data_Structure_8171 | I | [
"is_sorted",
"bogo_sort_simulated"
] | 2 | [
[
"bogo_sort_simulated",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e1030035e83cf7252e00210114ce3f31d01a1e93 | c2ae4eebcc58da16c29a2cba8393029c414ede98 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8206_I | ### Question: Implement an Optimized Quick Sort Algorithm
**Scenario**: You are provided with a dataset consisting of numerical elements that need to be sorted. You have identified that the classical Quick Sort may not handle certain edge cases efficiently.
Write a function `optimized_quick_sort(arr, simulation=False... | import random
def insertion_sort(arr, left, right):
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def partition(arr, low, high):
pivot_index = random.randint(low,... | import random
import pytest
from solution import quick_sort
def test_sorted_array():
assert quick_sort([]) == []
assert quick_sort([1]) == [1]
assert quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
assert quick_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_random_array():
arr = [12, 4, 5, 6, 7,... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"paramet... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef 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 >= ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00008206",
"row_id": 8206,
"seed_ids": "[25]"
} | 0.548115 | Data_Structure_8206 | I | [
"insertion_sort",
"partition",
"optimized_quick_sort",
"quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"insertion_sort"
],
[
"optimized_quick_sort",
"partition"
],
[
"quick_sort",
"optimized_quick_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ee2da460d9df4963d45e2062f5ee701286202b6e | c07315c0b08538c9c1c8350fc7c4119e07d3a33b | |||
v1.0 | instruct | Data_Structure | Data_Structure_8227_I | ### Question
Given a Red-Black Tree implementation in Python, your task is to extend this tree to efficiently handle the following operations:
1. **Successor**: Find the in-order successor of a given node in the Red-Black Tree.
2. **Predecessor**: Find the in-order predecessor of a given node in the Red-Black Tree.
#... | class RBNode:
def __init__(self, val, color):
self.val = val
self.color = color # 1 -> Red, 0 -> Black
self.left = None
self.right = None
self.parent = None
class RBTree:
def __init__(self):
self.nil = RBNode(0, 0) # Sentinel node (used for leaves)
sel... | import pytest
from solution import RBTree, RBNode, successor, predecessor
@pytest.fixture
def rb_tree():
rb = RBTree()
nodes = [20, 10, 30, 5, 15, 25, 35]
node_map = {}
for val in nodes:
node = RBNode(val, 1)
node_map[val] = node
rb.insert(node)
return rb, node_map
def test... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class RBNode:\n def __init__(self, val, color, left=None, right=None, parent=None):\n self.val = val\n self.color = color # 1 for Red, 0 for... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00008227",
"row_id": 8227,
"seed_ids": "[314]"
} | 0.475739 | Data_Structure_8227 | I | [
"tree_minimum",
"tree_maximum",
"successor",
"predecessor"
] | 4 | [
[
"predecessor",
"tree_maximum"
],
[
"successor",
"tree_minimum"
]
] | 2 | [] | false | [
"RBNode",
"RBTree"
] | true | pytest | true | [] | true | 686f9d90a26d370a6dd375c204a8893f5e815fa6 | 9925fa513f03c6783dca82cdb3291656dbef46b4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8238_I | ### Question: Optimizing GCD Calculation with Enhanced Requirements
You've learned about the Euclid's algorithm and a bitwise variant of it for calculating the Greatest Common Divisor (GCD) of two integers. Now, let's take this a step further. We will enhance the requirements to handle a set of integers and compute th... | from typing import List, Tuple
def gcd_bit(a: int, b: int) -> int:
while b:
a, b = b, a % b
return a
def pairwise_gcd(nums: List[int]) -> List[Tuple[int, int, int]]:
"""
Calculate the GCD for each possible pair of integers in the list.
Parameters:
nums (List[int]): A list of posit... | from solution import pairwise_gcd
def test_pairwise_gcd_example_case():
nums = [10, 15, 25]
result = pairwise_gcd(nums)
expected = [(10, 15, 5), (10, 25, 5), (15, 25, 5)]
assert result == expected
def test_pairwise_gcd_single_element():
nums = [4]
result = pairwise_gcd(nums)
expected = []
... | [
{
"docstring": null,
"function_declaration": "def gcd_bit(a, b):",
"function_name": "gcd_bit",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate the GCD for each possible pair of integers in the list.\n\nParameters:\nnums (List[int]): A list of positive integers\n\nReturns:\nList[Tuple... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef gcd_bit(a: int, b: int) -> int:\n \"\"\"\n Compute the GCD of two integers using bitwise operations.\n \"\"\"\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00008238",
"row_id": 8238,
"seed_ids": "[166]"
} | 0.6841 | Data_Structure_8238 | I | [
"gcd_bit",
"pairwise_gcd"
] | 2 | [
[
"pairwise_gcd",
"gcd_bit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5133babb77b424c9337eb50e43d4249cfa6d7411 | 10129fb0e3cb8d1744ad8f84d7024651dcee8f34 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8283_I | ### Question: Enhanced Insertion Sort for Improved Performance
#### Context
You are working as a software engineer at a tech company where optimal performance of algorithms is crucial. Your team identifies that the existing Insertion Sort algorithm works inefficiently for larger datasets. The goal is to enhance the cu... | def binary_search(arr, val, start, end):
"""
Perform a binary search to find the correct position of an element to be inserted.
"""
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
start = mid + 1
else:
end = mid
return start
def enhance... | from solution import enhanced_insertion_sort
def test_enhanced_insertion_sort_random_list():
assert enhanced_insertion_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
def test_enhanced_insertion_sort_empty_list():
assert enhanced_insertion_sort([]) == []
def test_enhanced_inserti... | [
{
"docstring": "Perform a binary search to find the correct position of an element to be inserted.",
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": "Sorts an array using an enh... | [
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_insertion_sort(arr):\n \"\"\"\n An enhanced version of the insertion sort algorithm using binary search\n to find the correct position f... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00008283",
"row_id": 8283,
"seed_ids": "[7]"
} | 0.536041 | Data_Structure_8283 | I | [
"binary_search",
"enhanced_insertion_sort"
] | 2 | [
[
"enhanced_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 01c9faa097c0b12f2c9c6a641dd5103852a14578 | c01ad6bb15c86f06a746adc80f6c4d7c469e386a | |||
v1.0 | instruct | Data_Structure | Data_Structure_8296_I | You are required to implement a function that checks whether RLE encoded data can be decoded to match a given target string.
### Detailed Description:
You need to write a function `is_match_rle(encoded_data, target_string)` that receives two parameters:
1. `encoded_data`: A string representing the data compressed usi... | def decode_rle(encoded_data):
decoded = []
count = 0
for char in encoded_data:
if char.isdigit():
count = count * 10 + int(char) # Accommodates multi-digit numbers
else:
decoded.append(char * count)
count = 0
return ''.join(decoded)
def is_... | from solution import is_match_rle
def test_is_match_rle_basic_match():
assert is_match_rle("3a2b1c", "aaabbc") == True
def test_is_match_rle_basic_no_match():
assert is_match_rle("3a1b1c", "aaaabc") == False
def test_is_match_rle_empty_strings():
assert is_match_rle("", "") == True
def test_is_match_rle... | [
{
"docstring": null,
"function_declaration": "def decode_rle(encoded_data):",
"function_name": "decode_rle",
"parameter_list": "(encoded_data)"
},
{
"docstring": null,
"function_declaration": "def is_match_rle(encoded_data, target_string):",
"function_name": "is_match_rle",
"para... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_match_rle(encoded_data: str, target_string: str) -> bool:\n \"\"\"\n Checks if the RLE encoded data can be decoded to match the target string.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00008296",
"row_id": 8296,
"seed_ids": "[334]"
} | 0.579452 | Data_Structure_8296 | I | [
"decode_rle",
"is_match_rle"
] | 2 | [
[
"is_match_rle",
"decode_rle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cb556c3551b4b8efd11ea7a57dafd11fc35e80e4 | c2362aa0acc53aed9d358295dfa5e9d36b2595e9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_8414_I | #### Scenario
You are tasked with implementing a sorted insertion method that utilizes binary search to ensure efficiency. This method will help in dynamically building a sorted list by repeatedly inserting new elements while maintaining the list order.
#### Problem Statement
Implement a function `sorted_insertion(lst... | from typing import List
def search_insert(lst: List[int], val: int) -> int:
"""
Helper function to find the insertion point using binary search.
"""
lo, hi = 0, len(lst)
while lo < hi:
mid = (lo + hi) // 2
if lst[mid] < val:
lo = mid + 1
else:
hi = mi... | from solution import sorted_insertion
def test_sorted_insertion_simple():
assert sorted_insertion([1, 3, 5, 6], 2) == [1, 2, 3, 5, 6]
def test_sorted_insertion_middle():
assert sorted_insertion([1, 2, 4, 5, 6], 3) == [1, 2, 3, 4, 5, 6]
def test_sorted_insertion_empty_list():
assert sorted_insertion([], 1... | [
{
"docstring": "Helper function to find the insertion point using binary search.",
"function_declaration": "def search_insert(lst, val):",
"function_name": "search_insert",
"parameter_list": "(lst, val)"
},
{
"docstring": "Inserts val into the sorted list lst while maintaining the order.",
... | [
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 sorted_insertion(lst: List[int], val: int) -> List[int]:\n \"\"\"\n Inserts val into the sorted lst such that lst remains... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00008414",
"row_id": 8414,
"seed_ids": "[199]"
} | 0.56618 | Data_Structure_8414 | I | [
"search_insert",
"sorted_insertion"
] | 2 | [
[
"sorted_insertion",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2318a83c0df978b15fe78f93a72ae7cc80672053 | 010f9f61dbe5a9407760be965fa5c2fb74330aac |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.